babylon.max.js 4.1 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664846658466684667846688466984670846718467284673846748467584676846778467884679846808468184682846838468484685846868468784688846898469084691846928469384694846958469684697846988469984700847018470284703847048470584706847078470884709847108471184712847138471484715847168471784718847198472084721847228472384724847258472684727847288472984730847318473284733847348473584736847378473884739847408474184742847438474484745847468474784748847498475084751847528475384754847558475684757847588475984760847618476284763847648476584766847678476884769847708477184772847738477484775847768477784778847798478084781847828478384784847858478684787847888478984790847918479284793847948479584796847978479884799848008480184802848038480484805848068480784808848098481084811848128481384814848158481684817848188481984820848218482284823848248482584826848278482884829848308483184832848338483484835848368483784838848398484084841848428484384844848458484684847848488484984850848518485284853848548485584856848578485884859848608486184862848638486484865848668486784868848698487084871848728487384874848758487684877848788487984880848818488284883848848488584886848878488884889848908489184892848938489484895848968489784898848998490084901849028490384904849058490684907849088490984910849118491284913849148491584916849178491884919849208492184922849238492484925849268492784928849298493084931849328493384934849358493684937849388493984940849418494284943849448494584946849478494884949849508495184952849538495484955849568495784958849598496084961849628496384964849658496684967849688496984970849718497284973849748497584976849778497884979849808498184982849838498484985849868498784988849898499084991849928499384994849958499684997849988499985000850018500285003850048500585006850078500885009850108501185012850138501485015850168501785018850198502085021850228502385024850258502685027850288502985030850318503285033850348503585036850378503885039850408504185042850438504485045850468504785048850498505085051850528505385054850558505685057850588505985060850618506285063850648506585066850678506885069850708507185072850738507485075850768507785078850798508085081850828508385084850858508685087850888508985090850918509285093850948509585096850978509885099851008510185102851038510485105851068510785108851098511085111851128511385114851158511685117851188511985120851218512285123851248512585126851278512885129851308513185132851338513485135851368513785138851398514085141851428514385144851458514685147851488514985150851518515285153851548515585156851578515885159851608516185162851638516485165851668516785168851698517085171851728517385174851758517685177851788517985180851818518285183851848518585186851878518885189851908519185192851938519485195851968519785198851998520085201852028520385204852058520685207852088520985210852118521285213852148521585216
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. //# sourceMappingURL=babylon.types.js.map
  18. var BABYLON;
  19. (function (BABYLON) {
  20. var KeyboardEventTypes = /** @class */ (function () {
  21. function KeyboardEventTypes() {
  22. }
  23. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  24. get: function () {
  25. return KeyboardEventTypes._KEYDOWN;
  26. },
  27. enumerable: true,
  28. configurable: true
  29. });
  30. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  31. get: function () {
  32. return KeyboardEventTypes._KEYUP;
  33. },
  34. enumerable: true,
  35. configurable: true
  36. });
  37. KeyboardEventTypes._KEYDOWN = 0x01;
  38. KeyboardEventTypes._KEYUP = 0x02;
  39. return KeyboardEventTypes;
  40. }());
  41. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  42. var KeyboardInfo = /** @class */ (function () {
  43. function KeyboardInfo(type, event) {
  44. this.type = type;
  45. this.event = event;
  46. }
  47. return KeyboardInfo;
  48. }());
  49. BABYLON.KeyboardInfo = KeyboardInfo;
  50. /**
  51. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  52. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  53. */
  54. var KeyboardInfoPre = /** @class */ (function (_super) {
  55. __extends(KeyboardInfoPre, _super);
  56. function KeyboardInfoPre(type, event) {
  57. var _this = _super.call(this, type, event) || this;
  58. _this.skipOnPointerObservable = false;
  59. return _this;
  60. }
  61. return KeyboardInfoPre;
  62. }(KeyboardInfo));
  63. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  64. })(BABYLON || (BABYLON = {}));
  65. //# sourceMappingURL=babylon.keyboardEvents.js.map
  66. var BABYLON;
  67. (function (BABYLON) {
  68. var PointerEventTypes = /** @class */ (function () {
  69. function PointerEventTypes() {
  70. }
  71. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  72. get: function () {
  73. return PointerEventTypes._POINTERDOWN;
  74. },
  75. enumerable: true,
  76. configurable: true
  77. });
  78. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  79. get: function () {
  80. return PointerEventTypes._POINTERUP;
  81. },
  82. enumerable: true,
  83. configurable: true
  84. });
  85. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  86. get: function () {
  87. return PointerEventTypes._POINTERMOVE;
  88. },
  89. enumerable: true,
  90. configurable: true
  91. });
  92. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  93. get: function () {
  94. return PointerEventTypes._POINTERWHEEL;
  95. },
  96. enumerable: true,
  97. configurable: true
  98. });
  99. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  100. get: function () {
  101. return PointerEventTypes._POINTERPICK;
  102. },
  103. enumerable: true,
  104. configurable: true
  105. });
  106. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  107. get: function () {
  108. return PointerEventTypes._POINTERTAP;
  109. },
  110. enumerable: true,
  111. configurable: true
  112. });
  113. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  114. get: function () {
  115. return PointerEventTypes._POINTERDOUBLETAP;
  116. },
  117. enumerable: true,
  118. configurable: true
  119. });
  120. PointerEventTypes._POINTERDOWN = 0x01;
  121. PointerEventTypes._POINTERUP = 0x02;
  122. PointerEventTypes._POINTERMOVE = 0x04;
  123. PointerEventTypes._POINTERWHEEL = 0x08;
  124. PointerEventTypes._POINTERPICK = 0x10;
  125. PointerEventTypes._POINTERTAP = 0x20;
  126. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  127. return PointerEventTypes;
  128. }());
  129. BABYLON.PointerEventTypes = PointerEventTypes;
  130. var PointerInfoBase = /** @class */ (function () {
  131. function PointerInfoBase(type, event) {
  132. this.type = type;
  133. this.event = event;
  134. }
  135. return PointerInfoBase;
  136. }());
  137. BABYLON.PointerInfoBase = PointerInfoBase;
  138. /**
  139. * This class is used to store pointer related info for the onPrePointerObservable event.
  140. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  141. */
  142. var PointerInfoPre = /** @class */ (function (_super) {
  143. __extends(PointerInfoPre, _super);
  144. function PointerInfoPre(type, event, localX, localY) {
  145. var _this = _super.call(this, type, event) || this;
  146. _this.skipOnPointerObservable = false;
  147. _this.localPosition = new BABYLON.Vector2(localX, localY);
  148. return _this;
  149. }
  150. return PointerInfoPre;
  151. }(PointerInfoBase));
  152. BABYLON.PointerInfoPre = PointerInfoPre;
  153. /**
  154. * This type contains all the data related to a pointer event in Babylon.js.
  155. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  156. */
  157. var PointerInfo = /** @class */ (function (_super) {
  158. __extends(PointerInfo, _super);
  159. function PointerInfo(type, event, pickInfo) {
  160. var _this = _super.call(this, type, event) || this;
  161. _this.pickInfo = pickInfo;
  162. return _this;
  163. }
  164. return PointerInfo;
  165. }(PointerInfoBase));
  166. BABYLON.PointerInfo = PointerInfo;
  167. })(BABYLON || (BABYLON = {}));
  168. //# sourceMappingURL=babylon.pointerEvents.js.map
  169. var BABYLON;
  170. (function (BABYLON) {
  171. BABYLON.ToGammaSpace = 1 / 2.2;
  172. BABYLON.ToLinearSpace = 2.2;
  173. BABYLON.Epsilon = 0.001;
  174. var Color3 = /** @class */ (function () {
  175. /**
  176. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  177. */
  178. function Color3(r, g, b) {
  179. if (r === void 0) { r = 0; }
  180. if (g === void 0) { g = 0; }
  181. if (b === void 0) { b = 0; }
  182. this.r = r;
  183. this.g = g;
  184. this.b = b;
  185. }
  186. /**
  187. * Returns a string with the Color3 current values.
  188. */
  189. Color3.prototype.toString = function () {
  190. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  191. };
  192. /**
  193. * Returns the string "Color3".
  194. */
  195. Color3.prototype.getClassName = function () {
  196. return "Color3";
  197. };
  198. /**
  199. * Returns the Color3 hash code.
  200. */
  201. Color3.prototype.getHashCode = function () {
  202. var hash = this.r || 0;
  203. hash = (hash * 397) ^ (this.g || 0);
  204. hash = (hash * 397) ^ (this.b || 0);
  205. return hash;
  206. };
  207. // Operators
  208. /**
  209. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  210. * Returns the Color3.
  211. */
  212. Color3.prototype.toArray = function (array, index) {
  213. if (index === undefined) {
  214. index = 0;
  215. }
  216. array[index] = this.r;
  217. array[index + 1] = this.g;
  218. array[index + 2] = this.b;
  219. return this;
  220. };
  221. /**
  222. * Returns a new Color4 object from the current Color3 and the passed alpha.
  223. */
  224. Color3.prototype.toColor4 = function (alpha) {
  225. if (alpha === void 0) { alpha = 1; }
  226. return new Color4(this.r, this.g, this.b, alpha);
  227. };
  228. /**
  229. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  230. */
  231. Color3.prototype.asArray = function () {
  232. var result = new Array();
  233. this.toArray(result, 0);
  234. return result;
  235. };
  236. /**
  237. * Returns the luminance value (float).
  238. */
  239. Color3.prototype.toLuminance = function () {
  240. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  241. };
  242. /**
  243. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  244. * Returns this new object.
  245. */
  246. Color3.prototype.multiply = function (otherColor) {
  247. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  248. };
  249. /**
  250. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  251. * Returns the current Color3.
  252. */
  253. Color3.prototype.multiplyToRef = function (otherColor, result) {
  254. result.r = this.r * otherColor.r;
  255. result.g = this.g * otherColor.g;
  256. result.b = this.b * otherColor.b;
  257. return this;
  258. };
  259. /**
  260. * Boolean : True if the rgb values are equal to the passed ones.
  261. */
  262. Color3.prototype.equals = function (otherColor) {
  263. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  264. };
  265. /**
  266. * Boolean : True if the rgb values are equal to the passed ones.
  267. */
  268. Color3.prototype.equalsFloats = function (r, g, b) {
  269. return this.r === r && this.g === g && this.b === b;
  270. };
  271. /**
  272. * Multiplies in place each rgb value by scale.
  273. * Returns the updated Color3.
  274. */
  275. Color3.prototype.scale = function (scale) {
  276. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  277. };
  278. /**
  279. * Multiplies the rgb values by scale and stores the result into "result".
  280. * Returns the unmodified current Color3.
  281. */
  282. Color3.prototype.scaleToRef = function (scale, result) {
  283. result.r = this.r * scale;
  284. result.g = this.g * scale;
  285. result.b = this.b * scale;
  286. return this;
  287. };
  288. /**
  289. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  290. */
  291. Color3.prototype.add = function (otherColor) {
  292. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  293. };
  294. /**
  295. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  296. * Returns the unmodified current Color3.
  297. */
  298. Color3.prototype.addToRef = function (otherColor, result) {
  299. result.r = this.r + otherColor.r;
  300. result.g = this.g + otherColor.g;
  301. result.b = this.b + otherColor.b;
  302. return this;
  303. };
  304. /**
  305. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  306. */
  307. Color3.prototype.subtract = function (otherColor) {
  308. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  309. };
  310. /**
  311. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  312. * Returns the unmodified current Color3.
  313. */
  314. Color3.prototype.subtractToRef = function (otherColor, result) {
  315. result.r = this.r - otherColor.r;
  316. result.g = this.g - otherColor.g;
  317. result.b = this.b - otherColor.b;
  318. return this;
  319. };
  320. /**
  321. * Returns a new Color3 copied the current one.
  322. */
  323. Color3.prototype.clone = function () {
  324. return new Color3(this.r, this.g, this.b);
  325. };
  326. /**
  327. * Copies the rgb values from the source in the current Color3.
  328. * Returns the updated Color3.
  329. */
  330. Color3.prototype.copyFrom = function (source) {
  331. this.r = source.r;
  332. this.g = source.g;
  333. this.b = source.b;
  334. return this;
  335. };
  336. /**
  337. * Updates the Color3 rgb values from the passed floats.
  338. * Returns the Color3.
  339. */
  340. Color3.prototype.copyFromFloats = function (r, g, b) {
  341. this.r = r;
  342. this.g = g;
  343. this.b = b;
  344. return this;
  345. };
  346. /**
  347. * Updates the Color3 rgb values from the passed floats.
  348. * Returns the Color3.
  349. */
  350. Color3.prototype.set = function (r, g, b) {
  351. return this.copyFromFloats(r, g, b);
  352. };
  353. /**
  354. * Returns the Color3 hexadecimal code as a string.
  355. */
  356. Color3.prototype.toHexString = function () {
  357. var intR = (this.r * 255) | 0;
  358. var intG = (this.g * 255) | 0;
  359. var intB = (this.b * 255) | 0;
  360. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  361. };
  362. /**
  363. * Returns a new Color3 converted to linear space.
  364. */
  365. Color3.prototype.toLinearSpace = function () {
  366. var convertedColor = new Color3();
  367. this.toLinearSpaceToRef(convertedColor);
  368. return convertedColor;
  369. };
  370. /**
  371. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  372. * Returns the unmodified Color3.
  373. */
  374. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  375. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  376. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  377. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  378. return this;
  379. };
  380. /**
  381. * Returns a new Color3 converted to gamma space.
  382. */
  383. Color3.prototype.toGammaSpace = function () {
  384. var convertedColor = new Color3();
  385. this.toGammaSpaceToRef(convertedColor);
  386. return convertedColor;
  387. };
  388. /**
  389. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  390. * Returns the unmodified Color3.
  391. */
  392. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  393. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  394. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  395. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  396. return this;
  397. };
  398. // Statics
  399. /**
  400. * Creates a new Color3 from the string containing valid hexadecimal values.
  401. */
  402. Color3.FromHexString = function (hex) {
  403. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  404. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  405. return new Color3(0, 0, 0);
  406. }
  407. var r = parseInt(hex.substring(1, 3), 16);
  408. var g = parseInt(hex.substring(3, 5), 16);
  409. var b = parseInt(hex.substring(5, 7), 16);
  410. return Color3.FromInts(r, g, b);
  411. };
  412. /**
  413. * Creates a new Vector3 from the startind index of the passed array.
  414. */
  415. Color3.FromArray = function (array, offset) {
  416. if (offset === void 0) { offset = 0; }
  417. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  418. };
  419. /**
  420. * Creates a new Color3 from integer values ( < 256).
  421. */
  422. Color3.FromInts = function (r, g, b) {
  423. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  424. };
  425. /**
  426. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  427. */
  428. Color3.Lerp = function (start, end, amount) {
  429. var r = start.r + ((end.r - start.r) * amount);
  430. var g = start.g + ((end.g - start.g) * amount);
  431. var b = start.b + ((end.b - start.b) * amount);
  432. return new Color3(r, g, b);
  433. };
  434. Color3.Red = function () { return new Color3(1, 0, 0); };
  435. Color3.Green = function () { return new Color3(0, 1, 0); };
  436. Color3.Blue = function () { return new Color3(0, 0, 1); };
  437. Color3.Black = function () { return new Color3(0, 0, 0); };
  438. Color3.White = function () { return new Color3(1, 1, 1); };
  439. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  440. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  441. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  442. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  443. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  444. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  445. return Color3;
  446. }());
  447. BABYLON.Color3 = Color3;
  448. var Color4 = /** @class */ (function () {
  449. /**
  450. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  451. */
  452. function Color4(r, g, b, a) {
  453. if (r === void 0) { r = 0; }
  454. if (g === void 0) { g = 0; }
  455. if (b === void 0) { b = 0; }
  456. if (a === void 0) { a = 1; }
  457. this.r = r;
  458. this.g = g;
  459. this.b = b;
  460. this.a = a;
  461. }
  462. // Operators
  463. /**
  464. * Adds in place the passed Color4 values to the current Color4.
  465. * Returns the updated Color4.
  466. */
  467. Color4.prototype.addInPlace = function (right) {
  468. this.r += right.r;
  469. this.g += right.g;
  470. this.b += right.b;
  471. this.a += right.a;
  472. return this;
  473. };
  474. /**
  475. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  476. */
  477. Color4.prototype.asArray = function () {
  478. var result = new Array();
  479. this.toArray(result, 0);
  480. return result;
  481. };
  482. /**
  483. * Stores from the starting index in the passed array the Color4 successive values.
  484. * Returns the Color4.
  485. */
  486. Color4.prototype.toArray = function (array, index) {
  487. if (index === undefined) {
  488. index = 0;
  489. }
  490. array[index] = this.r;
  491. array[index + 1] = this.g;
  492. array[index + 2] = this.b;
  493. array[index + 3] = this.a;
  494. return this;
  495. };
  496. /**
  497. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  498. */
  499. Color4.prototype.add = function (right) {
  500. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  501. };
  502. /**
  503. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  504. */
  505. Color4.prototype.subtract = function (right) {
  506. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  507. };
  508. /**
  509. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  510. * Returns the Color4.
  511. */
  512. Color4.prototype.subtractToRef = function (right, result) {
  513. result.r = this.r - right.r;
  514. result.g = this.g - right.g;
  515. result.b = this.b - right.b;
  516. result.a = this.a - right.a;
  517. return this;
  518. };
  519. /**
  520. * Creates a new Color4 with the current Color4 values multiplied by scale.
  521. */
  522. Color4.prototype.scale = function (scale) {
  523. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  524. };
  525. /**
  526. * Multiplies the current Color4 values by scale and stores the result in "result".
  527. * Returns the Color4.
  528. */
  529. Color4.prototype.scaleToRef = function (scale, result) {
  530. result.r = this.r * scale;
  531. result.g = this.g * scale;
  532. result.b = this.b * scale;
  533. result.a = this.a * scale;
  534. return this;
  535. };
  536. /**
  537. * Multipy an RGBA Color4 value by another and return a new Color4 object
  538. * @param color The Color4 (RGBA) value to multiply by
  539. * @returns A new Color4.
  540. */
  541. Color4.prototype.multiply = function (color) {
  542. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  543. };
  544. /**
  545. * Multipy an RGBA Color4 value by another and push the result in a reference value
  546. * @param color The Color4 (RGBA) value to multiply by
  547. * @param result The Color4 (RGBA) to fill the result in
  548. * @returns the result Color4.
  549. */
  550. Color4.prototype.multiplyToRef = function (color, result) {
  551. result.r = this.r * color.r;
  552. result.g = this.g * color.g;
  553. result.b = this.b * color.b;
  554. result.a = this.a * color.a;
  555. return result;
  556. };
  557. /**
  558. * Returns a string with the Color4 values.
  559. */
  560. Color4.prototype.toString = function () {
  561. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  562. };
  563. /**
  564. * Returns the string "Color4"
  565. */
  566. Color4.prototype.getClassName = function () {
  567. return "Color4";
  568. };
  569. /**
  570. * Return the Color4 hash code as a number.
  571. */
  572. Color4.prototype.getHashCode = function () {
  573. var hash = this.r || 0;
  574. hash = (hash * 397) ^ (this.g || 0);
  575. hash = (hash * 397) ^ (this.b || 0);
  576. hash = (hash * 397) ^ (this.a || 0);
  577. return hash;
  578. };
  579. /**
  580. * Creates a new Color4 copied from the current one.
  581. */
  582. Color4.prototype.clone = function () {
  583. return new Color4(this.r, this.g, this.b, this.a);
  584. };
  585. /**
  586. * Copies the passed Color4 values into the current one.
  587. * Returns the updated Color4.
  588. */
  589. Color4.prototype.copyFrom = function (source) {
  590. this.r = source.r;
  591. this.g = source.g;
  592. this.b = source.b;
  593. this.a = source.a;
  594. return this;
  595. };
  596. /**
  597. * Copies the passed float values into the current one.
  598. * Returns the updated Color4.
  599. */
  600. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  601. this.r = r;
  602. this.g = g;
  603. this.b = b;
  604. this.a = a;
  605. return this;
  606. };
  607. /**
  608. * Copies the passed float values into the current one.
  609. * Returns the updated Color4.
  610. */
  611. Color4.prototype.set = function (r, g, b, a) {
  612. return this.copyFromFloats(r, g, b, a);
  613. };
  614. /**
  615. * Returns a string containing the hexadecimal Color4 code.
  616. */
  617. Color4.prototype.toHexString = function () {
  618. var intR = (this.r * 255) | 0;
  619. var intG = (this.g * 255) | 0;
  620. var intB = (this.b * 255) | 0;
  621. var intA = (this.a * 255) | 0;
  622. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  623. };
  624. /**
  625. * Returns a new Color4 converted to linear space.
  626. */
  627. Color4.prototype.toLinearSpace = function () {
  628. var convertedColor = new Color4();
  629. this.toLinearSpaceToRef(convertedColor);
  630. return convertedColor;
  631. };
  632. /**
  633. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  634. * Returns the unmodified Color4.
  635. */
  636. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  637. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  638. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  639. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  640. convertedColor.a = this.a;
  641. return this;
  642. };
  643. /**
  644. * Returns a new Color4 converted to gamma space.
  645. */
  646. Color4.prototype.toGammaSpace = function () {
  647. var convertedColor = new Color4();
  648. this.toGammaSpaceToRef(convertedColor);
  649. return convertedColor;
  650. };
  651. /**
  652. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  653. * Returns the unmodified Color4.
  654. */
  655. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  656. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  657. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  658. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  659. convertedColor.a = this.a;
  660. return this;
  661. };
  662. // Statics
  663. /**
  664. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  665. */
  666. Color4.FromHexString = function (hex) {
  667. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  668. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  669. return new Color4(0.0, 0.0, 0.0, 0.0);
  670. }
  671. var r = parseInt(hex.substring(1, 3), 16);
  672. var g = parseInt(hex.substring(3, 5), 16);
  673. var b = parseInt(hex.substring(5, 7), 16);
  674. var a = parseInt(hex.substring(7, 9), 16);
  675. return Color4.FromInts(r, g, b, a);
  676. };
  677. /**
  678. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  679. */
  680. Color4.Lerp = function (left, right, amount) {
  681. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  682. Color4.LerpToRef(left, right, amount, result);
  683. return result;
  684. };
  685. /**
  686. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  687. */
  688. Color4.LerpToRef = function (left, right, amount, result) {
  689. result.r = left.r + (right.r - left.r) * amount;
  690. result.g = left.g + (right.g - left.g) * amount;
  691. result.b = left.b + (right.b - left.b) * amount;
  692. result.a = left.a + (right.a - left.a) * amount;
  693. };
  694. /**
  695. * Creates a new Color4 from the starting index element of the passed array.
  696. */
  697. Color4.FromArray = function (array, offset) {
  698. if (offset === void 0) { offset = 0; }
  699. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  700. };
  701. /**
  702. * Creates a new Color4 from the passed integers ( < 256 ).
  703. */
  704. Color4.FromInts = function (r, g, b, a) {
  705. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  706. };
  707. Color4.CheckColors4 = function (colors, count) {
  708. // Check if color3 was used
  709. if (colors.length === count * 3) {
  710. var colors4 = [];
  711. for (var index = 0; index < colors.length; index += 3) {
  712. var newIndex = (index / 3) * 4;
  713. colors4[newIndex] = colors[index];
  714. colors4[newIndex + 1] = colors[index + 1];
  715. colors4[newIndex + 2] = colors[index + 2];
  716. colors4[newIndex + 3] = 1.0;
  717. }
  718. return colors4;
  719. }
  720. return colors;
  721. };
  722. return Color4;
  723. }());
  724. BABYLON.Color4 = Color4;
  725. var Vector2 = /** @class */ (function () {
  726. /**
  727. * Creates a new Vector2 from the passed x and y coordinates.
  728. */
  729. function Vector2(x, y) {
  730. this.x = x;
  731. this.y = y;
  732. }
  733. /**
  734. * Returns a string with the Vector2 coordinates.
  735. */
  736. Vector2.prototype.toString = function () {
  737. return "{X: " + this.x + " Y:" + this.y + "}";
  738. };
  739. /**
  740. * Returns the string "Vector2"
  741. */
  742. Vector2.prototype.getClassName = function () {
  743. return "Vector2";
  744. };
  745. /**
  746. * Returns the Vector2 hash code as a number.
  747. */
  748. Vector2.prototype.getHashCode = function () {
  749. var hash = this.x || 0;
  750. hash = (hash * 397) ^ (this.y || 0);
  751. return hash;
  752. };
  753. // Operators
  754. /**
  755. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  756. * Returns the Vector2.
  757. */
  758. Vector2.prototype.toArray = function (array, index) {
  759. if (index === void 0) { index = 0; }
  760. array[index] = this.x;
  761. array[index + 1] = this.y;
  762. return this;
  763. };
  764. /**
  765. * Returns a new array with 2 elements : the Vector2 coordinates.
  766. */
  767. Vector2.prototype.asArray = function () {
  768. var result = new Array();
  769. this.toArray(result, 0);
  770. return result;
  771. };
  772. /**
  773. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  774. * Returns the updated Vector2.
  775. */
  776. Vector2.prototype.copyFrom = function (source) {
  777. this.x = source.x;
  778. this.y = source.y;
  779. return this;
  780. };
  781. /**
  782. * Sets the Vector2 coordinates with the passed floats.
  783. * Returns the updated Vector2.
  784. */
  785. Vector2.prototype.copyFromFloats = function (x, y) {
  786. this.x = x;
  787. this.y = y;
  788. return this;
  789. };
  790. /**
  791. * Sets the Vector2 coordinates with the passed floats.
  792. * Returns the updated Vector2.
  793. */
  794. Vector2.prototype.set = function (x, y) {
  795. return this.copyFromFloats(x, y);
  796. };
  797. /**
  798. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  799. */
  800. Vector2.prototype.add = function (otherVector) {
  801. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  802. };
  803. /**
  804. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  805. * Returns the Vector2.
  806. */
  807. Vector2.prototype.addToRef = function (otherVector, result) {
  808. result.x = this.x + otherVector.x;
  809. result.y = this.y + otherVector.y;
  810. return this;
  811. };
  812. /**
  813. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  814. * Returns the updated Vector2.
  815. */
  816. Vector2.prototype.addInPlace = function (otherVector) {
  817. this.x += otherVector.x;
  818. this.y += otherVector.y;
  819. return this;
  820. };
  821. /**
  822. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  823. */
  824. Vector2.prototype.addVector3 = function (otherVector) {
  825. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  826. };
  827. /**
  828. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  829. */
  830. Vector2.prototype.subtract = function (otherVector) {
  831. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  832. };
  833. /**
  834. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  835. * Returns the Vector2.
  836. */
  837. Vector2.prototype.subtractToRef = function (otherVector, result) {
  838. result.x = this.x - otherVector.x;
  839. result.y = this.y - otherVector.y;
  840. return this;
  841. };
  842. /**
  843. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  844. * Returns the updated Vector2.
  845. */
  846. Vector2.prototype.subtractInPlace = function (otherVector) {
  847. this.x -= otherVector.x;
  848. this.y -= otherVector.y;
  849. return this;
  850. };
  851. /**
  852. * Multiplies in place the current Vector2 coordinates by the passed ones.
  853. * Returns the updated Vector2.
  854. */
  855. Vector2.prototype.multiplyInPlace = function (otherVector) {
  856. this.x *= otherVector.x;
  857. this.y *= otherVector.y;
  858. return this;
  859. };
  860. /**
  861. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  862. */
  863. Vector2.prototype.multiply = function (otherVector) {
  864. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  865. };
  866. /**
  867. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  868. * Returns the Vector2.
  869. */
  870. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  871. result.x = this.x * otherVector.x;
  872. result.y = this.y * otherVector.y;
  873. return this;
  874. };
  875. /**
  876. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  877. */
  878. Vector2.prototype.multiplyByFloats = function (x, y) {
  879. return new Vector2(this.x * x, this.y * y);
  880. };
  881. /**
  882. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  883. */
  884. Vector2.prototype.divide = function (otherVector) {
  885. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  886. };
  887. /**
  888. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  889. * Returns the Vector2.
  890. */
  891. Vector2.prototype.divideToRef = function (otherVector, result) {
  892. result.x = this.x / otherVector.x;
  893. result.y = this.y / otherVector.y;
  894. return this;
  895. };
  896. /**
  897. * Returns a new Vector2 with current Vector2 negated coordinates.
  898. */
  899. Vector2.prototype.negate = function () {
  900. return new Vector2(-this.x, -this.y);
  901. };
  902. /**
  903. * Multiply the Vector2 coordinates by scale.
  904. * Returns the updated Vector2.
  905. */
  906. Vector2.prototype.scaleInPlace = function (scale) {
  907. this.x *= scale;
  908. this.y *= scale;
  909. return this;
  910. };
  911. /**
  912. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  913. */
  914. Vector2.prototype.scale = function (scale) {
  915. return new Vector2(this.x * scale, this.y * scale);
  916. };
  917. /**
  918. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  919. */
  920. Vector2.prototype.equals = function (otherVector) {
  921. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  922. };
  923. /**
  924. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  925. */
  926. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  927. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  928. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  929. };
  930. // Properties
  931. /**
  932. * Returns the vector length (float).
  933. */
  934. Vector2.prototype.length = function () {
  935. return Math.sqrt(this.x * this.x + this.y * this.y);
  936. };
  937. /**
  938. * Returns the vector squared length (float);
  939. */
  940. Vector2.prototype.lengthSquared = function () {
  941. return (this.x * this.x + this.y * this.y);
  942. };
  943. // Methods
  944. /**
  945. * Normalize the vector.
  946. * Returns the updated Vector2.
  947. */
  948. Vector2.prototype.normalize = function () {
  949. var len = this.length();
  950. if (len === 0)
  951. return this;
  952. var num = 1.0 / len;
  953. this.x *= num;
  954. this.y *= num;
  955. return this;
  956. };
  957. /**
  958. * Returns a new Vector2 copied from the Vector2.
  959. */
  960. Vector2.prototype.clone = function () {
  961. return new Vector2(this.x, this.y);
  962. };
  963. // Statics
  964. /**
  965. * Returns a new Vector2(0, 0)
  966. */
  967. Vector2.Zero = function () {
  968. return new Vector2(0, 0);
  969. };
  970. /**
  971. * Returns a new Vector2(1, 1)
  972. */
  973. Vector2.One = function () {
  974. return new Vector2(1, 1);
  975. };
  976. /**
  977. * Returns a new Vector2 set from the passed index element of the passed array.
  978. */
  979. Vector2.FromArray = function (array, offset) {
  980. if (offset === void 0) { offset = 0; }
  981. return new Vector2(array[offset], array[offset + 1]);
  982. };
  983. /**
  984. * Sets "result" from the passed index element of the passed array.
  985. */
  986. Vector2.FromArrayToRef = function (array, offset, result) {
  987. result.x = array[offset];
  988. result.y = array[offset + 1];
  989. };
  990. /**
  991. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  992. */
  993. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  994. var squared = amount * amount;
  995. var cubed = amount * squared;
  996. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  997. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  998. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  999. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1000. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1001. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1002. return new Vector2(x, y);
  1003. };
  1004. /**
  1005. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  1006. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  1007. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  1008. */
  1009. Vector2.Clamp = function (value, min, max) {
  1010. var x = value.x;
  1011. x = (x > max.x) ? max.x : x;
  1012. x = (x < min.x) ? min.x : x;
  1013. var y = value.y;
  1014. y = (y > max.y) ? max.y : y;
  1015. y = (y < min.y) ? min.y : y;
  1016. return new Vector2(x, y);
  1017. };
  1018. /**
  1019. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  1020. */
  1021. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1022. var squared = amount * amount;
  1023. var cubed = amount * squared;
  1024. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1025. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1026. var part3 = (cubed - (2.0 * squared)) + amount;
  1027. var part4 = cubed - squared;
  1028. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1029. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1030. return new Vector2(x, y);
  1031. };
  1032. /**
  1033. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  1034. */
  1035. Vector2.Lerp = function (start, end, amount) {
  1036. var x = start.x + ((end.x - start.x) * amount);
  1037. var y = start.y + ((end.y - start.y) * amount);
  1038. return new Vector2(x, y);
  1039. };
  1040. /**
  1041. * Returns the dot product (float) of the vector "left" and the vector "right".
  1042. */
  1043. Vector2.Dot = function (left, right) {
  1044. return left.x * right.x + left.y * right.y;
  1045. };
  1046. /**
  1047. * Returns a new Vector2 equal to the normalized passed vector.
  1048. */
  1049. Vector2.Normalize = function (vector) {
  1050. var newVector = vector.clone();
  1051. newVector.normalize();
  1052. return newVector;
  1053. };
  1054. /**
  1055. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  1056. */
  1057. Vector2.Minimize = function (left, right) {
  1058. var x = (left.x < right.x) ? left.x : right.x;
  1059. var y = (left.y < right.y) ? left.y : right.y;
  1060. return new Vector2(x, y);
  1061. };
  1062. /**
  1063. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  1064. */
  1065. Vector2.Maximize = function (left, right) {
  1066. var x = (left.x > right.x) ? left.x : right.x;
  1067. var y = (left.y > right.y) ? left.y : right.y;
  1068. return new Vector2(x, y);
  1069. };
  1070. /**
  1071. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  1072. */
  1073. Vector2.Transform = function (vector, transformation) {
  1074. var r = Vector2.Zero();
  1075. Vector2.TransformToRef(vector, transformation, r);
  1076. return r;
  1077. };
  1078. /**
  1079. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  1080. */
  1081. Vector2.TransformToRef = function (vector, transformation, result) {
  1082. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  1083. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  1084. result.x = x;
  1085. result.y = y;
  1086. };
  1087. /**
  1088. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  1089. */
  1090. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  1091. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  1092. var sign = a < 0 ? -1 : 1;
  1093. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  1094. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  1095. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  1096. };
  1097. /**
  1098. * Returns the distance (float) between the vectors "value1" and "value2".
  1099. */
  1100. Vector2.Distance = function (value1, value2) {
  1101. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  1102. };
  1103. /**
  1104. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1105. */
  1106. Vector2.DistanceSquared = function (value1, value2) {
  1107. var x = value1.x - value2.x;
  1108. var y = value1.y - value2.y;
  1109. return (x * x) + (y * y);
  1110. };
  1111. /**
  1112. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  1113. */
  1114. Vector2.Center = function (value1, value2) {
  1115. var center = value1.add(value2);
  1116. center.scaleInPlace(0.5);
  1117. return center;
  1118. };
  1119. /**
  1120. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1121. */
  1122. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  1123. var l2 = Vector2.DistanceSquared(segA, segB);
  1124. if (l2 === 0.0) {
  1125. return Vector2.Distance(p, segA);
  1126. }
  1127. var v = segB.subtract(segA);
  1128. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1129. var proj = segA.add(v.multiplyByFloats(t, t));
  1130. return Vector2.Distance(p, proj);
  1131. };
  1132. return Vector2;
  1133. }());
  1134. BABYLON.Vector2 = Vector2;
  1135. var Vector3 = /** @class */ (function () {
  1136. /**
  1137. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1138. * A Vector3 is the main object used in 3D geometry.
  1139. * It can represent etiher the coordinates of a point the space, either a direction.
  1140. */
  1141. function Vector3(x, y, z) {
  1142. this.x = x;
  1143. this.y = y;
  1144. this.z = z;
  1145. }
  1146. /**
  1147. * Returns a string with the Vector3 coordinates.
  1148. */
  1149. Vector3.prototype.toString = function () {
  1150. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1151. };
  1152. /**
  1153. * Returns the string "Vector3"
  1154. */
  1155. Vector3.prototype.getClassName = function () {
  1156. return "Vector3";
  1157. };
  1158. /**
  1159. * Returns the Vector hash code.
  1160. */
  1161. Vector3.prototype.getHashCode = function () {
  1162. var hash = this.x || 0;
  1163. hash = (hash * 397) ^ (this.y || 0);
  1164. hash = (hash * 397) ^ (this.z || 0);
  1165. return hash;
  1166. };
  1167. // Operators
  1168. /**
  1169. * Returns a new array with three elements : the coordinates the Vector3.
  1170. */
  1171. Vector3.prototype.asArray = function () {
  1172. var result = [];
  1173. this.toArray(result, 0);
  1174. return result;
  1175. };
  1176. /**
  1177. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1178. * Returns the Vector3.
  1179. */
  1180. Vector3.prototype.toArray = function (array, index) {
  1181. if (index === void 0) { index = 0; }
  1182. array[index] = this.x;
  1183. array[index + 1] = this.y;
  1184. array[index + 2] = this.z;
  1185. return this;
  1186. };
  1187. /**
  1188. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1189. */
  1190. Vector3.prototype.toQuaternion = function () {
  1191. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1192. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1193. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1194. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1195. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1196. var cosy = Math.cos(this.y * 0.5);
  1197. var siny = Math.sin(this.y * 0.5);
  1198. result.x = coszMinusx * siny;
  1199. result.y = -sinzMinusx * siny;
  1200. result.z = sinxPlusz * cosy;
  1201. result.w = cosxPlusz * cosy;
  1202. return result;
  1203. };
  1204. /**
  1205. * Adds the passed vector to the current Vector3.
  1206. * Returns the updated Vector3.
  1207. */
  1208. Vector3.prototype.addInPlace = function (otherVector) {
  1209. this.x += otherVector.x;
  1210. this.y += otherVector.y;
  1211. this.z += otherVector.z;
  1212. return this;
  1213. };
  1214. /**
  1215. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1216. */
  1217. Vector3.prototype.add = function (otherVector) {
  1218. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1219. };
  1220. /**
  1221. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1222. * Returns the current Vector3.
  1223. */
  1224. Vector3.prototype.addToRef = function (otherVector, result) {
  1225. result.x = this.x + otherVector.x;
  1226. result.y = this.y + otherVector.y;
  1227. result.z = this.z + otherVector.z;
  1228. return this;
  1229. };
  1230. /**
  1231. * Subtract the passed vector from the current Vector3.
  1232. * Returns the updated Vector3.
  1233. */
  1234. Vector3.prototype.subtractInPlace = function (otherVector) {
  1235. this.x -= otherVector.x;
  1236. this.y -= otherVector.y;
  1237. this.z -= otherVector.z;
  1238. return this;
  1239. };
  1240. /**
  1241. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1242. */
  1243. Vector3.prototype.subtract = function (otherVector) {
  1244. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1245. };
  1246. /**
  1247. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1248. * Returns the current Vector3.
  1249. */
  1250. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1251. result.x = this.x - otherVector.x;
  1252. result.y = this.y - otherVector.y;
  1253. result.z = this.z - otherVector.z;
  1254. return this;
  1255. };
  1256. /**
  1257. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1258. */
  1259. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1260. return new Vector3(this.x - x, this.y - y, this.z - z);
  1261. };
  1262. /**
  1263. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1264. * Returns the current Vector3.
  1265. */
  1266. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1267. result.x = this.x - x;
  1268. result.y = this.y - y;
  1269. result.z = this.z - z;
  1270. return this;
  1271. };
  1272. /**
  1273. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1274. */
  1275. Vector3.prototype.negate = function () {
  1276. return new Vector3(-this.x, -this.y, -this.z);
  1277. };
  1278. /**
  1279. * Multiplies the Vector3 coordinates by the float "scale".
  1280. * Returns the updated Vector3.
  1281. */
  1282. Vector3.prototype.scaleInPlace = function (scale) {
  1283. this.x *= scale;
  1284. this.y *= scale;
  1285. this.z *= scale;
  1286. return this;
  1287. };
  1288. /**
  1289. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1290. */
  1291. Vector3.prototype.scale = function (scale) {
  1292. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1293. };
  1294. /**
  1295. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1296. * Returns the current Vector3.
  1297. */
  1298. Vector3.prototype.scaleToRef = function (scale, result) {
  1299. result.x = this.x * scale;
  1300. result.y = this.y * scale;
  1301. result.z = this.z * scale;
  1302. return this;
  1303. };
  1304. /**
  1305. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1306. */
  1307. Vector3.prototype.equals = function (otherVector) {
  1308. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1309. };
  1310. /**
  1311. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1312. */
  1313. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1314. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1315. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  1316. };
  1317. /**
  1318. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1319. */
  1320. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1321. return this.x === x && this.y === y && this.z === z;
  1322. };
  1323. /**
  1324. * Muliplies the current Vector3 coordinates by the passed ones.
  1325. * Returns the updated Vector3.
  1326. */
  1327. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1328. this.x *= otherVector.x;
  1329. this.y *= otherVector.y;
  1330. this.z *= otherVector.z;
  1331. return this;
  1332. };
  1333. /**
  1334. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1335. */
  1336. Vector3.prototype.multiply = function (otherVector) {
  1337. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1338. };
  1339. /**
  1340. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1341. * Returns the current Vector3.
  1342. */
  1343. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1344. result.x = this.x * otherVector.x;
  1345. result.y = this.y * otherVector.y;
  1346. result.z = this.z * otherVector.z;
  1347. return this;
  1348. };
  1349. /**
  1350. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1351. */
  1352. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1353. return new Vector3(this.x * x, this.y * y, this.z * z);
  1354. };
  1355. /**
  1356. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1357. */
  1358. Vector3.prototype.divide = function (otherVector) {
  1359. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1360. };
  1361. /**
  1362. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1363. * Returns the current Vector3.
  1364. */
  1365. Vector3.prototype.divideToRef = function (otherVector, result) {
  1366. result.x = this.x / otherVector.x;
  1367. result.y = this.y / otherVector.y;
  1368. result.z = this.z / otherVector.z;
  1369. return this;
  1370. };
  1371. /**
  1372. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1373. * Returns the updated Vector3.
  1374. */
  1375. Vector3.prototype.MinimizeInPlace = function (other) {
  1376. if (other.x < this.x)
  1377. this.x = other.x;
  1378. if (other.y < this.y)
  1379. this.y = other.y;
  1380. if (other.z < this.z)
  1381. this.z = other.z;
  1382. return this;
  1383. };
  1384. /**
  1385. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1386. * Returns the updated Vector3.
  1387. */
  1388. Vector3.prototype.MaximizeInPlace = function (other) {
  1389. if (other.x > this.x)
  1390. this.x = other.x;
  1391. if (other.y > this.y)
  1392. this.y = other.y;
  1393. if (other.z > this.z)
  1394. this.z = other.z;
  1395. return this;
  1396. };
  1397. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  1398. /**
  1399. * Return true is the vector is non uniform meaning x, y or z are not all the same.
  1400. */
  1401. get: function () {
  1402. var absX = Math.abs(this.x);
  1403. var absY = Math.abs(this.y);
  1404. if (absX !== absY) {
  1405. return true;
  1406. }
  1407. var absZ = Math.abs(this.z);
  1408. if (absX !== absZ) {
  1409. return true;
  1410. }
  1411. if (absY !== absZ) {
  1412. return true;
  1413. }
  1414. return false;
  1415. },
  1416. enumerable: true,
  1417. configurable: true
  1418. });
  1419. // Properties
  1420. /**
  1421. * Returns the length of the Vector3 (float).
  1422. */
  1423. Vector3.prototype.length = function () {
  1424. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1425. };
  1426. /**
  1427. * Returns the squared length of the Vector3 (float).
  1428. */
  1429. Vector3.prototype.lengthSquared = function () {
  1430. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1431. };
  1432. /**
  1433. * Normalize the current Vector3.
  1434. * Returns the updated Vector3.
  1435. * /!\ In place operation.
  1436. */
  1437. Vector3.prototype.normalize = function () {
  1438. var len = this.length();
  1439. if (len === 0 || len === 1.0)
  1440. return this;
  1441. var num = 1.0 / len;
  1442. this.x *= num;
  1443. this.y *= num;
  1444. this.z *= num;
  1445. return this;
  1446. };
  1447. /**
  1448. * Normalize the current Vector3 to a new vector.
  1449. * @returns the new Vector3.
  1450. */
  1451. Vector3.prototype.normalizeToNew = function () {
  1452. var normalized = new Vector3(0, 0, 0);
  1453. this.normalizeToRef(normalized);
  1454. return normalized;
  1455. };
  1456. /**
  1457. * Normalize the current Vector3 to the reference.
  1458. * @param the reference to update.
  1459. * @returns the updated Vector3.
  1460. */
  1461. Vector3.prototype.normalizeToRef = function (reference) {
  1462. var len = this.length();
  1463. if (len === 0 || len === 1.0) {
  1464. reference.set(this.x, this.y, this.z);
  1465. return reference;
  1466. }
  1467. var scale = 1.0 / len;
  1468. this.scaleToRef(scale, reference);
  1469. return reference;
  1470. };
  1471. /**
  1472. * Returns a new Vector3 copied from the current Vector3.
  1473. */
  1474. Vector3.prototype.clone = function () {
  1475. return new Vector3(this.x, this.y, this.z);
  1476. };
  1477. /**
  1478. * Copies the passed vector coordinates to the current Vector3 ones.
  1479. * Returns the updated Vector3.
  1480. */
  1481. Vector3.prototype.copyFrom = function (source) {
  1482. this.x = source.x;
  1483. this.y = source.y;
  1484. this.z = source.z;
  1485. return this;
  1486. };
  1487. /**
  1488. * Copies the passed floats to the current Vector3 coordinates.
  1489. * Returns the updated Vector3.
  1490. */
  1491. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1492. this.x = x;
  1493. this.y = y;
  1494. this.z = z;
  1495. return this;
  1496. };
  1497. /**
  1498. * Copies the passed floats to the current Vector3 coordinates.
  1499. * Returns the updated Vector3.
  1500. */
  1501. Vector3.prototype.set = function (x, y, z) {
  1502. return this.copyFromFloats(x, y, z);
  1503. };
  1504. // Statics
  1505. /**
  1506. *
  1507. */
  1508. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1509. var d0 = Vector3.Dot(vector0, axis) - size;
  1510. var d1 = Vector3.Dot(vector1, axis) - size;
  1511. var s = d0 / (d0 - d1);
  1512. return s;
  1513. };
  1514. /**
  1515. * Returns a new Vector3 set from the index "offset" of the passed array.
  1516. */
  1517. Vector3.FromArray = function (array, offset) {
  1518. if (!offset) {
  1519. offset = 0;
  1520. }
  1521. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1522. };
  1523. /**
  1524. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1525. * This function is deprecated. Use FromArray instead.
  1526. */
  1527. Vector3.FromFloatArray = function (array, offset) {
  1528. return Vector3.FromArray(array, offset);
  1529. };
  1530. /**
  1531. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1532. */
  1533. Vector3.FromArrayToRef = function (array, offset, result) {
  1534. result.x = array[offset];
  1535. result.y = array[offset + 1];
  1536. result.z = array[offset + 2];
  1537. };
  1538. /**
  1539. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1540. * This function is deprecated. Use FromArrayToRef instead.
  1541. */
  1542. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1543. return Vector3.FromArrayToRef(array, offset, result);
  1544. };
  1545. /**
  1546. * Sets the passed vector "result" with the passed floats.
  1547. */
  1548. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1549. result.x = x;
  1550. result.y = y;
  1551. result.z = z;
  1552. };
  1553. /**
  1554. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1555. */
  1556. Vector3.Zero = function () {
  1557. return new Vector3(0.0, 0.0, 0.0);
  1558. };
  1559. /**
  1560. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  1561. */
  1562. Vector3.One = function () {
  1563. return new Vector3(1.0, 1.0, 1.0);
  1564. };
  1565. /**
  1566. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1567. */
  1568. Vector3.Up = function () {
  1569. return new Vector3(0.0, 1.0, 0.0);
  1570. };
  1571. /**
  1572. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1573. */
  1574. Vector3.Forward = function () {
  1575. return new Vector3(0.0, 0.0, 1.0);
  1576. };
  1577. /**
  1578. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1579. */
  1580. Vector3.Right = function () {
  1581. return new Vector3(1.0, 0.0, 0.0);
  1582. };
  1583. /**
  1584. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1585. */
  1586. Vector3.Left = function () {
  1587. return new Vector3(-1.0, 0.0, 0.0);
  1588. };
  1589. /**
  1590. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1591. * This method computes tranformed coordinates only, not transformed direction vectors.
  1592. */
  1593. Vector3.TransformCoordinates = function (vector, transformation) {
  1594. var result = Vector3.Zero();
  1595. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1596. return result;
  1597. };
  1598. /**
  1599. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1600. * This method computes tranformed coordinates only, not transformed direction vectors.
  1601. */
  1602. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1603. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1604. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1605. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1606. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1607. result.x = x / w;
  1608. result.y = y / w;
  1609. result.z = z / w;
  1610. };
  1611. /**
  1612. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1613. * This method computes tranformed coordinates only, not transformed direction vectors.
  1614. */
  1615. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1616. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1617. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1618. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1619. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1620. result.x = rx / rw;
  1621. result.y = ry / rw;
  1622. result.z = rz / rw;
  1623. };
  1624. /**
  1625. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1626. * This methods computes transformed normalized direction vectors only.
  1627. */
  1628. Vector3.TransformNormal = function (vector, transformation) {
  1629. var result = Vector3.Zero();
  1630. Vector3.TransformNormalToRef(vector, transformation, result);
  1631. return result;
  1632. };
  1633. /**
  1634. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1635. * This methods computes transformed normalized direction vectors only.
  1636. */
  1637. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1638. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1639. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1640. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1641. result.x = x;
  1642. result.y = y;
  1643. result.z = z;
  1644. };
  1645. /**
  1646. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1647. * This methods computes transformed normalized direction vectors only.
  1648. */
  1649. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1650. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1651. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1652. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1653. };
  1654. /**
  1655. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1656. */
  1657. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1658. var squared = amount * amount;
  1659. var cubed = amount * squared;
  1660. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1661. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1662. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1663. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1664. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1665. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1666. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1667. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1668. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1669. return new Vector3(x, y, z);
  1670. };
  1671. /**
  1672. * 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".
  1673. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1674. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1675. */
  1676. Vector3.Clamp = function (value, min, max) {
  1677. var x = value.x;
  1678. x = (x > max.x) ? max.x : x;
  1679. x = (x < min.x) ? min.x : x;
  1680. var y = value.y;
  1681. y = (y > max.y) ? max.y : y;
  1682. y = (y < min.y) ? min.y : y;
  1683. var z = value.z;
  1684. z = (z > max.z) ? max.z : z;
  1685. z = (z < min.z) ? min.z : z;
  1686. return new Vector3(x, y, z);
  1687. };
  1688. /**
  1689. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1690. */
  1691. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1692. var squared = amount * amount;
  1693. var cubed = amount * squared;
  1694. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1695. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1696. var part3 = (cubed - (2.0 * squared)) + amount;
  1697. var part4 = cubed - squared;
  1698. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1699. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1700. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1701. return new Vector3(x, y, z);
  1702. };
  1703. /**
  1704. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1705. */
  1706. Vector3.Lerp = function (start, end, amount) {
  1707. var result = new Vector3(0, 0, 0);
  1708. Vector3.LerpToRef(start, end, amount, result);
  1709. return result;
  1710. };
  1711. /**
  1712. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1713. */
  1714. Vector3.LerpToRef = function (start, end, amount, result) {
  1715. result.x = start.x + ((end.x - start.x) * amount);
  1716. result.y = start.y + ((end.y - start.y) * amount);
  1717. result.z = start.z + ((end.z - start.z) * amount);
  1718. };
  1719. /**
  1720. * Returns the dot product (float) between the vectors "left" and "right".
  1721. */
  1722. Vector3.Dot = function (left, right) {
  1723. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1724. };
  1725. /**
  1726. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1727. * The cross product is then orthogonal to both "left" and "right".
  1728. */
  1729. Vector3.Cross = function (left, right) {
  1730. var result = Vector3.Zero();
  1731. Vector3.CrossToRef(left, right, result);
  1732. return result;
  1733. };
  1734. /**
  1735. * Sets the passed vector "result" with the cross product of "left" and "right".
  1736. * The cross product is then orthogonal to both "left" and "right".
  1737. */
  1738. Vector3.CrossToRef = function (left, right, result) {
  1739. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1740. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1741. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1742. result.copyFrom(MathTmp.Vector3[0]);
  1743. };
  1744. /**
  1745. * Returns a new Vector3 as the normalization of the passed vector.
  1746. */
  1747. Vector3.Normalize = function (vector) {
  1748. var result = Vector3.Zero();
  1749. Vector3.NormalizeToRef(vector, result);
  1750. return result;
  1751. };
  1752. /**
  1753. * Sets the passed vector "result" with the normalization of the passed first vector.
  1754. */
  1755. Vector3.NormalizeToRef = function (vector, result) {
  1756. result.copyFrom(vector);
  1757. result.normalize();
  1758. };
  1759. Vector3.Project = function (vector, world, transform, viewport) {
  1760. var cw = viewport.width;
  1761. var ch = viewport.height;
  1762. var cx = viewport.x;
  1763. var cy = viewport.y;
  1764. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1765. 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);
  1766. var matrix = MathTmp.Matrix[0];
  1767. world.multiplyToRef(transform, matrix);
  1768. matrix.multiplyToRef(viewportMatrix, matrix);
  1769. return Vector3.TransformCoordinates(vector, matrix);
  1770. };
  1771. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1772. var matrix = MathTmp.Matrix[0];
  1773. world.multiplyToRef(transform, matrix);
  1774. matrix.invert();
  1775. source.x = source.x / viewportWidth * 2 - 1;
  1776. source.y = -(source.y / viewportHeight * 2 - 1);
  1777. var vector = Vector3.TransformCoordinates(source, matrix);
  1778. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1779. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1780. vector = vector.scale(1.0 / num);
  1781. }
  1782. return vector;
  1783. };
  1784. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1785. var result = Vector3.Zero();
  1786. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  1787. return result;
  1788. };
  1789. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  1790. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  1791. };
  1792. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  1793. var matrix = MathTmp.Matrix[0];
  1794. world.multiplyToRef(view, matrix);
  1795. matrix.multiplyToRef(projection, matrix);
  1796. matrix.invert();
  1797. var screenSource = MathTmp.Vector3[0];
  1798. screenSource.x = sourceX / viewportWidth * 2 - 1;
  1799. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  1800. screenSource.z = 2 * sourceZ - 1.0;
  1801. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  1802. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1803. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1804. result.scaleInPlace(1.0 / num);
  1805. }
  1806. };
  1807. Vector3.Minimize = function (left, right) {
  1808. var min = left.clone();
  1809. min.MinimizeInPlace(right);
  1810. return min;
  1811. };
  1812. Vector3.Maximize = function (left, right) {
  1813. var max = left.clone();
  1814. max.MaximizeInPlace(right);
  1815. return max;
  1816. };
  1817. /**
  1818. * Returns the distance (float) between the vectors "value1" and "value2".
  1819. */
  1820. Vector3.Distance = function (value1, value2) {
  1821. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1822. };
  1823. /**
  1824. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1825. */
  1826. Vector3.DistanceSquared = function (value1, value2) {
  1827. var x = value1.x - value2.x;
  1828. var y = value1.y - value2.y;
  1829. var z = value1.z - value2.z;
  1830. return (x * x) + (y * y) + (z * z);
  1831. };
  1832. /**
  1833. * Returns a new Vector3 located at the center between "value1" and "value2".
  1834. */
  1835. Vector3.Center = function (value1, value2) {
  1836. var center = value1.add(value2);
  1837. center.scaleInPlace(0.5);
  1838. return center;
  1839. };
  1840. /**
  1841. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1842. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1843. * to something in order to rotate it from its local system to the given target system.
  1844. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1845. * Returns a new Vector3.
  1846. */
  1847. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1848. var rotation = Vector3.Zero();
  1849. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1850. return rotation;
  1851. };
  1852. /**
  1853. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1854. */
  1855. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1856. var quat = MathTmp.Quaternion[0];
  1857. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1858. quat.toEulerAnglesToRef(ref);
  1859. };
  1860. return Vector3;
  1861. }());
  1862. BABYLON.Vector3 = Vector3;
  1863. //Vector4 class created for EulerAngle class conversion to Quaternion
  1864. var Vector4 = /** @class */ (function () {
  1865. /**
  1866. * Creates a Vector4 object from the passed floats.
  1867. */
  1868. function Vector4(x, y, z, w) {
  1869. this.x = x;
  1870. this.y = y;
  1871. this.z = z;
  1872. this.w = w;
  1873. }
  1874. /**
  1875. * Returns the string with the Vector4 coordinates.
  1876. */
  1877. Vector4.prototype.toString = function () {
  1878. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1879. };
  1880. /**
  1881. * Returns the string "Vector4".
  1882. */
  1883. Vector4.prototype.getClassName = function () {
  1884. return "Vector4";
  1885. };
  1886. /**
  1887. * Returns the Vector4 hash code.
  1888. */
  1889. Vector4.prototype.getHashCode = function () {
  1890. var hash = this.x || 0;
  1891. hash = (hash * 397) ^ (this.y || 0);
  1892. hash = (hash * 397) ^ (this.z || 0);
  1893. hash = (hash * 397) ^ (this.w || 0);
  1894. return hash;
  1895. };
  1896. // Operators
  1897. /**
  1898. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1899. */
  1900. Vector4.prototype.asArray = function () {
  1901. var result = new Array();
  1902. this.toArray(result, 0);
  1903. return result;
  1904. };
  1905. /**
  1906. * Populates the passed array from the passed index with the Vector4 coordinates.
  1907. * Returns the Vector4.
  1908. */
  1909. Vector4.prototype.toArray = function (array, index) {
  1910. if (index === undefined) {
  1911. index = 0;
  1912. }
  1913. array[index] = this.x;
  1914. array[index + 1] = this.y;
  1915. array[index + 2] = this.z;
  1916. array[index + 3] = this.w;
  1917. return this;
  1918. };
  1919. /**
  1920. * Adds the passed vector to the current Vector4.
  1921. * Returns the updated Vector4.
  1922. */
  1923. Vector4.prototype.addInPlace = function (otherVector) {
  1924. this.x += otherVector.x;
  1925. this.y += otherVector.y;
  1926. this.z += otherVector.z;
  1927. this.w += otherVector.w;
  1928. return this;
  1929. };
  1930. /**
  1931. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1932. */
  1933. Vector4.prototype.add = function (otherVector) {
  1934. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1935. };
  1936. /**
  1937. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1938. * Returns the current Vector4.
  1939. */
  1940. Vector4.prototype.addToRef = function (otherVector, result) {
  1941. result.x = this.x + otherVector.x;
  1942. result.y = this.y + otherVector.y;
  1943. result.z = this.z + otherVector.z;
  1944. result.w = this.w + otherVector.w;
  1945. return this;
  1946. };
  1947. /**
  1948. * Subtract in place the passed vector from the current Vector4.
  1949. * Returns the updated Vector4.
  1950. */
  1951. Vector4.prototype.subtractInPlace = function (otherVector) {
  1952. this.x -= otherVector.x;
  1953. this.y -= otherVector.y;
  1954. this.z -= otherVector.z;
  1955. this.w -= otherVector.w;
  1956. return this;
  1957. };
  1958. /**
  1959. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1960. */
  1961. Vector4.prototype.subtract = function (otherVector) {
  1962. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1963. };
  1964. /**
  1965. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1966. * Returns the current Vector4.
  1967. */
  1968. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1969. result.x = this.x - otherVector.x;
  1970. result.y = this.y - otherVector.y;
  1971. result.z = this.z - otherVector.z;
  1972. result.w = this.w - otherVector.w;
  1973. return this;
  1974. };
  1975. /**
  1976. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1977. */
  1978. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1979. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1980. };
  1981. /**
  1982. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1983. * Returns the current Vector4.
  1984. */
  1985. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1986. result.x = this.x - x;
  1987. result.y = this.y - y;
  1988. result.z = this.z - z;
  1989. result.w = this.w - w;
  1990. return this;
  1991. };
  1992. /**
  1993. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1994. */
  1995. Vector4.prototype.negate = function () {
  1996. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1997. };
  1998. /**
  1999. * Multiplies the current Vector4 coordinates by scale (float).
  2000. * Returns the updated Vector4.
  2001. */
  2002. Vector4.prototype.scaleInPlace = function (scale) {
  2003. this.x *= scale;
  2004. this.y *= scale;
  2005. this.z *= scale;
  2006. this.w *= scale;
  2007. return this;
  2008. };
  2009. /**
  2010. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  2011. */
  2012. Vector4.prototype.scale = function (scale) {
  2013. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  2014. };
  2015. /**
  2016. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  2017. * Returns the current Vector4.
  2018. */
  2019. Vector4.prototype.scaleToRef = function (scale, result) {
  2020. result.x = this.x * scale;
  2021. result.y = this.y * scale;
  2022. result.z = this.z * scale;
  2023. result.w = this.w * scale;
  2024. return this;
  2025. };
  2026. /**
  2027. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  2028. */
  2029. Vector4.prototype.equals = function (otherVector) {
  2030. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  2031. };
  2032. /**
  2033. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  2034. */
  2035. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2036. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2037. return otherVector
  2038. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  2039. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  2040. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  2041. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  2042. };
  2043. /**
  2044. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  2045. */
  2046. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  2047. return this.x === x && this.y === y && this.z === z && this.w === w;
  2048. };
  2049. /**
  2050. * Multiplies in place the current Vector4 by the passed one.
  2051. * Returns the updated Vector4.
  2052. */
  2053. Vector4.prototype.multiplyInPlace = function (otherVector) {
  2054. this.x *= otherVector.x;
  2055. this.y *= otherVector.y;
  2056. this.z *= otherVector.z;
  2057. this.w *= otherVector.w;
  2058. return this;
  2059. };
  2060. /**
  2061. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  2062. */
  2063. Vector4.prototype.multiply = function (otherVector) {
  2064. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  2065. };
  2066. /**
  2067. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  2068. * Returns the current Vector4.
  2069. */
  2070. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  2071. result.x = this.x * otherVector.x;
  2072. result.y = this.y * otherVector.y;
  2073. result.z = this.z * otherVector.z;
  2074. result.w = this.w * otherVector.w;
  2075. return this;
  2076. };
  2077. /**
  2078. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  2079. */
  2080. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  2081. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  2082. };
  2083. /**
  2084. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  2085. */
  2086. Vector4.prototype.divide = function (otherVector) {
  2087. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  2088. };
  2089. /**
  2090. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  2091. * Returns the current Vector4.
  2092. */
  2093. Vector4.prototype.divideToRef = function (otherVector, result) {
  2094. result.x = this.x / otherVector.x;
  2095. result.y = this.y / otherVector.y;
  2096. result.z = this.z / otherVector.z;
  2097. result.w = this.w / otherVector.w;
  2098. return this;
  2099. };
  2100. /**
  2101. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  2102. */
  2103. Vector4.prototype.MinimizeInPlace = function (other) {
  2104. if (other.x < this.x)
  2105. this.x = other.x;
  2106. if (other.y < this.y)
  2107. this.y = other.y;
  2108. if (other.z < this.z)
  2109. this.z = other.z;
  2110. if (other.w < this.w)
  2111. this.w = other.w;
  2112. return this;
  2113. };
  2114. /**
  2115. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  2116. */
  2117. Vector4.prototype.MaximizeInPlace = function (other) {
  2118. if (other.x > this.x)
  2119. this.x = other.x;
  2120. if (other.y > this.y)
  2121. this.y = other.y;
  2122. if (other.z > this.z)
  2123. this.z = other.z;
  2124. if (other.w > this.w)
  2125. this.w = other.w;
  2126. return this;
  2127. };
  2128. // Properties
  2129. /**
  2130. * Returns the Vector4 length (float).
  2131. */
  2132. Vector4.prototype.length = function () {
  2133. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2134. };
  2135. /**
  2136. * Returns the Vector4 squared length (float).
  2137. */
  2138. Vector4.prototype.lengthSquared = function () {
  2139. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2140. };
  2141. // Methods
  2142. /**
  2143. * Normalizes in place the Vector4.
  2144. * Returns the updated Vector4.
  2145. */
  2146. Vector4.prototype.normalize = function () {
  2147. var len = this.length();
  2148. if (len === 0)
  2149. return this;
  2150. var num = 1.0 / len;
  2151. this.x *= num;
  2152. this.y *= num;
  2153. this.z *= num;
  2154. this.w *= num;
  2155. return this;
  2156. };
  2157. /**
  2158. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  2159. */
  2160. Vector4.prototype.toVector3 = function () {
  2161. return new Vector3(this.x, this.y, this.z);
  2162. };
  2163. /**
  2164. * Returns a new Vector4 copied from the current one.
  2165. */
  2166. Vector4.prototype.clone = function () {
  2167. return new Vector4(this.x, this.y, this.z, this.w);
  2168. };
  2169. /**
  2170. * Updates the current Vector4 with the passed one coordinates.
  2171. * Returns the updated Vector4.
  2172. */
  2173. Vector4.prototype.copyFrom = function (source) {
  2174. this.x = source.x;
  2175. this.y = source.y;
  2176. this.z = source.z;
  2177. this.w = source.w;
  2178. return this;
  2179. };
  2180. /**
  2181. * Updates the current Vector4 coordinates with the passed floats.
  2182. * Returns the updated Vector4.
  2183. */
  2184. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  2185. this.x = x;
  2186. this.y = y;
  2187. this.z = z;
  2188. this.w = w;
  2189. return this;
  2190. };
  2191. /**
  2192. * Updates the current Vector4 coordinates with the passed floats.
  2193. * Returns the updated Vector4.
  2194. */
  2195. Vector4.prototype.set = function (x, y, z, w) {
  2196. return this.copyFromFloats(x, y, z, w);
  2197. };
  2198. // Statics
  2199. /**
  2200. * Returns a new Vector4 set from the starting index of the passed array.
  2201. */
  2202. Vector4.FromArray = function (array, offset) {
  2203. if (!offset) {
  2204. offset = 0;
  2205. }
  2206. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2207. };
  2208. /**
  2209. * Updates the passed vector "result" from the starting index of the passed array.
  2210. */
  2211. Vector4.FromArrayToRef = function (array, offset, result) {
  2212. result.x = array[offset];
  2213. result.y = array[offset + 1];
  2214. result.z = array[offset + 2];
  2215. result.w = array[offset + 3];
  2216. };
  2217. /**
  2218. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2219. */
  2220. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2221. Vector4.FromArrayToRef(array, offset, result);
  2222. };
  2223. /**
  2224. * Updates the passed vector "result" coordinates from the passed floats.
  2225. */
  2226. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2227. result.x = x;
  2228. result.y = y;
  2229. result.z = z;
  2230. result.w = w;
  2231. };
  2232. /**
  2233. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2234. */
  2235. Vector4.Zero = function () {
  2236. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2237. };
  2238. /**
  2239. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  2240. */
  2241. Vector4.One = function () {
  2242. return new Vector4(1.0, 1.0, 1.0, 1.0);
  2243. };
  2244. /**
  2245. * Returns a new normalized Vector4 from the passed one.
  2246. */
  2247. Vector4.Normalize = function (vector) {
  2248. var result = Vector4.Zero();
  2249. Vector4.NormalizeToRef(vector, result);
  2250. return result;
  2251. };
  2252. /**
  2253. * Updates the passed vector "result" from the normalization of the passed one.
  2254. */
  2255. Vector4.NormalizeToRef = function (vector, result) {
  2256. result.copyFrom(vector);
  2257. result.normalize();
  2258. };
  2259. Vector4.Minimize = function (left, right) {
  2260. var min = left.clone();
  2261. min.MinimizeInPlace(right);
  2262. return min;
  2263. };
  2264. Vector4.Maximize = function (left, right) {
  2265. var max = left.clone();
  2266. max.MaximizeInPlace(right);
  2267. return max;
  2268. };
  2269. /**
  2270. * Returns the distance (float) between the vectors "value1" and "value2".
  2271. */
  2272. Vector4.Distance = function (value1, value2) {
  2273. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2274. };
  2275. /**
  2276. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2277. */
  2278. Vector4.DistanceSquared = function (value1, value2) {
  2279. var x = value1.x - value2.x;
  2280. var y = value1.y - value2.y;
  2281. var z = value1.z - value2.z;
  2282. var w = value1.w - value2.w;
  2283. return (x * x) + (y * y) + (z * z) + (w * w);
  2284. };
  2285. /**
  2286. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2287. */
  2288. Vector4.Center = function (value1, value2) {
  2289. var center = value1.add(value2);
  2290. center.scaleInPlace(0.5);
  2291. return center;
  2292. };
  2293. /**
  2294. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2295. * This methods computes transformed normalized direction vectors only.
  2296. */
  2297. Vector4.TransformNormal = function (vector, transformation) {
  2298. var result = Vector4.Zero();
  2299. Vector4.TransformNormalToRef(vector, transformation, result);
  2300. return result;
  2301. };
  2302. /**
  2303. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2304. * This methods computes transformed normalized direction vectors only.
  2305. */
  2306. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2307. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2308. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2309. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2310. result.x = x;
  2311. result.y = y;
  2312. result.z = z;
  2313. result.w = vector.w;
  2314. };
  2315. /**
  2316. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2317. * This methods computes transformed normalized direction vectors only.
  2318. */
  2319. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2320. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2321. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2322. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2323. result.w = w;
  2324. };
  2325. return Vector4;
  2326. }());
  2327. BABYLON.Vector4 = Vector4;
  2328. var Size = /** @class */ (function () {
  2329. /**
  2330. * Creates a Size object from the passed width and height (floats).
  2331. */
  2332. function Size(width, height) {
  2333. this.width = width;
  2334. this.height = height;
  2335. }
  2336. // Returns a string with the Size width and height.
  2337. Size.prototype.toString = function () {
  2338. return "{W: " + this.width + ", H: " + this.height + "}";
  2339. };
  2340. /**
  2341. * Returns the string "Size"
  2342. */
  2343. Size.prototype.getClassName = function () {
  2344. return "Size";
  2345. };
  2346. /**
  2347. * Returns the Size hash code.
  2348. */
  2349. Size.prototype.getHashCode = function () {
  2350. var hash = this.width || 0;
  2351. hash = (hash * 397) ^ (this.height || 0);
  2352. return hash;
  2353. };
  2354. /**
  2355. * Updates the current size from the passed one.
  2356. * Returns the updated Size.
  2357. */
  2358. Size.prototype.copyFrom = function (src) {
  2359. this.width = src.width;
  2360. this.height = src.height;
  2361. };
  2362. /**
  2363. * Updates in place the current Size from the passed floats.
  2364. * Returns the updated Size.
  2365. */
  2366. Size.prototype.copyFromFloats = function (width, height) {
  2367. this.width = width;
  2368. this.height = height;
  2369. return this;
  2370. };
  2371. /**
  2372. * Updates in place the current Size from the passed floats.
  2373. * Returns the updated Size.
  2374. */
  2375. Size.prototype.set = function (width, height) {
  2376. return this.copyFromFloats(width, height);
  2377. };
  2378. /**
  2379. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2380. */
  2381. Size.prototype.multiplyByFloats = function (w, h) {
  2382. return new Size(this.width * w, this.height * h);
  2383. };
  2384. /**
  2385. * Returns a new Size copied from the passed one.
  2386. */
  2387. Size.prototype.clone = function () {
  2388. return new Size(this.width, this.height);
  2389. };
  2390. /**
  2391. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2392. */
  2393. Size.prototype.equals = function (other) {
  2394. if (!other) {
  2395. return false;
  2396. }
  2397. return (this.width === other.width) && (this.height === other.height);
  2398. };
  2399. Object.defineProperty(Size.prototype, "surface", {
  2400. /**
  2401. * Returns the surface of the Size : width * height (float).
  2402. */
  2403. get: function () {
  2404. return this.width * this.height;
  2405. },
  2406. enumerable: true,
  2407. configurable: true
  2408. });
  2409. /**
  2410. * Returns a new Size set to (0.0, 0.0)
  2411. */
  2412. Size.Zero = function () {
  2413. return new Size(0.0, 0.0);
  2414. };
  2415. /**
  2416. * Returns a new Size set as the addition result of the current Size and the passed one.
  2417. */
  2418. Size.prototype.add = function (otherSize) {
  2419. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2420. return r;
  2421. };
  2422. /**
  2423. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2424. */
  2425. Size.prototype.subtract = function (otherSize) {
  2426. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2427. return r;
  2428. };
  2429. /**
  2430. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2431. */
  2432. Size.Lerp = function (start, end, amount) {
  2433. var w = start.width + ((end.width - start.width) * amount);
  2434. var h = start.height + ((end.height - start.height) * amount);
  2435. return new Size(w, h);
  2436. };
  2437. return Size;
  2438. }());
  2439. BABYLON.Size = Size;
  2440. var Quaternion = /** @class */ (function () {
  2441. /**
  2442. * Creates a new Quaternion from the passed floats.
  2443. */
  2444. function Quaternion(x, y, z, w) {
  2445. if (x === void 0) { x = 0.0; }
  2446. if (y === void 0) { y = 0.0; }
  2447. if (z === void 0) { z = 0.0; }
  2448. if (w === void 0) { w = 1.0; }
  2449. this.x = x;
  2450. this.y = y;
  2451. this.z = z;
  2452. this.w = w;
  2453. }
  2454. /**
  2455. * Returns a string with the Quaternion coordinates.
  2456. */
  2457. Quaternion.prototype.toString = function () {
  2458. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2459. };
  2460. /**
  2461. * Returns the string "Quaternion".
  2462. */
  2463. Quaternion.prototype.getClassName = function () {
  2464. return "Quaternion";
  2465. };
  2466. /**
  2467. * Returns the Quaternion hash code.
  2468. */
  2469. Quaternion.prototype.getHashCode = function () {
  2470. var hash = this.x || 0;
  2471. hash = (hash * 397) ^ (this.y || 0);
  2472. hash = (hash * 397) ^ (this.z || 0);
  2473. hash = (hash * 397) ^ (this.w || 0);
  2474. return hash;
  2475. };
  2476. /**
  2477. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2478. */
  2479. Quaternion.prototype.asArray = function () {
  2480. return [this.x, this.y, this.z, this.w];
  2481. };
  2482. /**
  2483. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2484. */
  2485. Quaternion.prototype.equals = function (otherQuaternion) {
  2486. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2487. };
  2488. /**
  2489. * Returns a new Quaternion copied from the current one.
  2490. */
  2491. Quaternion.prototype.clone = function () {
  2492. return new Quaternion(this.x, this.y, this.z, this.w);
  2493. };
  2494. /**
  2495. * Updates the current Quaternion from the passed one coordinates.
  2496. * Returns the updated Quaterion.
  2497. */
  2498. Quaternion.prototype.copyFrom = function (other) {
  2499. this.x = other.x;
  2500. this.y = other.y;
  2501. this.z = other.z;
  2502. this.w = other.w;
  2503. return this;
  2504. };
  2505. /**
  2506. * Updates the current Quaternion from the passed float coordinates.
  2507. * Returns the updated Quaterion.
  2508. */
  2509. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2510. this.x = x;
  2511. this.y = y;
  2512. this.z = z;
  2513. this.w = w;
  2514. return this;
  2515. };
  2516. /**
  2517. * Updates the current Quaternion from the passed float coordinates.
  2518. * Returns the updated Quaterion.
  2519. */
  2520. Quaternion.prototype.set = function (x, y, z, w) {
  2521. return this.copyFromFloats(x, y, z, w);
  2522. };
  2523. /**
  2524. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2525. */
  2526. Quaternion.prototype.add = function (other) {
  2527. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2528. };
  2529. /**
  2530. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2531. */
  2532. Quaternion.prototype.subtract = function (other) {
  2533. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2534. };
  2535. /**
  2536. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2537. */
  2538. Quaternion.prototype.scale = function (value) {
  2539. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2540. };
  2541. /**
  2542. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2543. */
  2544. Quaternion.prototype.multiply = function (q1) {
  2545. var result = new Quaternion(0, 0, 0, 1.0);
  2546. this.multiplyToRef(q1, result);
  2547. return result;
  2548. };
  2549. /**
  2550. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2551. * Returns the current Quaternion.
  2552. */
  2553. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2554. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2555. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2556. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2557. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2558. result.copyFromFloats(x, y, z, w);
  2559. return this;
  2560. };
  2561. /**
  2562. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2563. * Returns the updated Quaternion.
  2564. */
  2565. Quaternion.prototype.multiplyInPlace = function (q1) {
  2566. this.multiplyToRef(q1, this);
  2567. return this;
  2568. };
  2569. /**
  2570. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2571. * Returns the current Quaternion.
  2572. */
  2573. Quaternion.prototype.conjugateToRef = function (ref) {
  2574. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2575. return this;
  2576. };
  2577. /**
  2578. * Conjugates in place the current Quaternion.
  2579. * Returns the updated Quaternion.
  2580. */
  2581. Quaternion.prototype.conjugateInPlace = function () {
  2582. this.x *= -1;
  2583. this.y *= -1;
  2584. this.z *= -1;
  2585. return this;
  2586. };
  2587. /**
  2588. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2589. */
  2590. Quaternion.prototype.conjugate = function () {
  2591. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2592. return result;
  2593. };
  2594. /**
  2595. * Returns the Quaternion length (float).
  2596. */
  2597. Quaternion.prototype.length = function () {
  2598. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2599. };
  2600. /**
  2601. * Normalize in place the current Quaternion.
  2602. * Returns the updated Quaternion.
  2603. */
  2604. Quaternion.prototype.normalize = function () {
  2605. var length = 1.0 / this.length();
  2606. this.x *= length;
  2607. this.y *= length;
  2608. this.z *= length;
  2609. this.w *= length;
  2610. return this;
  2611. };
  2612. /**
  2613. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2614. */
  2615. Quaternion.prototype.toEulerAngles = function (order) {
  2616. if (order === void 0) { order = "YZX"; }
  2617. var result = Vector3.Zero();
  2618. this.toEulerAnglesToRef(result, order);
  2619. return result;
  2620. };
  2621. /**
  2622. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2623. * Returns the current Quaternion.
  2624. */
  2625. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2626. if (order === void 0) { order = "YZX"; }
  2627. var qz = this.z;
  2628. var qx = this.x;
  2629. var qy = this.y;
  2630. var qw = this.w;
  2631. var sqw = qw * qw;
  2632. var sqz = qz * qz;
  2633. var sqx = qx * qx;
  2634. var sqy = qy * qy;
  2635. var zAxisY = qy * qz - qx * qw;
  2636. var limit = .4999999;
  2637. if (zAxisY < -limit) {
  2638. result.y = 2 * Math.atan2(qy, qw);
  2639. result.x = Math.PI / 2;
  2640. result.z = 0;
  2641. }
  2642. else if (zAxisY > limit) {
  2643. result.y = 2 * Math.atan2(qy, qw);
  2644. result.x = -Math.PI / 2;
  2645. result.z = 0;
  2646. }
  2647. else {
  2648. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2649. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2650. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2651. }
  2652. return this;
  2653. };
  2654. /**
  2655. * Updates the passed rotation matrix with the current Quaternion values.
  2656. * Returns the current Quaternion.
  2657. */
  2658. Quaternion.prototype.toRotationMatrix = function (result) {
  2659. var xx = this.x * this.x;
  2660. var yy = this.y * this.y;
  2661. var zz = this.z * this.z;
  2662. var xy = this.x * this.y;
  2663. var zw = this.z * this.w;
  2664. var zx = this.z * this.x;
  2665. var yw = this.y * this.w;
  2666. var yz = this.y * this.z;
  2667. var xw = this.x * this.w;
  2668. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2669. result.m[1] = 2.0 * (xy + zw);
  2670. result.m[2] = 2.0 * (zx - yw);
  2671. result.m[3] = 0;
  2672. result.m[4] = 2.0 * (xy - zw);
  2673. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2674. result.m[6] = 2.0 * (yz + xw);
  2675. result.m[7] = 0;
  2676. result.m[8] = 2.0 * (zx + yw);
  2677. result.m[9] = 2.0 * (yz - xw);
  2678. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2679. result.m[11] = 0;
  2680. result.m[12] = 0;
  2681. result.m[13] = 0;
  2682. result.m[14] = 0;
  2683. result.m[15] = 1.0;
  2684. result._markAsUpdated();
  2685. return this;
  2686. };
  2687. /**
  2688. * Updates the current Quaternion from the passed rotation matrix values.
  2689. * Returns the updated Quaternion.
  2690. */
  2691. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2692. Quaternion.FromRotationMatrixToRef(matrix, this);
  2693. return this;
  2694. };
  2695. // Statics
  2696. /**
  2697. * Returns a new Quaternion set from the passed rotation matrix values.
  2698. */
  2699. Quaternion.FromRotationMatrix = function (matrix) {
  2700. var result = new Quaternion();
  2701. Quaternion.FromRotationMatrixToRef(matrix, result);
  2702. return result;
  2703. };
  2704. /**
  2705. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2706. */
  2707. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2708. var data = matrix.m;
  2709. var m11 = data[0], m12 = data[4], m13 = data[8];
  2710. var m21 = data[1], m22 = data[5], m23 = data[9];
  2711. var m31 = data[2], m32 = data[6], m33 = data[10];
  2712. var trace = m11 + m22 + m33;
  2713. var s;
  2714. if (trace > 0) {
  2715. s = 0.5 / Math.sqrt(trace + 1.0);
  2716. result.w = 0.25 / s;
  2717. result.x = (m32 - m23) * s;
  2718. result.y = (m13 - m31) * s;
  2719. result.z = (m21 - m12) * s;
  2720. }
  2721. else if (m11 > m22 && m11 > m33) {
  2722. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2723. result.w = (m32 - m23) / s;
  2724. result.x = 0.25 * s;
  2725. result.y = (m12 + m21) / s;
  2726. result.z = (m13 + m31) / s;
  2727. }
  2728. else if (m22 > m33) {
  2729. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2730. result.w = (m13 - m31) / s;
  2731. result.x = (m12 + m21) / s;
  2732. result.y = 0.25 * s;
  2733. result.z = (m23 + m32) / s;
  2734. }
  2735. else {
  2736. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2737. result.w = (m21 - m12) / s;
  2738. result.x = (m13 + m31) / s;
  2739. result.y = (m23 + m32) / s;
  2740. result.z = 0.25 * s;
  2741. }
  2742. };
  2743. /**
  2744. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2745. */
  2746. Quaternion.Zero = function () {
  2747. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2748. };
  2749. /**
  2750. * Returns a new Quaternion as the inverted current Quaternion.
  2751. */
  2752. Quaternion.Inverse = function (q) {
  2753. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2754. };
  2755. /**
  2756. * Returns the identity Quaternion.
  2757. */
  2758. Quaternion.Identity = function () {
  2759. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2760. };
  2761. Quaternion.IsIdentity = function (quaternion) {
  2762. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2763. };
  2764. /**
  2765. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2766. */
  2767. Quaternion.RotationAxis = function (axis, angle) {
  2768. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2769. };
  2770. /**
  2771. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2772. */
  2773. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2774. var sin = Math.sin(angle / 2);
  2775. axis.normalize();
  2776. result.w = Math.cos(angle / 2);
  2777. result.x = axis.x * sin;
  2778. result.y = axis.y * sin;
  2779. result.z = axis.z * sin;
  2780. return result;
  2781. };
  2782. /**
  2783. * Retuns a new Quaternion set from the starting index of the passed array.
  2784. */
  2785. Quaternion.FromArray = function (array, offset) {
  2786. if (!offset) {
  2787. offset = 0;
  2788. }
  2789. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2790. };
  2791. /**
  2792. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2793. */
  2794. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2795. var q = new Quaternion();
  2796. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2797. return q;
  2798. };
  2799. /**
  2800. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2801. */
  2802. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2803. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2804. var halfRoll = roll * 0.5;
  2805. var halfPitch = pitch * 0.5;
  2806. var halfYaw = yaw * 0.5;
  2807. var sinRoll = Math.sin(halfRoll);
  2808. var cosRoll = Math.cos(halfRoll);
  2809. var sinPitch = Math.sin(halfPitch);
  2810. var cosPitch = Math.cos(halfPitch);
  2811. var sinYaw = Math.sin(halfYaw);
  2812. var cosYaw = Math.cos(halfYaw);
  2813. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2814. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2815. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2816. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2817. };
  2818. /**
  2819. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2820. */
  2821. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2822. var result = new Quaternion();
  2823. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2824. return result;
  2825. };
  2826. /**
  2827. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2828. */
  2829. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2830. // Produces a quaternion from Euler angles in the z-x-z orientation
  2831. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2832. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2833. var halfBeta = beta * 0.5;
  2834. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2835. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2836. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2837. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2838. };
  2839. /**
  2840. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2841. * cf to Vector3.RotationFromAxis() documentation.
  2842. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2843. */
  2844. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2845. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2846. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2847. return quat;
  2848. };
  2849. /**
  2850. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2851. * cf to Vector3.RotationFromAxis() documentation.
  2852. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2853. */
  2854. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2855. var rotMat = MathTmp.Matrix[0];
  2856. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2857. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2858. };
  2859. Quaternion.Slerp = function (left, right, amount) {
  2860. var result = Quaternion.Identity();
  2861. Quaternion.SlerpToRef(left, right, amount, result);
  2862. return result;
  2863. };
  2864. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2865. var num2;
  2866. var num3;
  2867. var num = amount;
  2868. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2869. var flag = false;
  2870. if (num4 < 0) {
  2871. flag = true;
  2872. num4 = -num4;
  2873. }
  2874. if (num4 > 0.999999) {
  2875. num3 = 1 - num;
  2876. num2 = flag ? -num : num;
  2877. }
  2878. else {
  2879. var num5 = Math.acos(num4);
  2880. var num6 = (1.0 / Math.sin(num5));
  2881. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2882. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2883. }
  2884. result.x = (num3 * left.x) + (num2 * right.x);
  2885. result.y = (num3 * left.y) + (num2 * right.y);
  2886. result.z = (num3 * left.z) + (num2 * right.z);
  2887. result.w = (num3 * left.w) + (num2 * right.w);
  2888. };
  2889. /**
  2890. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2891. */
  2892. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2893. var squared = amount * amount;
  2894. var cubed = amount * squared;
  2895. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2896. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2897. var part3 = (cubed - (2.0 * squared)) + amount;
  2898. var part4 = cubed - squared;
  2899. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2900. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2901. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2902. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2903. return new Quaternion(x, y, z, w);
  2904. };
  2905. return Quaternion;
  2906. }());
  2907. BABYLON.Quaternion = Quaternion;
  2908. var Matrix = /** @class */ (function () {
  2909. function Matrix() {
  2910. this._isIdentity = false;
  2911. this._isIdentityDirty = true;
  2912. this.m = new Float32Array(16);
  2913. this._markAsUpdated();
  2914. }
  2915. Matrix.prototype._markAsUpdated = function () {
  2916. this.updateFlag = Matrix._updateFlagSeed++;
  2917. this._isIdentityDirty = true;
  2918. };
  2919. // Properties
  2920. /**
  2921. * Boolean : True is the matrix is the identity matrix
  2922. */
  2923. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  2924. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  2925. if (this._isIdentityDirty) {
  2926. this._isIdentityDirty = false;
  2927. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  2928. this._isIdentity = false;
  2929. }
  2930. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2931. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2932. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2933. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  2934. this._isIdentity = false;
  2935. }
  2936. else {
  2937. this._isIdentity = true;
  2938. }
  2939. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  2940. this._isIdentity = false;
  2941. }
  2942. }
  2943. return this._isIdentity;
  2944. };
  2945. /**
  2946. * Returns the matrix determinant (float).
  2947. */
  2948. Matrix.prototype.determinant = function () {
  2949. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2950. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2951. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2952. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2953. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2954. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2955. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2956. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2957. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2958. };
  2959. // Methods
  2960. /**
  2961. * Returns the matrix underlying array.
  2962. */
  2963. Matrix.prototype.toArray = function () {
  2964. return this.m;
  2965. };
  2966. /**
  2967. * Returns the matrix underlying array.
  2968. */
  2969. Matrix.prototype.asArray = function () {
  2970. return this.toArray();
  2971. };
  2972. /**
  2973. * Inverts in place the Matrix.
  2974. * Returns the Matrix inverted.
  2975. */
  2976. Matrix.prototype.invert = function () {
  2977. this.invertToRef(this);
  2978. return this;
  2979. };
  2980. /**
  2981. * Sets all the matrix elements to zero.
  2982. * Returns the Matrix.
  2983. */
  2984. Matrix.prototype.reset = function () {
  2985. for (var index = 0; index < 16; index++) {
  2986. this.m[index] = 0.0;
  2987. }
  2988. this._markAsUpdated();
  2989. return this;
  2990. };
  2991. /**
  2992. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2993. */
  2994. Matrix.prototype.add = function (other) {
  2995. var result = new Matrix();
  2996. this.addToRef(other, result);
  2997. return result;
  2998. };
  2999. /**
  3000. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  3001. * Returns the Matrix.
  3002. */
  3003. Matrix.prototype.addToRef = function (other, result) {
  3004. for (var index = 0; index < 16; index++) {
  3005. result.m[index] = this.m[index] + other.m[index];
  3006. }
  3007. result._markAsUpdated();
  3008. return this;
  3009. };
  3010. /**
  3011. * Adds in place the passed matrix to the current Matrix.
  3012. * Returns the updated Matrix.
  3013. */
  3014. Matrix.prototype.addToSelf = function (other) {
  3015. for (var index = 0; index < 16; index++) {
  3016. this.m[index] += other.m[index];
  3017. }
  3018. this._markAsUpdated();
  3019. return this;
  3020. };
  3021. /**
  3022. * Sets the passed matrix with the current inverted Matrix.
  3023. * Returns the unmodified current Matrix.
  3024. */
  3025. Matrix.prototype.invertToRef = function (other) {
  3026. var l1 = this.m[0];
  3027. var l2 = this.m[1];
  3028. var l3 = this.m[2];
  3029. var l4 = this.m[3];
  3030. var l5 = this.m[4];
  3031. var l6 = this.m[5];
  3032. var l7 = this.m[6];
  3033. var l8 = this.m[7];
  3034. var l9 = this.m[8];
  3035. var l10 = this.m[9];
  3036. var l11 = this.m[10];
  3037. var l12 = this.m[11];
  3038. var l13 = this.m[12];
  3039. var l14 = this.m[13];
  3040. var l15 = this.m[14];
  3041. var l16 = this.m[15];
  3042. var l17 = (l11 * l16) - (l12 * l15);
  3043. var l18 = (l10 * l16) - (l12 * l14);
  3044. var l19 = (l10 * l15) - (l11 * l14);
  3045. var l20 = (l9 * l16) - (l12 * l13);
  3046. var l21 = (l9 * l15) - (l11 * l13);
  3047. var l22 = (l9 * l14) - (l10 * l13);
  3048. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  3049. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  3050. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  3051. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  3052. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  3053. var l28 = (l7 * l16) - (l8 * l15);
  3054. var l29 = (l6 * l16) - (l8 * l14);
  3055. var l30 = (l6 * l15) - (l7 * l14);
  3056. var l31 = (l5 * l16) - (l8 * l13);
  3057. var l32 = (l5 * l15) - (l7 * l13);
  3058. var l33 = (l5 * l14) - (l6 * l13);
  3059. var l34 = (l7 * l12) - (l8 * l11);
  3060. var l35 = (l6 * l12) - (l8 * l10);
  3061. var l36 = (l6 * l11) - (l7 * l10);
  3062. var l37 = (l5 * l12) - (l8 * l9);
  3063. var l38 = (l5 * l11) - (l7 * l9);
  3064. var l39 = (l5 * l10) - (l6 * l9);
  3065. other.m[0] = l23 * l27;
  3066. other.m[4] = l24 * l27;
  3067. other.m[8] = l25 * l27;
  3068. other.m[12] = l26 * l27;
  3069. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  3070. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  3071. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  3072. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  3073. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  3074. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  3075. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  3076. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  3077. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  3078. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  3079. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  3080. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  3081. other._markAsUpdated();
  3082. return this;
  3083. };
  3084. /**
  3085. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  3086. * Returns the updated Matrix.
  3087. */
  3088. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  3089. this.m[12] = x;
  3090. this.m[13] = y;
  3091. this.m[14] = z;
  3092. this._markAsUpdated();
  3093. return this;
  3094. };
  3095. /**
  3096. * Inserts the translation vector in the current Matrix.
  3097. * Returns the updated Matrix.
  3098. */
  3099. Matrix.prototype.setTranslation = function (vector3) {
  3100. this.m[12] = vector3.x;
  3101. this.m[13] = vector3.y;
  3102. this.m[14] = vector3.z;
  3103. this._markAsUpdated();
  3104. return this;
  3105. };
  3106. /**
  3107. * Returns a new Vector3 as the extracted translation from the Matrix.
  3108. */
  3109. Matrix.prototype.getTranslation = function () {
  3110. return new Vector3(this.m[12], this.m[13], this.m[14]);
  3111. };
  3112. /**
  3113. * Fill a Vector3 with the extracted translation from the Matrix.
  3114. */
  3115. Matrix.prototype.getTranslationToRef = function (result) {
  3116. result.x = this.m[12];
  3117. result.y = this.m[13];
  3118. result.z = this.m[14];
  3119. return this;
  3120. };
  3121. /**
  3122. * Remove rotation and scaling part from the Matrix.
  3123. * Returns the updated Matrix.
  3124. */
  3125. Matrix.prototype.removeRotationAndScaling = function () {
  3126. this.setRowFromFloats(0, 1, 0, 0, 0);
  3127. this.setRowFromFloats(1, 0, 1, 0, 0);
  3128. this.setRowFromFloats(2, 0, 0, 1, 0);
  3129. return this;
  3130. };
  3131. /**
  3132. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  3133. */
  3134. Matrix.prototype.multiply = function (other) {
  3135. var result = new Matrix();
  3136. this.multiplyToRef(other, result);
  3137. return result;
  3138. };
  3139. /**
  3140. * Updates the current Matrix from the passed one values.
  3141. * Returns the updated Matrix.
  3142. */
  3143. Matrix.prototype.copyFrom = function (other) {
  3144. for (var index = 0; index < 16; index++) {
  3145. this.m[index] = other.m[index];
  3146. }
  3147. this._markAsUpdated();
  3148. return this;
  3149. };
  3150. /**
  3151. * Populates the passed array from the starting index with the Matrix values.
  3152. * Returns the Matrix.
  3153. */
  3154. Matrix.prototype.copyToArray = function (array, offset) {
  3155. if (offset === void 0) { offset = 0; }
  3156. for (var index = 0; index < 16; index++) {
  3157. array[offset + index] = this.m[index];
  3158. }
  3159. return this;
  3160. };
  3161. /**
  3162. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  3163. */
  3164. Matrix.prototype.multiplyToRef = function (other, result) {
  3165. this.multiplyToArray(other, result.m, 0);
  3166. result._markAsUpdated();
  3167. return this;
  3168. };
  3169. /**
  3170. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  3171. */
  3172. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  3173. var tm0 = this.m[0];
  3174. var tm1 = this.m[1];
  3175. var tm2 = this.m[2];
  3176. var tm3 = this.m[3];
  3177. var tm4 = this.m[4];
  3178. var tm5 = this.m[5];
  3179. var tm6 = this.m[6];
  3180. var tm7 = this.m[7];
  3181. var tm8 = this.m[8];
  3182. var tm9 = this.m[9];
  3183. var tm10 = this.m[10];
  3184. var tm11 = this.m[11];
  3185. var tm12 = this.m[12];
  3186. var tm13 = this.m[13];
  3187. var tm14 = this.m[14];
  3188. var tm15 = this.m[15];
  3189. var om0 = other.m[0];
  3190. var om1 = other.m[1];
  3191. var om2 = other.m[2];
  3192. var om3 = other.m[3];
  3193. var om4 = other.m[4];
  3194. var om5 = other.m[5];
  3195. var om6 = other.m[6];
  3196. var om7 = other.m[7];
  3197. var om8 = other.m[8];
  3198. var om9 = other.m[9];
  3199. var om10 = other.m[10];
  3200. var om11 = other.m[11];
  3201. var om12 = other.m[12];
  3202. var om13 = other.m[13];
  3203. var om14 = other.m[14];
  3204. var om15 = other.m[15];
  3205. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  3206. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  3207. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  3208. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  3209. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  3210. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  3211. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  3212. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  3213. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  3214. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  3215. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3216. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3217. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3218. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3219. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3220. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3221. return this;
  3222. };
  3223. /**
  3224. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3225. */
  3226. Matrix.prototype.equals = function (value) {
  3227. return value &&
  3228. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3229. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3230. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3231. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3232. };
  3233. /**
  3234. * Returns a new Matrix from the current Matrix.
  3235. */
  3236. Matrix.prototype.clone = function () {
  3237. 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]);
  3238. };
  3239. /**
  3240. * Returns the string "Matrix"
  3241. */
  3242. Matrix.prototype.getClassName = function () {
  3243. return "Matrix";
  3244. };
  3245. /**
  3246. * Returns the Matrix hash code.
  3247. */
  3248. Matrix.prototype.getHashCode = function () {
  3249. var hash = this.m[0] || 0;
  3250. for (var i = 1; i < 16; i++) {
  3251. hash = (hash * 397) ^ (this.m[i] || 0);
  3252. }
  3253. return hash;
  3254. };
  3255. /**
  3256. * Decomposes the current Matrix into :
  3257. * - a scale vector3 passed as a reference to update,
  3258. * - a rotation quaternion passed as a reference to update,
  3259. * - a translation vector3 passed as a reference to update.
  3260. * Returns the boolean `true`.
  3261. */
  3262. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3263. translation.x = this.m[12];
  3264. translation.y = this.m[13];
  3265. translation.z = this.m[14];
  3266. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3267. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3268. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3269. if (this.determinant() <= 0) {
  3270. scale.y *= -1;
  3271. }
  3272. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3273. rotation.x = 0;
  3274. rotation.y = 0;
  3275. rotation.z = 0;
  3276. rotation.w = 1;
  3277. return false;
  3278. }
  3279. 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]);
  3280. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3281. return true;
  3282. };
  3283. /**
  3284. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3285. */
  3286. Matrix.prototype.getRotationMatrix = function () {
  3287. var result = Matrix.Identity();
  3288. this.getRotationMatrixToRef(result);
  3289. return result;
  3290. };
  3291. /**
  3292. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3293. * Returns the current Matrix.
  3294. */
  3295. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3296. var m = this.m;
  3297. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3298. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3299. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3300. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3301. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3302. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3303. 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);
  3304. return this;
  3305. };
  3306. // Statics
  3307. /**
  3308. * Returns a new Matrix set from the starting index of the passed array.
  3309. */
  3310. Matrix.FromArray = function (array, offset) {
  3311. var result = new Matrix();
  3312. if (!offset) {
  3313. offset = 0;
  3314. }
  3315. Matrix.FromArrayToRef(array, offset, result);
  3316. return result;
  3317. };
  3318. /**
  3319. * Sets the passed "result" matrix from the starting index of the passed array.
  3320. */
  3321. Matrix.FromArrayToRef = function (array, offset, result) {
  3322. for (var index = 0; index < 16; index++) {
  3323. result.m[index] = array[index + offset];
  3324. }
  3325. result._markAsUpdated();
  3326. };
  3327. /**
  3328. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3329. */
  3330. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3331. for (var index = 0; index < 16; index++) {
  3332. result.m[index] = array[index + offset] * scale;
  3333. }
  3334. result._markAsUpdated();
  3335. };
  3336. /**
  3337. * Sets the passed matrix "result" with the 16 passed floats.
  3338. */
  3339. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3340. result.m[0] = initialM11;
  3341. result.m[1] = initialM12;
  3342. result.m[2] = initialM13;
  3343. result.m[3] = initialM14;
  3344. result.m[4] = initialM21;
  3345. result.m[5] = initialM22;
  3346. result.m[6] = initialM23;
  3347. result.m[7] = initialM24;
  3348. result.m[8] = initialM31;
  3349. result.m[9] = initialM32;
  3350. result.m[10] = initialM33;
  3351. result.m[11] = initialM34;
  3352. result.m[12] = initialM41;
  3353. result.m[13] = initialM42;
  3354. result.m[14] = initialM43;
  3355. result.m[15] = initialM44;
  3356. result._markAsUpdated();
  3357. };
  3358. /**
  3359. * Returns the index-th row of the current matrix as a new Vector4.
  3360. */
  3361. Matrix.prototype.getRow = function (index) {
  3362. if (index < 0 || index > 3) {
  3363. return null;
  3364. }
  3365. var i = index * 4;
  3366. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3367. };
  3368. /**
  3369. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3370. * Returns the updated Matrix.
  3371. */
  3372. Matrix.prototype.setRow = function (index, row) {
  3373. if (index < 0 || index > 3) {
  3374. return this;
  3375. }
  3376. var i = index * 4;
  3377. this.m[i + 0] = row.x;
  3378. this.m[i + 1] = row.y;
  3379. this.m[i + 2] = row.z;
  3380. this.m[i + 3] = row.w;
  3381. this._markAsUpdated();
  3382. return this;
  3383. };
  3384. /**
  3385. * Compute the transpose of the matrix.
  3386. * Returns a new Matrix.
  3387. */
  3388. Matrix.prototype.transpose = function () {
  3389. return Matrix.Transpose(this);
  3390. };
  3391. /**
  3392. * Compute the transpose of the matrix.
  3393. * Returns the current matrix.
  3394. */
  3395. Matrix.prototype.transposeToRef = function (result) {
  3396. Matrix.TransposeToRef(this, result);
  3397. return this;
  3398. };
  3399. /**
  3400. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3401. * Returns the updated Matrix.
  3402. */
  3403. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3404. if (index < 0 || index > 3) {
  3405. return this;
  3406. }
  3407. var i = index * 4;
  3408. this.m[i + 0] = x;
  3409. this.m[i + 1] = y;
  3410. this.m[i + 2] = z;
  3411. this.m[i + 3] = w;
  3412. this._markAsUpdated();
  3413. return this;
  3414. };
  3415. Object.defineProperty(Matrix, "IdentityReadOnly", {
  3416. /**
  3417. * Static identity matrix to be used as readonly matrix
  3418. * Must not be updated.
  3419. */
  3420. get: function () {
  3421. return Matrix._identityReadOnly;
  3422. },
  3423. enumerable: true,
  3424. configurable: true
  3425. });
  3426. /**
  3427. * Returns a new Matrix set from the 16 passed floats.
  3428. */
  3429. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3430. var result = new Matrix();
  3431. result.m[0] = initialM11;
  3432. result.m[1] = initialM12;
  3433. result.m[2] = initialM13;
  3434. result.m[3] = initialM14;
  3435. result.m[4] = initialM21;
  3436. result.m[5] = initialM22;
  3437. result.m[6] = initialM23;
  3438. result.m[7] = initialM24;
  3439. result.m[8] = initialM31;
  3440. result.m[9] = initialM32;
  3441. result.m[10] = initialM33;
  3442. result.m[11] = initialM34;
  3443. result.m[12] = initialM41;
  3444. result.m[13] = initialM42;
  3445. result.m[14] = initialM43;
  3446. result.m[15] = initialM44;
  3447. return result;
  3448. };
  3449. /**
  3450. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3451. */
  3452. Matrix.Compose = function (scale, rotation, translation) {
  3453. var result = Matrix.Identity();
  3454. Matrix.ComposeToRef(scale, rotation, translation, result);
  3455. return result;
  3456. };
  3457. /**
  3458. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3459. */
  3460. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3461. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3462. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3463. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3464. result.setTranslation(translation);
  3465. };
  3466. /**
  3467. * Returns a new indentity Matrix.
  3468. */
  3469. Matrix.Identity = function () {
  3470. 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);
  3471. };
  3472. /**
  3473. * Sets the passed "result" as an identity matrix.
  3474. */
  3475. Matrix.IdentityToRef = function (result) {
  3476. 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);
  3477. };
  3478. /**
  3479. * Returns a new zero Matrix.
  3480. */
  3481. Matrix.Zero = function () {
  3482. 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);
  3483. };
  3484. /**
  3485. * Returns a new rotation matrix for "angle" radians around the X axis.
  3486. */
  3487. Matrix.RotationX = function (angle) {
  3488. var result = new Matrix();
  3489. Matrix.RotationXToRef(angle, result);
  3490. return result;
  3491. };
  3492. /**
  3493. * Returns a new Matrix as the passed inverted one.
  3494. */
  3495. Matrix.Invert = function (source) {
  3496. var result = new Matrix();
  3497. source.invertToRef(result);
  3498. return result;
  3499. };
  3500. /**
  3501. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3502. */
  3503. Matrix.RotationXToRef = function (angle, result) {
  3504. var s = Math.sin(angle);
  3505. var c = Math.cos(angle);
  3506. result.m[0] = 1.0;
  3507. result.m[15] = 1.0;
  3508. result.m[5] = c;
  3509. result.m[10] = c;
  3510. result.m[9] = -s;
  3511. result.m[6] = s;
  3512. result.m[1] = 0.0;
  3513. result.m[2] = 0.0;
  3514. result.m[3] = 0.0;
  3515. result.m[4] = 0.0;
  3516. result.m[7] = 0.0;
  3517. result.m[8] = 0.0;
  3518. result.m[11] = 0.0;
  3519. result.m[12] = 0.0;
  3520. result.m[13] = 0.0;
  3521. result.m[14] = 0.0;
  3522. result._markAsUpdated();
  3523. };
  3524. /**
  3525. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3526. */
  3527. Matrix.RotationY = function (angle) {
  3528. var result = new Matrix();
  3529. Matrix.RotationYToRef(angle, result);
  3530. return result;
  3531. };
  3532. /**
  3533. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3534. */
  3535. Matrix.RotationYToRef = function (angle, result) {
  3536. var s = Math.sin(angle);
  3537. var c = Math.cos(angle);
  3538. result.m[5] = 1.0;
  3539. result.m[15] = 1.0;
  3540. result.m[0] = c;
  3541. result.m[2] = -s;
  3542. result.m[8] = s;
  3543. result.m[10] = c;
  3544. result.m[1] = 0.0;
  3545. result.m[3] = 0.0;
  3546. result.m[4] = 0.0;
  3547. result.m[6] = 0.0;
  3548. result.m[7] = 0.0;
  3549. result.m[9] = 0.0;
  3550. result.m[11] = 0.0;
  3551. result.m[12] = 0.0;
  3552. result.m[13] = 0.0;
  3553. result.m[14] = 0.0;
  3554. result._markAsUpdated();
  3555. };
  3556. /**
  3557. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3558. */
  3559. Matrix.RotationZ = function (angle) {
  3560. var result = new Matrix();
  3561. Matrix.RotationZToRef(angle, result);
  3562. return result;
  3563. };
  3564. /**
  3565. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3566. */
  3567. Matrix.RotationZToRef = function (angle, result) {
  3568. var s = Math.sin(angle);
  3569. var c = Math.cos(angle);
  3570. result.m[10] = 1.0;
  3571. result.m[15] = 1.0;
  3572. result.m[0] = c;
  3573. result.m[1] = s;
  3574. result.m[4] = -s;
  3575. result.m[5] = c;
  3576. result.m[2] = 0.0;
  3577. result.m[3] = 0.0;
  3578. result.m[6] = 0.0;
  3579. result.m[7] = 0.0;
  3580. result.m[8] = 0.0;
  3581. result.m[9] = 0.0;
  3582. result.m[11] = 0.0;
  3583. result.m[12] = 0.0;
  3584. result.m[13] = 0.0;
  3585. result.m[14] = 0.0;
  3586. result._markAsUpdated();
  3587. };
  3588. /**
  3589. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3590. */
  3591. Matrix.RotationAxis = function (axis, angle) {
  3592. var result = Matrix.Zero();
  3593. Matrix.RotationAxisToRef(axis, angle, result);
  3594. return result;
  3595. };
  3596. /**
  3597. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3598. */
  3599. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3600. var s = Math.sin(-angle);
  3601. var c = Math.cos(-angle);
  3602. var c1 = 1 - c;
  3603. axis.normalize();
  3604. result.m[0] = (axis.x * axis.x) * c1 + c;
  3605. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3606. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3607. result.m[3] = 0.0;
  3608. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3609. result.m[5] = (axis.y * axis.y) * c1 + c;
  3610. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3611. result.m[7] = 0.0;
  3612. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3613. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3614. result.m[10] = (axis.z * axis.z) * c1 + c;
  3615. result.m[11] = 0.0;
  3616. result.m[15] = 1.0;
  3617. result._markAsUpdated();
  3618. };
  3619. /**
  3620. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3621. */
  3622. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3623. var result = new Matrix();
  3624. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3625. return result;
  3626. };
  3627. /**
  3628. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3629. */
  3630. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3631. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3632. this._tempQuaternion.toRotationMatrix(result);
  3633. };
  3634. /**
  3635. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3636. */
  3637. Matrix.Scaling = function (x, y, z) {
  3638. var result = Matrix.Zero();
  3639. Matrix.ScalingToRef(x, y, z, result);
  3640. return result;
  3641. };
  3642. /**
  3643. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3644. */
  3645. Matrix.ScalingToRef = function (x, y, z, result) {
  3646. result.m[0] = x;
  3647. result.m[1] = 0.0;
  3648. result.m[2] = 0.0;
  3649. result.m[3] = 0.0;
  3650. result.m[4] = 0.0;
  3651. result.m[5] = y;
  3652. result.m[6] = 0.0;
  3653. result.m[7] = 0.0;
  3654. result.m[8] = 0.0;
  3655. result.m[9] = 0.0;
  3656. result.m[10] = z;
  3657. result.m[11] = 0.0;
  3658. result.m[12] = 0.0;
  3659. result.m[13] = 0.0;
  3660. result.m[14] = 0.0;
  3661. result.m[15] = 1.0;
  3662. result._markAsUpdated();
  3663. };
  3664. /**
  3665. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3666. */
  3667. Matrix.Translation = function (x, y, z) {
  3668. var result = Matrix.Identity();
  3669. Matrix.TranslationToRef(x, y, z, result);
  3670. return result;
  3671. };
  3672. /**
  3673. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3674. */
  3675. Matrix.TranslationToRef = function (x, y, z, result) {
  3676. 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);
  3677. };
  3678. /**
  3679. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3680. */
  3681. Matrix.Lerp = function (startValue, endValue, gradient) {
  3682. var result = Matrix.Zero();
  3683. for (var index = 0; index < 16; index++) {
  3684. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3685. }
  3686. result._markAsUpdated();
  3687. return result;
  3688. };
  3689. /**
  3690. * Returns a new Matrix whose values are computed by :
  3691. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3692. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3693. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3694. */
  3695. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3696. var startScale = new Vector3(0, 0, 0);
  3697. var startRotation = new Quaternion();
  3698. var startTranslation = new Vector3(0, 0, 0);
  3699. startValue.decompose(startScale, startRotation, startTranslation);
  3700. var endScale = new Vector3(0, 0, 0);
  3701. var endRotation = new Quaternion();
  3702. var endTranslation = new Vector3(0, 0, 0);
  3703. endValue.decompose(endScale, endRotation, endTranslation);
  3704. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3705. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3706. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3707. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3708. };
  3709. /**
  3710. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3711. * This methods works for a Left-Handed system.
  3712. */
  3713. Matrix.LookAtLH = function (eye, target, up) {
  3714. var result = Matrix.Zero();
  3715. Matrix.LookAtLHToRef(eye, target, up, result);
  3716. return result;
  3717. };
  3718. /**
  3719. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3720. * This methods works for a Left-Handed system.
  3721. */
  3722. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3723. // Z axis
  3724. target.subtractToRef(eye, this._zAxis);
  3725. this._zAxis.normalize();
  3726. // X axis
  3727. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3728. if (this._xAxis.lengthSquared() === 0) {
  3729. this._xAxis.x = 1.0;
  3730. }
  3731. else {
  3732. this._xAxis.normalize();
  3733. }
  3734. // Y axis
  3735. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3736. this._yAxis.normalize();
  3737. // Eye angles
  3738. var ex = -Vector3.Dot(this._xAxis, eye);
  3739. var ey = -Vector3.Dot(this._yAxis, eye);
  3740. var ez = -Vector3.Dot(this._zAxis, eye);
  3741. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  3742. };
  3743. /**
  3744. * Returns a new 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".
  3745. * This methods works for a Right-Handed system.
  3746. */
  3747. Matrix.LookAtRH = function (eye, target, up) {
  3748. var result = Matrix.Zero();
  3749. Matrix.LookAtRHToRef(eye, target, up, result);
  3750. return result;
  3751. };
  3752. /**
  3753. * 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".
  3754. * This methods works for a Left-Handed system.
  3755. */
  3756. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3757. // Z axis
  3758. eye.subtractToRef(target, this._zAxis);
  3759. this._zAxis.normalize();
  3760. // X axis
  3761. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3762. if (this._xAxis.lengthSquared() === 0) {
  3763. this._xAxis.x = 1.0;
  3764. }
  3765. else {
  3766. this._xAxis.normalize();
  3767. }
  3768. // Y axis
  3769. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3770. this._yAxis.normalize();
  3771. // Eye angles
  3772. var ex = -Vector3.Dot(this._xAxis, eye);
  3773. var ey = -Vector3.Dot(this._yAxis, eye);
  3774. var ez = -Vector3.Dot(this._zAxis, eye);
  3775. 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);
  3776. };
  3777. /**
  3778. * 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.
  3779. */
  3780. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3781. var matrix = Matrix.Zero();
  3782. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3783. return matrix;
  3784. };
  3785. /**
  3786. * 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.
  3787. */
  3788. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3789. var n = znear;
  3790. var f = zfar;
  3791. var a = 2.0 / width;
  3792. var b = 2.0 / height;
  3793. var c = 2.0 / (f - n);
  3794. var d = -(f + n) / (f - n);
  3795. 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);
  3796. };
  3797. /**
  3798. * 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.
  3799. */
  3800. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3801. var matrix = Matrix.Zero();
  3802. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3803. return matrix;
  3804. };
  3805. /**
  3806. * 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.
  3807. */
  3808. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3809. var n = znear;
  3810. var f = zfar;
  3811. var a = 2.0 / (right - left);
  3812. var b = 2.0 / (top - bottom);
  3813. var c = 2.0 / (f - n);
  3814. var d = -(f + n) / (f - n);
  3815. var i0 = (left + right) / (left - right);
  3816. var i1 = (top + bottom) / (bottom - top);
  3817. 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);
  3818. };
  3819. /**
  3820. * 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.
  3821. */
  3822. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3823. var matrix = Matrix.Zero();
  3824. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3825. return matrix;
  3826. };
  3827. /**
  3828. * 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.
  3829. */
  3830. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3831. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3832. result.m[10] *= -1.0;
  3833. };
  3834. /**
  3835. * 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.
  3836. */
  3837. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3838. var matrix = Matrix.Zero();
  3839. var n = znear;
  3840. var f = zfar;
  3841. var a = 2.0 * n / width;
  3842. var b = 2.0 * n / height;
  3843. var c = (f + n) / (f - n);
  3844. var d = -2.0 * f * n / (f - n);
  3845. 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);
  3846. return matrix;
  3847. };
  3848. /**
  3849. * 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.
  3850. */
  3851. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3852. var matrix = Matrix.Zero();
  3853. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3854. return matrix;
  3855. };
  3856. /**
  3857. * 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.
  3858. */
  3859. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3860. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3861. var n = znear;
  3862. var f = zfar;
  3863. var t = 1.0 / (Math.tan(fov * 0.5));
  3864. var a = isVerticalFovFixed ? (t / aspect) : t;
  3865. var b = isVerticalFovFixed ? t : (t * aspect);
  3866. var c = (f + n) / (f - n);
  3867. var d = -2.0 * f * n / (f - n);
  3868. 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);
  3869. };
  3870. /**
  3871. * 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.
  3872. */
  3873. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3874. var matrix = Matrix.Zero();
  3875. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3876. return matrix;
  3877. };
  3878. /**
  3879. * 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.
  3880. */
  3881. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3882. //alternatively this could be expressed as:
  3883. // m = PerspectiveFovLHToRef
  3884. // m[10] *= -1.0;
  3885. // m[11] *= -1.0;
  3886. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3887. var n = znear;
  3888. var f = zfar;
  3889. var t = 1.0 / (Math.tan(fov * 0.5));
  3890. var a = isVerticalFovFixed ? (t / aspect) : t;
  3891. var b = isVerticalFovFixed ? t : (t * aspect);
  3892. var c = -(f + n) / (f - n);
  3893. var d = -2 * f * n / (f - n);
  3894. 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);
  3895. };
  3896. /**
  3897. * 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.
  3898. */
  3899. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3900. if (rightHanded === void 0) { rightHanded = false; }
  3901. var rightHandedFactor = rightHanded ? -1 : 1;
  3902. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3903. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3904. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3905. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3906. var xScale = 2.0 / (leftTan + rightTan);
  3907. var yScale = 2.0 / (upTan + downTan);
  3908. result.m[0] = xScale;
  3909. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3910. result.m[5] = yScale;
  3911. result.m[6] = result.m[7] = 0.0;
  3912. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3913. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3914. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3915. result.m[10] = -zfar / (znear - zfar);
  3916. result.m[11] = 1.0 * rightHandedFactor;
  3917. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3918. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3919. // result.m[14] = (znear * zfar) / (znear - zfar);
  3920. result._markAsUpdated();
  3921. };
  3922. /**
  3923. * Returns the final transformation matrix : world * view * projection * viewport
  3924. */
  3925. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3926. var cw = viewport.width;
  3927. var ch = viewport.height;
  3928. var cx = viewport.x;
  3929. var cy = viewport.y;
  3930. 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);
  3931. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3932. };
  3933. /**
  3934. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3935. */
  3936. Matrix.GetAsMatrix2x2 = function (matrix) {
  3937. return new Float32Array([
  3938. matrix.m[0], matrix.m[1],
  3939. matrix.m[4], matrix.m[5]
  3940. ]);
  3941. };
  3942. /**
  3943. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3944. */
  3945. Matrix.GetAsMatrix3x3 = function (matrix) {
  3946. return new Float32Array([
  3947. matrix.m[0], matrix.m[1], matrix.m[2],
  3948. matrix.m[4], matrix.m[5], matrix.m[6],
  3949. matrix.m[8], matrix.m[9], matrix.m[10]
  3950. ]);
  3951. };
  3952. /**
  3953. * Compute the transpose of the passed Matrix.
  3954. * Returns a new Matrix.
  3955. */
  3956. Matrix.Transpose = function (matrix) {
  3957. var result = new Matrix();
  3958. Matrix.TransposeToRef(matrix, result);
  3959. return result;
  3960. };
  3961. /**
  3962. * Compute the transpose of the passed Matrix and store it in the result matrix.
  3963. */
  3964. Matrix.TransposeToRef = function (matrix, result) {
  3965. result.m[0] = matrix.m[0];
  3966. result.m[1] = matrix.m[4];
  3967. result.m[2] = matrix.m[8];
  3968. result.m[3] = matrix.m[12];
  3969. result.m[4] = matrix.m[1];
  3970. result.m[5] = matrix.m[5];
  3971. result.m[6] = matrix.m[9];
  3972. result.m[7] = matrix.m[13];
  3973. result.m[8] = matrix.m[2];
  3974. result.m[9] = matrix.m[6];
  3975. result.m[10] = matrix.m[10];
  3976. result.m[11] = matrix.m[14];
  3977. result.m[12] = matrix.m[3];
  3978. result.m[13] = matrix.m[7];
  3979. result.m[14] = matrix.m[11];
  3980. result.m[15] = matrix.m[15];
  3981. };
  3982. /**
  3983. * Returns a new Matrix as the reflection matrix across the passed plane.
  3984. */
  3985. Matrix.Reflection = function (plane) {
  3986. var matrix = new Matrix();
  3987. Matrix.ReflectionToRef(plane, matrix);
  3988. return matrix;
  3989. };
  3990. /**
  3991. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3992. */
  3993. Matrix.ReflectionToRef = function (plane, result) {
  3994. plane.normalize();
  3995. var x = plane.normal.x;
  3996. var y = plane.normal.y;
  3997. var z = plane.normal.z;
  3998. var temp = -2 * x;
  3999. var temp2 = -2 * y;
  4000. var temp3 = -2 * z;
  4001. result.m[0] = (temp * x) + 1;
  4002. result.m[1] = temp2 * x;
  4003. result.m[2] = temp3 * x;
  4004. result.m[3] = 0.0;
  4005. result.m[4] = temp * y;
  4006. result.m[5] = (temp2 * y) + 1;
  4007. result.m[6] = temp3 * y;
  4008. result.m[7] = 0.0;
  4009. result.m[8] = temp * z;
  4010. result.m[9] = temp2 * z;
  4011. result.m[10] = (temp3 * z) + 1;
  4012. result.m[11] = 0.0;
  4013. result.m[12] = temp * plane.d;
  4014. result.m[13] = temp2 * plane.d;
  4015. result.m[14] = temp3 * plane.d;
  4016. result.m[15] = 1.0;
  4017. result._markAsUpdated();
  4018. };
  4019. /**
  4020. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  4021. */
  4022. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  4023. result.m[0] = xaxis.x;
  4024. result.m[1] = xaxis.y;
  4025. result.m[2] = xaxis.z;
  4026. result.m[3] = 0.0;
  4027. result.m[4] = yaxis.x;
  4028. result.m[5] = yaxis.y;
  4029. result.m[6] = yaxis.z;
  4030. result.m[7] = 0.0;
  4031. result.m[8] = zaxis.x;
  4032. result.m[9] = zaxis.y;
  4033. result.m[10] = zaxis.z;
  4034. result.m[11] = 0.0;
  4035. result.m[12] = 0.0;
  4036. result.m[13] = 0.0;
  4037. result.m[14] = 0.0;
  4038. result.m[15] = 1.0;
  4039. result._markAsUpdated();
  4040. };
  4041. /**
  4042. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  4043. */
  4044. Matrix.FromQuaternionToRef = function (quat, result) {
  4045. var xx = quat.x * quat.x;
  4046. var yy = quat.y * quat.y;
  4047. var zz = quat.z * quat.z;
  4048. var xy = quat.x * quat.y;
  4049. var zw = quat.z * quat.w;
  4050. var zx = quat.z * quat.x;
  4051. var yw = quat.y * quat.w;
  4052. var yz = quat.y * quat.z;
  4053. var xw = quat.x * quat.w;
  4054. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4055. result.m[1] = 2.0 * (xy + zw);
  4056. result.m[2] = 2.0 * (zx - yw);
  4057. result.m[3] = 0.0;
  4058. result.m[4] = 2.0 * (xy - zw);
  4059. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4060. result.m[6] = 2.0 * (yz + xw);
  4061. result.m[7] = 0.0;
  4062. result.m[8] = 2.0 * (zx + yw);
  4063. result.m[9] = 2.0 * (yz - xw);
  4064. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4065. result.m[11] = 0.0;
  4066. result.m[12] = 0.0;
  4067. result.m[13] = 0.0;
  4068. result.m[14] = 0.0;
  4069. result.m[15] = 1.0;
  4070. result._markAsUpdated();
  4071. };
  4072. Matrix._tempQuaternion = new Quaternion();
  4073. Matrix._xAxis = Vector3.Zero();
  4074. Matrix._yAxis = Vector3.Zero();
  4075. Matrix._zAxis = Vector3.Zero();
  4076. Matrix._updateFlagSeed = 0;
  4077. Matrix._identityReadOnly = Matrix.Identity();
  4078. return Matrix;
  4079. }());
  4080. BABYLON.Matrix = Matrix;
  4081. var Plane = /** @class */ (function () {
  4082. /**
  4083. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  4084. */
  4085. function Plane(a, b, c, d) {
  4086. this.normal = new Vector3(a, b, c);
  4087. this.d = d;
  4088. }
  4089. /**
  4090. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  4091. */
  4092. Plane.prototype.asArray = function () {
  4093. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  4094. };
  4095. // Methods
  4096. /**
  4097. * Returns a new plane copied from the current Plane.
  4098. */
  4099. Plane.prototype.clone = function () {
  4100. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  4101. };
  4102. /**
  4103. * Returns the string "Plane".
  4104. */
  4105. Plane.prototype.getClassName = function () {
  4106. return "Plane";
  4107. };
  4108. /**
  4109. * Returns the Plane hash code.
  4110. */
  4111. Plane.prototype.getHashCode = function () {
  4112. var hash = this.normal.getHashCode();
  4113. hash = (hash * 397) ^ (this.d || 0);
  4114. return hash;
  4115. };
  4116. /**
  4117. * Normalize the current Plane in place.
  4118. * Returns the updated Plane.
  4119. */
  4120. Plane.prototype.normalize = function () {
  4121. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  4122. var magnitude = 0.0;
  4123. if (norm !== 0) {
  4124. magnitude = 1.0 / norm;
  4125. }
  4126. this.normal.x *= magnitude;
  4127. this.normal.y *= magnitude;
  4128. this.normal.z *= magnitude;
  4129. this.d *= magnitude;
  4130. return this;
  4131. };
  4132. /**
  4133. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  4134. */
  4135. Plane.prototype.transform = function (transformation) {
  4136. var transposedMatrix = Matrix.Transpose(transformation);
  4137. var x = this.normal.x;
  4138. var y = this.normal.y;
  4139. var z = this.normal.z;
  4140. var d = this.d;
  4141. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  4142. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  4143. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  4144. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  4145. return new Plane(normalX, normalY, normalZ, finalD);
  4146. };
  4147. /**
  4148. * Returns the dot product (float) of the point coordinates and the plane normal.
  4149. */
  4150. Plane.prototype.dotCoordinate = function (point) {
  4151. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  4152. };
  4153. /**
  4154. * Updates the current Plane from the plane defined by the three passed points.
  4155. * Returns the updated Plane.
  4156. */
  4157. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  4158. var x1 = point2.x - point1.x;
  4159. var y1 = point2.y - point1.y;
  4160. var z1 = point2.z - point1.z;
  4161. var x2 = point3.x - point1.x;
  4162. var y2 = point3.y - point1.y;
  4163. var z2 = point3.z - point1.z;
  4164. var yz = (y1 * z2) - (z1 * y2);
  4165. var xz = (z1 * x2) - (x1 * z2);
  4166. var xy = (x1 * y2) - (y1 * x2);
  4167. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  4168. var invPyth;
  4169. if (pyth !== 0) {
  4170. invPyth = 1.0 / pyth;
  4171. }
  4172. else {
  4173. invPyth = 0.0;
  4174. }
  4175. this.normal.x = yz * invPyth;
  4176. this.normal.y = xz * invPyth;
  4177. this.normal.z = xy * invPyth;
  4178. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  4179. return this;
  4180. };
  4181. /**
  4182. * Boolean : True is the vector "direction" is the same side than the plane normal.
  4183. */
  4184. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  4185. var dot = Vector3.Dot(this.normal, direction);
  4186. return (dot <= epsilon);
  4187. };
  4188. /**
  4189. * Returns the signed distance (float) from the passed point to the Plane.
  4190. */
  4191. Plane.prototype.signedDistanceTo = function (point) {
  4192. return Vector3.Dot(point, this.normal) + this.d;
  4193. };
  4194. // Statics
  4195. /**
  4196. * Returns a new Plane from the passed array.
  4197. */
  4198. Plane.FromArray = function (array) {
  4199. return new Plane(array[0], array[1], array[2], array[3]);
  4200. };
  4201. /**
  4202. * Returns a new Plane defined by the three passed points.
  4203. */
  4204. Plane.FromPoints = function (point1, point2, point3) {
  4205. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4206. result.copyFromPoints(point1, point2, point3);
  4207. return result;
  4208. };
  4209. /**
  4210. * Returns a new Plane the normal vector to this plane at the passed origin point.
  4211. * Note : the vector "normal" is updated because normalized.
  4212. */
  4213. Plane.FromPositionAndNormal = function (origin, normal) {
  4214. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4215. normal.normalize();
  4216. result.normal = normal;
  4217. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4218. return result;
  4219. };
  4220. /**
  4221. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  4222. */
  4223. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  4224. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4225. return Vector3.Dot(point, normal) + d;
  4226. };
  4227. return Plane;
  4228. }());
  4229. BABYLON.Plane = Plane;
  4230. var Viewport = /** @class */ (function () {
  4231. /**
  4232. * Creates a Viewport object located at (x, y) and sized (width, height).
  4233. */
  4234. function Viewport(x, y, width, height) {
  4235. this.x = x;
  4236. this.y = y;
  4237. this.width = width;
  4238. this.height = height;
  4239. }
  4240. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  4241. if (renderWidthOrEngine.getRenderWidth) {
  4242. var engine = renderWidthOrEngine;
  4243. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4244. }
  4245. var renderWidth = renderWidthOrEngine;
  4246. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  4247. };
  4248. /**
  4249. * Returns a new Viewport copied from the current one.
  4250. */
  4251. Viewport.prototype.clone = function () {
  4252. return new Viewport(this.x, this.y, this.width, this.height);
  4253. };
  4254. return Viewport;
  4255. }());
  4256. BABYLON.Viewport = Viewport;
  4257. var Frustum = /** @class */ (function () {
  4258. function Frustum() {
  4259. }
  4260. /**
  4261. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4262. */
  4263. Frustum.GetPlanes = function (transform) {
  4264. var frustumPlanes = [];
  4265. for (var index = 0; index < 6; index++) {
  4266. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4267. }
  4268. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4269. return frustumPlanes;
  4270. };
  4271. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  4272. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  4273. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  4274. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  4275. frustumPlane.d = transform.m[15] + transform.m[14];
  4276. frustumPlane.normalize();
  4277. };
  4278. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  4279. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  4280. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  4281. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  4282. frustumPlane.d = transform.m[15] - transform.m[14];
  4283. frustumPlane.normalize();
  4284. };
  4285. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  4286. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  4287. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  4288. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  4289. frustumPlane.d = transform.m[15] + transform.m[12];
  4290. frustumPlane.normalize();
  4291. };
  4292. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  4293. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  4294. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  4295. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  4296. frustumPlane.d = transform.m[15] - transform.m[12];
  4297. frustumPlane.normalize();
  4298. };
  4299. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  4300. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  4301. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  4302. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  4303. frustumPlane.d = transform.m[15] - transform.m[13];
  4304. frustumPlane.normalize();
  4305. };
  4306. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  4307. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  4308. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  4309. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  4310. frustumPlane.d = transform.m[15] + transform.m[13];
  4311. frustumPlane.normalize();
  4312. };
  4313. /**
  4314. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4315. */
  4316. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4317. // Near
  4318. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  4319. // Far
  4320. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  4321. // Left
  4322. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  4323. // Right
  4324. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  4325. // Top
  4326. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  4327. // Bottom
  4328. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  4329. };
  4330. return Frustum;
  4331. }());
  4332. BABYLON.Frustum = Frustum;
  4333. var Space;
  4334. (function (Space) {
  4335. Space[Space["LOCAL"] = 0] = "LOCAL";
  4336. Space[Space["WORLD"] = 1] = "WORLD";
  4337. Space[Space["BONE"] = 2] = "BONE";
  4338. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4339. var Axis = /** @class */ (function () {
  4340. function Axis() {
  4341. }
  4342. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4343. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4344. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4345. return Axis;
  4346. }());
  4347. BABYLON.Axis = Axis;
  4348. ;
  4349. var BezierCurve = /** @class */ (function () {
  4350. function BezierCurve() {
  4351. }
  4352. /**
  4353. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4354. */
  4355. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4356. // Extract X (which is equal to time here)
  4357. var f0 = 1 - 3 * x2 + 3 * x1;
  4358. var f1 = 3 * x2 - 6 * x1;
  4359. var f2 = 3 * x1;
  4360. var refinedT = t;
  4361. for (var i = 0; i < 5; i++) {
  4362. var refinedT2 = refinedT * refinedT;
  4363. var refinedT3 = refinedT2 * refinedT;
  4364. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4365. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4366. refinedT -= (x - t) * slope;
  4367. refinedT = Math.min(1, Math.max(0, refinedT));
  4368. }
  4369. // Resolve cubic bezier for the given x
  4370. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4371. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4372. Math.pow(refinedT, 3);
  4373. };
  4374. return BezierCurve;
  4375. }());
  4376. BABYLON.BezierCurve = BezierCurve;
  4377. var Orientation;
  4378. (function (Orientation) {
  4379. Orientation[Orientation["CW"] = 0] = "CW";
  4380. Orientation[Orientation["CCW"] = 1] = "CCW";
  4381. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4382. var Angle = /** @class */ (function () {
  4383. /**
  4384. * Creates an Angle object of "radians" radians (float).
  4385. */
  4386. function Angle(radians) {
  4387. var _this = this;
  4388. /**
  4389. * Returns the Angle value in degrees (float).
  4390. */
  4391. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4392. /**
  4393. * Returns the Angle value in radians (float).
  4394. */
  4395. this.radians = function () { return _this._radians; };
  4396. this._radians = radians;
  4397. if (this._radians < 0.0)
  4398. this._radians += (2.0 * Math.PI);
  4399. }
  4400. /**
  4401. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4402. */
  4403. Angle.BetweenTwoPoints = function (a, b) {
  4404. var delta = b.subtract(a);
  4405. var theta = Math.atan2(delta.y, delta.x);
  4406. return new Angle(theta);
  4407. };
  4408. /**
  4409. * Returns a new Angle object from the passed float in radians.
  4410. */
  4411. Angle.FromRadians = function (radians) {
  4412. return new Angle(radians);
  4413. };
  4414. /**
  4415. * Returns a new Angle object from the passed float in degrees.
  4416. */
  4417. Angle.FromDegrees = function (degrees) {
  4418. return new Angle(degrees * Math.PI / 180.0);
  4419. };
  4420. return Angle;
  4421. }());
  4422. BABYLON.Angle = Angle;
  4423. var Arc2 = /** @class */ (function () {
  4424. /**
  4425. * Creates an Arc object from the three passed points : start, middle and end.
  4426. */
  4427. function Arc2(startPoint, midPoint, endPoint) {
  4428. this.startPoint = startPoint;
  4429. this.midPoint = midPoint;
  4430. this.endPoint = endPoint;
  4431. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4432. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4433. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4434. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4435. 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);
  4436. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4437. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4438. var a1 = this.startAngle.degrees();
  4439. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4440. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4441. // angles correction
  4442. if (a2 - a1 > +180.0)
  4443. a2 -= 360.0;
  4444. if (a2 - a1 < -180.0)
  4445. a2 += 360.0;
  4446. if (a3 - a2 > +180.0)
  4447. a3 -= 360.0;
  4448. if (a3 - a2 < -180.0)
  4449. a3 += 360.0;
  4450. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4451. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4452. }
  4453. return Arc2;
  4454. }());
  4455. BABYLON.Arc2 = Arc2;
  4456. var Path2 = /** @class */ (function () {
  4457. /**
  4458. * Creates a Path2 object from the starting 2D coordinates x and y.
  4459. */
  4460. function Path2(x, y) {
  4461. this._points = new Array();
  4462. this._length = 0.0;
  4463. this.closed = false;
  4464. this._points.push(new Vector2(x, y));
  4465. }
  4466. /**
  4467. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4468. * Returns the updated Path2.
  4469. */
  4470. Path2.prototype.addLineTo = function (x, y) {
  4471. if (this.closed) {
  4472. //Tools.Error("cannot add lines to closed paths");
  4473. return this;
  4474. }
  4475. var newPoint = new Vector2(x, y);
  4476. var previousPoint = this._points[this._points.length - 1];
  4477. this._points.push(newPoint);
  4478. this._length += newPoint.subtract(previousPoint).length();
  4479. return this;
  4480. };
  4481. /**
  4482. * 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.
  4483. * Returns the updated Path2.
  4484. */
  4485. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4486. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4487. if (this.closed) {
  4488. //Tools.Error("cannot add arcs to closed paths");
  4489. return this;
  4490. }
  4491. var startPoint = this._points[this._points.length - 1];
  4492. var midPoint = new Vector2(midX, midY);
  4493. var endPoint = new Vector2(endX, endY);
  4494. var arc = new Arc2(startPoint, midPoint, endPoint);
  4495. var increment = arc.angle.radians() / numberOfSegments;
  4496. if (arc.orientation === Orientation.CW)
  4497. increment *= -1;
  4498. var currentAngle = arc.startAngle.radians() + increment;
  4499. for (var i = 0; i < numberOfSegments; i++) {
  4500. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4501. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4502. this.addLineTo(x, y);
  4503. currentAngle += increment;
  4504. }
  4505. return this;
  4506. };
  4507. /**
  4508. * Closes the Path2.
  4509. * Returns the Path2.
  4510. */
  4511. Path2.prototype.close = function () {
  4512. this.closed = true;
  4513. return this;
  4514. };
  4515. /**
  4516. * Returns the Path2 total length (float).
  4517. */
  4518. Path2.prototype.length = function () {
  4519. var result = this._length;
  4520. if (!this.closed) {
  4521. var lastPoint = this._points[this._points.length - 1];
  4522. var firstPoint = this._points[0];
  4523. result += (firstPoint.subtract(lastPoint).length());
  4524. }
  4525. return result;
  4526. };
  4527. /**
  4528. * Returns the Path2 internal array of points.
  4529. */
  4530. Path2.prototype.getPoints = function () {
  4531. return this._points;
  4532. };
  4533. /**
  4534. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4535. */
  4536. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4537. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4538. //Tools.Error("normalized length position should be between 0 and 1.");
  4539. return Vector2.Zero();
  4540. }
  4541. var lengthPosition = normalizedLengthPosition * this.length();
  4542. var previousOffset = 0;
  4543. for (var i = 0; i < this._points.length; i++) {
  4544. var j = (i + 1) % this._points.length;
  4545. var a = this._points[i];
  4546. var b = this._points[j];
  4547. var bToA = b.subtract(a);
  4548. var nextOffset = (bToA.length() + previousOffset);
  4549. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4550. var dir = bToA.normalize();
  4551. var localOffset = lengthPosition - previousOffset;
  4552. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4553. }
  4554. previousOffset = nextOffset;
  4555. }
  4556. //Tools.Error("internal error");
  4557. return Vector2.Zero();
  4558. };
  4559. /**
  4560. * Returns a new Path2 starting at the coordinates (x, y).
  4561. */
  4562. Path2.StartingAt = function (x, y) {
  4563. return new Path2(x, y);
  4564. };
  4565. return Path2;
  4566. }());
  4567. BABYLON.Path2 = Path2;
  4568. var Path3D = /** @class */ (function () {
  4569. /**
  4570. * new Path3D(path, normal, raw)
  4571. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4572. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4573. * path : an array of Vector3, the curve axis of the Path3D
  4574. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4575. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4576. */
  4577. function Path3D(path, firstNormal, raw) {
  4578. if (firstNormal === void 0) { firstNormal = null; }
  4579. this.path = path;
  4580. this._curve = new Array();
  4581. this._distances = new Array();
  4582. this._tangents = new Array();
  4583. this._normals = new Array();
  4584. this._binormals = new Array();
  4585. for (var p = 0; p < path.length; p++) {
  4586. this._curve[p] = path[p].clone(); // hard copy
  4587. }
  4588. this._raw = raw || false;
  4589. this._compute(firstNormal);
  4590. }
  4591. /**
  4592. * Returns the Path3D array of successive Vector3 designing its curve.
  4593. */
  4594. Path3D.prototype.getCurve = function () {
  4595. return this._curve;
  4596. };
  4597. /**
  4598. * Returns an array populated with tangent vectors on each Path3D curve point.
  4599. */
  4600. Path3D.prototype.getTangents = function () {
  4601. return this._tangents;
  4602. };
  4603. /**
  4604. * Returns an array populated with normal vectors on each Path3D curve point.
  4605. */
  4606. Path3D.prototype.getNormals = function () {
  4607. return this._normals;
  4608. };
  4609. /**
  4610. * Returns an array populated with binormal vectors on each Path3D curve point.
  4611. */
  4612. Path3D.prototype.getBinormals = function () {
  4613. return this._binormals;
  4614. };
  4615. /**
  4616. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4617. */
  4618. Path3D.prototype.getDistances = function () {
  4619. return this._distances;
  4620. };
  4621. /**
  4622. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4623. * Returns the same object updated.
  4624. */
  4625. Path3D.prototype.update = function (path, firstNormal) {
  4626. if (firstNormal === void 0) { firstNormal = null; }
  4627. for (var p = 0; p < path.length; p++) {
  4628. this._curve[p].x = path[p].x;
  4629. this._curve[p].y = path[p].y;
  4630. this._curve[p].z = path[p].z;
  4631. }
  4632. this._compute(firstNormal);
  4633. return this;
  4634. };
  4635. // private function compute() : computes tangents, normals and binormals
  4636. Path3D.prototype._compute = function (firstNormal) {
  4637. var l = this._curve.length;
  4638. // first and last tangents
  4639. this._tangents[0] = this._getFirstNonNullVector(0);
  4640. if (!this._raw) {
  4641. this._tangents[0].normalize();
  4642. }
  4643. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4644. if (!this._raw) {
  4645. this._tangents[l - 1].normalize();
  4646. }
  4647. // normals and binormals at first point : arbitrary vector with _normalVector()
  4648. var tg0 = this._tangents[0];
  4649. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4650. this._normals[0] = pp0;
  4651. if (!this._raw) {
  4652. this._normals[0].normalize();
  4653. }
  4654. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4655. if (!this._raw) {
  4656. this._binormals[0].normalize();
  4657. }
  4658. this._distances[0] = 0.0;
  4659. // normals and binormals : next points
  4660. var prev; // previous vector (segment)
  4661. var cur; // current vector (segment)
  4662. var curTang; // current tangent
  4663. // previous normal
  4664. var prevBinor; // previous binormal
  4665. for (var i = 1; i < l; i++) {
  4666. // tangents
  4667. prev = this._getLastNonNullVector(i);
  4668. if (i < l - 1) {
  4669. cur = this._getFirstNonNullVector(i);
  4670. this._tangents[i] = prev.add(cur);
  4671. this._tangents[i].normalize();
  4672. }
  4673. this._distances[i] = this._distances[i - 1] + prev.length();
  4674. // normals and binormals
  4675. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4676. curTang = this._tangents[i];
  4677. prevBinor = this._binormals[i - 1];
  4678. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4679. if (!this._raw) {
  4680. this._normals[i].normalize();
  4681. }
  4682. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4683. if (!this._raw) {
  4684. this._binormals[i].normalize();
  4685. }
  4686. }
  4687. };
  4688. // private function getFirstNonNullVector(index)
  4689. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4690. Path3D.prototype._getFirstNonNullVector = function (index) {
  4691. var i = 1;
  4692. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4693. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4694. i++;
  4695. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4696. }
  4697. return nNVector;
  4698. };
  4699. // private function getLastNonNullVector(index)
  4700. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4701. Path3D.prototype._getLastNonNullVector = function (index) {
  4702. var i = 1;
  4703. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4704. while (nLVector.length() === 0 && index > i + 1) {
  4705. i++;
  4706. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4707. }
  4708. return nLVector;
  4709. };
  4710. // private function normalVector(v0, vt, va) :
  4711. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4712. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4713. Path3D.prototype._normalVector = function (v0, vt, va) {
  4714. var normal0;
  4715. var tgl = vt.length();
  4716. if (tgl === 0.0) {
  4717. tgl = 1.0;
  4718. }
  4719. if (va === undefined || va === null) {
  4720. var point;
  4721. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4722. point = new Vector3(0.0, -1.0, 0.0);
  4723. }
  4724. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4725. point = new Vector3(1.0, 0.0, 0.0);
  4726. }
  4727. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4728. point = new Vector3(0.0, 0.0, 1.0);
  4729. }
  4730. else {
  4731. point = Vector3.Zero();
  4732. }
  4733. normal0 = Vector3.Cross(vt, point);
  4734. }
  4735. else {
  4736. normal0 = Vector3.Cross(vt, va);
  4737. Vector3.CrossToRef(normal0, vt, normal0);
  4738. }
  4739. normal0.normalize();
  4740. return normal0;
  4741. };
  4742. return Path3D;
  4743. }());
  4744. BABYLON.Path3D = Path3D;
  4745. var Curve3 = /** @class */ (function () {
  4746. /**
  4747. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4748. * A Curve3 is designed from a series of successive Vector3.
  4749. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4750. */
  4751. function Curve3(points) {
  4752. this._length = 0.0;
  4753. this._points = points;
  4754. this._length = this._computeLength(points);
  4755. }
  4756. /**
  4757. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4758. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4759. * @param v1 (Vector3) the control point
  4760. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4761. * @param nbPoints (integer) the wanted number of points in the curve
  4762. */
  4763. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4764. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4765. var bez = new Array();
  4766. var equation = function (t, val0, val1, val2) {
  4767. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4768. return res;
  4769. };
  4770. for (var i = 0; i <= nbPoints; i++) {
  4771. 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)));
  4772. }
  4773. return new Curve3(bez);
  4774. };
  4775. /**
  4776. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4777. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4778. * @param v1 (Vector3) the first control point
  4779. * @param v2 (Vector3) the second control point
  4780. * @param v3 (Vector3) the end point of the Cubic Bezier
  4781. * @param nbPoints (integer) the wanted number of points in the curve
  4782. */
  4783. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4784. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4785. var bez = new Array();
  4786. var equation = function (t, val0, val1, val2, val3) {
  4787. 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;
  4788. return res;
  4789. };
  4790. for (var i = 0; i <= nbPoints; i++) {
  4791. 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)));
  4792. }
  4793. return new Curve3(bez);
  4794. };
  4795. /**
  4796. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4797. * @param p1 (Vector3) the origin point of the Hermite Spline
  4798. * @param t1 (Vector3) the tangent vector at the origin point
  4799. * @param p2 (Vector3) the end point of the Hermite Spline
  4800. * @param t2 (Vector3) the tangent vector at the end point
  4801. * @param nbPoints (integer) the wanted number of points in the curve
  4802. */
  4803. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4804. var hermite = new Array();
  4805. var step = 1.0 / nbPoints;
  4806. for (var i = 0; i <= nbPoints; i++) {
  4807. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4808. }
  4809. return new Curve3(hermite);
  4810. };
  4811. /**
  4812. * Returns a Curve3 object along a CatmullRom Spline curve :
  4813. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4814. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4815. */
  4816. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4817. var totalPoints = new Array();
  4818. totalPoints.push(points[0].clone());
  4819. Array.prototype.push.apply(totalPoints, points);
  4820. totalPoints.push(points[points.length - 1].clone());
  4821. var catmullRom = new Array();
  4822. var step = 1.0 / nbPoints;
  4823. var amount = 0.0;
  4824. for (var i = 0; i < totalPoints.length - 3; i++) {
  4825. amount = 0;
  4826. for (var c = 0; c < nbPoints; c++) {
  4827. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4828. amount += step;
  4829. }
  4830. }
  4831. i--;
  4832. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4833. return new Curve3(catmullRom);
  4834. };
  4835. /**
  4836. * Returns the Curve3 stored array of successive Vector3
  4837. */
  4838. Curve3.prototype.getPoints = function () {
  4839. return this._points;
  4840. };
  4841. /**
  4842. * Returns the computed length (float) of the curve.
  4843. */
  4844. Curve3.prototype.length = function () {
  4845. return this._length;
  4846. };
  4847. /**
  4848. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4849. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4850. * curveA and curveB keep unchanged.
  4851. */
  4852. Curve3.prototype.continue = function (curve) {
  4853. var lastPoint = this._points[this._points.length - 1];
  4854. var continuedPoints = this._points.slice();
  4855. var curvePoints = curve.getPoints();
  4856. for (var i = 1; i < curvePoints.length; i++) {
  4857. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4858. }
  4859. var continuedCurve = new Curve3(continuedPoints);
  4860. return continuedCurve;
  4861. };
  4862. Curve3.prototype._computeLength = function (path) {
  4863. var l = 0;
  4864. for (var i = 1; i < path.length; i++) {
  4865. l += (path[i].subtract(path[i - 1])).length();
  4866. }
  4867. return l;
  4868. };
  4869. return Curve3;
  4870. }());
  4871. BABYLON.Curve3 = Curve3;
  4872. // Vertex formats
  4873. var PositionNormalVertex = /** @class */ (function () {
  4874. function PositionNormalVertex(position, normal) {
  4875. if (position === void 0) { position = Vector3.Zero(); }
  4876. if (normal === void 0) { normal = Vector3.Up(); }
  4877. this.position = position;
  4878. this.normal = normal;
  4879. }
  4880. PositionNormalVertex.prototype.clone = function () {
  4881. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4882. };
  4883. return PositionNormalVertex;
  4884. }());
  4885. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4886. var PositionNormalTextureVertex = /** @class */ (function () {
  4887. function PositionNormalTextureVertex(position, normal, uv) {
  4888. if (position === void 0) { position = Vector3.Zero(); }
  4889. if (normal === void 0) { normal = Vector3.Up(); }
  4890. if (uv === void 0) { uv = Vector2.Zero(); }
  4891. this.position = position;
  4892. this.normal = normal;
  4893. this.uv = uv;
  4894. }
  4895. PositionNormalTextureVertex.prototype.clone = function () {
  4896. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4897. };
  4898. return PositionNormalTextureVertex;
  4899. }());
  4900. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4901. // Temporary pre-allocated objects for engine internal use
  4902. // usage in any internal function :
  4903. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4904. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4905. var Tmp = /** @class */ (function () {
  4906. function Tmp() {
  4907. }
  4908. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4909. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4910. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4911. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4912. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4913. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4914. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4915. Matrix.Zero(), Matrix.Zero(),
  4916. Matrix.Zero(), Matrix.Zero(),
  4917. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4918. return Tmp;
  4919. }());
  4920. BABYLON.Tmp = Tmp;
  4921. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4922. var MathTmp = /** @class */ (function () {
  4923. function MathTmp() {
  4924. }
  4925. MathTmp.Vector3 = [Vector3.Zero()];
  4926. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4927. MathTmp.Quaternion = [Quaternion.Zero()];
  4928. return MathTmp;
  4929. }());
  4930. })(BABYLON || (BABYLON = {}));
  4931. //# sourceMappingURL=babylon.math.js.map
  4932. var BABYLON;
  4933. (function (BABYLON) {
  4934. var Scalar = /** @class */ (function () {
  4935. function Scalar() {
  4936. }
  4937. /**
  4938. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  4939. */
  4940. Scalar.WithinEpsilon = function (a, b, epsilon) {
  4941. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4942. var num = a - b;
  4943. return -epsilon <= num && num <= epsilon;
  4944. };
  4945. /**
  4946. * Returns a string : the upper case translation of the number i to hexadecimal.
  4947. */
  4948. Scalar.ToHex = function (i) {
  4949. var str = i.toString(16);
  4950. if (i <= 15) {
  4951. return ("0" + str).toUpperCase();
  4952. }
  4953. return str.toUpperCase();
  4954. };
  4955. /**
  4956. * Returns -1 if value is negative and +1 is value is positive.
  4957. * Returns the value itself if it's equal to zero.
  4958. */
  4959. Scalar.Sign = function (value) {
  4960. value = +value; // convert to a number
  4961. if (value === 0 || isNaN(value))
  4962. return value;
  4963. return value > 0 ? 1 : -1;
  4964. };
  4965. /**
  4966. * Returns the value itself if it's between min and max.
  4967. * Returns min if the value is lower than min.
  4968. * Returns max if the value is greater than max.
  4969. */
  4970. Scalar.Clamp = function (value, min, max) {
  4971. if (min === void 0) { min = 0; }
  4972. if (max === void 0) { max = 1; }
  4973. return Math.min(max, Math.max(min, value));
  4974. };
  4975. /**
  4976. * Returns the log2 of value.
  4977. */
  4978. Scalar.Log2 = function (value) {
  4979. return Math.log(value) * Math.LOG2E;
  4980. };
  4981. /**
  4982. * Loops the value, so that it is never larger than length and never smaller than 0.
  4983. *
  4984. * This is similar to the modulo operator but it works with floating point numbers.
  4985. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  4986. * With t = 5 and length = 2.5, the result would be 0.0.
  4987. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  4988. */
  4989. Scalar.Repeat = function (value, length) {
  4990. return value - Math.floor(value / length) * length;
  4991. };
  4992. /**
  4993. * Normalize the value between 0.0 and 1.0 using min and max values
  4994. */
  4995. Scalar.Normalize = function (value, min, max) {
  4996. return (value - min) / (max - min);
  4997. };
  4998. /**
  4999. * Denormalize the value from 0.0 and 1.0 using min and max values
  5000. */
  5001. Scalar.Denormalize = function (normalized, min, max) {
  5002. return (normalized * (max - min) + min);
  5003. };
  5004. /**
  5005. * Calculates the shortest difference between two given angles given in degrees.
  5006. */
  5007. Scalar.DeltaAngle = function (current, target) {
  5008. var num = Scalar.Repeat(target - current, 360.0);
  5009. if (num > 180.0) {
  5010. num -= 360.0;
  5011. }
  5012. return num;
  5013. };
  5014. /**
  5015. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  5016. *
  5017. * The returned value will move back and forth between 0 and length
  5018. */
  5019. Scalar.PingPong = function (tx, length) {
  5020. var t = Scalar.Repeat(tx, length * 2.0);
  5021. return length - Math.abs(t - length);
  5022. };
  5023. /**
  5024. * Interpolates between min and max with smoothing at the limits.
  5025. *
  5026. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  5027. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  5028. */
  5029. Scalar.SmoothStep = function (from, to, tx) {
  5030. var t = Scalar.Clamp(tx);
  5031. t = -2.0 * t * t * t + 3.0 * t * t;
  5032. return to * t + from * (1.0 - t);
  5033. };
  5034. /**
  5035. * Moves a value current towards target.
  5036. *
  5037. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  5038. * Negative values of maxDelta pushes the value away from target.
  5039. */
  5040. Scalar.MoveTowards = function (current, target, maxDelta) {
  5041. var result = 0;
  5042. if (Math.abs(target - current) <= maxDelta) {
  5043. result = target;
  5044. }
  5045. else {
  5046. result = current + Scalar.Sign(target - current) * maxDelta;
  5047. }
  5048. return result;
  5049. };
  5050. /**
  5051. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5052. *
  5053. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  5054. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  5055. */
  5056. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  5057. var num = Scalar.DeltaAngle(current, target);
  5058. var result = 0;
  5059. if (-maxDelta < num && num < maxDelta) {
  5060. result = target;
  5061. }
  5062. else {
  5063. target = current + num;
  5064. result = Scalar.MoveTowards(current, target, maxDelta);
  5065. }
  5066. return result;
  5067. };
  5068. /**
  5069. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  5070. */
  5071. Scalar.Lerp = function (start, end, amount) {
  5072. return start + ((end - start) * amount);
  5073. };
  5074. /**
  5075. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5076. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  5077. */
  5078. Scalar.LerpAngle = function (start, end, amount) {
  5079. var num = Scalar.Repeat(end - start, 360.0);
  5080. if (num > 180.0) {
  5081. num -= 360.0;
  5082. }
  5083. return start + num * Scalar.Clamp(amount);
  5084. };
  5085. /**
  5086. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  5087. */
  5088. Scalar.InverseLerp = function (a, b, value) {
  5089. var result = 0;
  5090. if (a != b) {
  5091. result = Scalar.Clamp((value - a) / (b - a));
  5092. }
  5093. else {
  5094. result = 0.0;
  5095. }
  5096. return result;
  5097. };
  5098. /**
  5099. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  5100. */
  5101. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5102. var squared = amount * amount;
  5103. var cubed = amount * squared;
  5104. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5105. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5106. var part3 = (cubed - (2.0 * squared)) + amount;
  5107. var part4 = cubed - squared;
  5108. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  5109. };
  5110. /**
  5111. * Returns a random float number between and min and max values
  5112. */
  5113. Scalar.RandomRange = function (min, max) {
  5114. if (min === max)
  5115. return min;
  5116. return ((Math.random() * (max - min)) + min);
  5117. };
  5118. /**
  5119. * This function returns percentage of a number in a given range.
  5120. *
  5121. * RangeToPercent(40,20,60) will return 0.5 (50%)
  5122. * RangeToPercent(34,0,100) will return 0.34 (34%)
  5123. */
  5124. Scalar.RangeToPercent = function (number, min, max) {
  5125. return ((number - min) / (max - min));
  5126. };
  5127. /**
  5128. * This function returns number that corresponds to the percentage in a given range.
  5129. *
  5130. * PercentToRange(0.34,0,100) will return 34.
  5131. */
  5132. Scalar.PercentToRange = function (percent, min, max) {
  5133. return ((max - min) * percent + min);
  5134. };
  5135. /**
  5136. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  5137. * @param angle The angle to normalize in radian.
  5138. * @return The converted angle.
  5139. */
  5140. Scalar.NormalizeRadians = function (angle) {
  5141. // More precise but slower version kept for reference.
  5142. // angle = angle % Tools.TwoPi;
  5143. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  5144. //if (angle > Math.PI) {
  5145. // angle -= Tools.TwoPi;
  5146. //}
  5147. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  5148. return angle;
  5149. };
  5150. /**
  5151. * Two pi constants convenient for computation.
  5152. */
  5153. Scalar.TwoPi = Math.PI * 2;
  5154. return Scalar;
  5155. }());
  5156. BABYLON.Scalar = Scalar;
  5157. })(BABYLON || (BABYLON = {}));
  5158. //# sourceMappingURL=babylon.math.scalar.js.map
  5159. //# sourceMappingURL=babylon.mixins.js.map
  5160. var BABYLON;
  5161. (function (BABYLON) {
  5162. var __decoratorInitialStore = {};
  5163. var __mergedStore = {};
  5164. var _copySource = function (creationFunction, source, instanciate) {
  5165. var destination = creationFunction();
  5166. // Tags
  5167. if (BABYLON.Tags) {
  5168. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5169. }
  5170. var classStore = getMergedStore(destination);
  5171. // Properties
  5172. for (var property in classStore) {
  5173. var propertyDescriptor = classStore[property];
  5174. var sourceProperty = source[property];
  5175. var propertyType = propertyDescriptor.type;
  5176. if (sourceProperty !== undefined && sourceProperty !== null) {
  5177. switch (propertyType) {
  5178. case 0: // Value
  5179. case 6:// Mesh reference
  5180. destination[property] = sourceProperty;
  5181. break;
  5182. case 1:// Texture
  5183. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  5184. break;
  5185. case 2: // Color3
  5186. case 3: // FresnelParameters
  5187. case 4: // Vector2
  5188. case 5: // Vector3
  5189. case 7: // Color Curves
  5190. case 10:// Quaternion
  5191. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  5192. break;
  5193. }
  5194. }
  5195. }
  5196. return destination;
  5197. };
  5198. function getDirectStore(target) {
  5199. var classKey = target.getClassName();
  5200. if (!__decoratorInitialStore[classKey]) {
  5201. __decoratorInitialStore[classKey] = {};
  5202. }
  5203. return __decoratorInitialStore[classKey];
  5204. }
  5205. /**
  5206. * Return the list of properties flagged as serializable
  5207. * @param target: host object
  5208. */
  5209. function getMergedStore(target) {
  5210. var classKey = target.getClassName();
  5211. if (__mergedStore[classKey]) {
  5212. return __mergedStore[classKey];
  5213. }
  5214. __mergedStore[classKey] = {};
  5215. var store = __mergedStore[classKey];
  5216. var currentTarget = target;
  5217. var currentKey = classKey;
  5218. while (currentKey) {
  5219. var initialStore = __decoratorInitialStore[currentKey];
  5220. for (var property in initialStore) {
  5221. store[property] = initialStore[property];
  5222. }
  5223. var parent_1 = void 0;
  5224. var done = false;
  5225. do {
  5226. parent_1 = Object.getPrototypeOf(currentTarget);
  5227. if (!parent_1.getClassName) {
  5228. done = true;
  5229. break;
  5230. }
  5231. if (parent_1.getClassName() !== currentKey) {
  5232. break;
  5233. }
  5234. currentTarget = parent_1;
  5235. } while (parent_1);
  5236. if (done) {
  5237. break;
  5238. }
  5239. currentKey = parent_1.getClassName();
  5240. currentTarget = parent_1;
  5241. }
  5242. return store;
  5243. }
  5244. function generateSerializableMember(type, sourceName) {
  5245. return function (target, propertyKey) {
  5246. var classStore = getDirectStore(target);
  5247. if (!classStore[propertyKey]) {
  5248. classStore[propertyKey] = { type: type, sourceName: sourceName };
  5249. }
  5250. };
  5251. }
  5252. function generateExpandMember(setCallback, targetKey) {
  5253. if (targetKey === void 0) { targetKey = null; }
  5254. return function (target, propertyKey) {
  5255. var key = targetKey || ("_" + propertyKey);
  5256. Object.defineProperty(target, propertyKey, {
  5257. get: function () {
  5258. return this[key];
  5259. },
  5260. set: function (value) {
  5261. if (this[key] === value) {
  5262. return;
  5263. }
  5264. this[key] = value;
  5265. target[setCallback].apply(this);
  5266. },
  5267. enumerable: true,
  5268. configurable: true
  5269. });
  5270. };
  5271. }
  5272. function expandToProperty(callback, targetKey) {
  5273. if (targetKey === void 0) { targetKey = null; }
  5274. return generateExpandMember(callback, targetKey);
  5275. }
  5276. BABYLON.expandToProperty = expandToProperty;
  5277. function serialize(sourceName) {
  5278. return generateSerializableMember(0, sourceName); // value member
  5279. }
  5280. BABYLON.serialize = serialize;
  5281. function serializeAsTexture(sourceName) {
  5282. return generateSerializableMember(1, sourceName); // texture member
  5283. }
  5284. BABYLON.serializeAsTexture = serializeAsTexture;
  5285. function serializeAsColor3(sourceName) {
  5286. return generateSerializableMember(2, sourceName); // color3 member
  5287. }
  5288. BABYLON.serializeAsColor3 = serializeAsColor3;
  5289. function serializeAsFresnelParameters(sourceName) {
  5290. return generateSerializableMember(3, sourceName); // fresnel parameters member
  5291. }
  5292. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  5293. function serializeAsVector2(sourceName) {
  5294. return generateSerializableMember(4, sourceName); // vector2 member
  5295. }
  5296. BABYLON.serializeAsVector2 = serializeAsVector2;
  5297. function serializeAsVector3(sourceName) {
  5298. return generateSerializableMember(5, sourceName); // vector3 member
  5299. }
  5300. BABYLON.serializeAsVector3 = serializeAsVector3;
  5301. function serializeAsMeshReference(sourceName) {
  5302. return generateSerializableMember(6, sourceName); // mesh reference member
  5303. }
  5304. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  5305. function serializeAsColorCurves(sourceName) {
  5306. return generateSerializableMember(7, sourceName); // color curves
  5307. }
  5308. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  5309. function serializeAsColor4(sourceName) {
  5310. return generateSerializableMember(8, sourceName); // color 4
  5311. }
  5312. BABYLON.serializeAsColor4 = serializeAsColor4;
  5313. function serializeAsImageProcessingConfiguration(sourceName) {
  5314. return generateSerializableMember(9, sourceName); // image processing
  5315. }
  5316. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  5317. function serializeAsQuaternion(sourceName) {
  5318. return generateSerializableMember(10, sourceName); // quaternion member
  5319. }
  5320. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  5321. var SerializationHelper = /** @class */ (function () {
  5322. function SerializationHelper() {
  5323. }
  5324. SerializationHelper.Serialize = function (entity, serializationObject) {
  5325. if (!serializationObject) {
  5326. serializationObject = {};
  5327. }
  5328. // Tags
  5329. if (BABYLON.Tags) {
  5330. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  5331. }
  5332. var serializedProperties = getMergedStore(entity);
  5333. // Properties
  5334. for (var property in serializedProperties) {
  5335. var propertyDescriptor = serializedProperties[property];
  5336. var targetPropertyName = propertyDescriptor.sourceName || property;
  5337. var propertyType = propertyDescriptor.type;
  5338. var sourceProperty = entity[property];
  5339. if (sourceProperty !== undefined && sourceProperty !== null) {
  5340. switch (propertyType) {
  5341. case 0:// Value
  5342. serializationObject[targetPropertyName] = sourceProperty;
  5343. break;
  5344. case 1:// Texture
  5345. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5346. break;
  5347. case 2:// Color3
  5348. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5349. break;
  5350. case 3:// FresnelParameters
  5351. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5352. break;
  5353. case 4:// Vector2
  5354. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5355. break;
  5356. case 5:// Vector3
  5357. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5358. break;
  5359. case 6:// Mesh reference
  5360. serializationObject[targetPropertyName] = sourceProperty.id;
  5361. break;
  5362. case 7:// Color Curves
  5363. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5364. break;
  5365. case 8:// Color 4
  5366. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5367. break;
  5368. case 9:// Image Processing
  5369. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5370. break;
  5371. }
  5372. }
  5373. }
  5374. return serializationObject;
  5375. };
  5376. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  5377. if (rootUrl === void 0) { rootUrl = null; }
  5378. var destination = creationFunction();
  5379. if (!rootUrl) {
  5380. rootUrl = "";
  5381. }
  5382. // Tags
  5383. if (BABYLON.Tags) {
  5384. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5385. }
  5386. var classStore = getMergedStore(destination);
  5387. // Properties
  5388. for (var property in classStore) {
  5389. var propertyDescriptor = classStore[property];
  5390. var sourceProperty = source[propertyDescriptor.sourceName || property];
  5391. var propertyType = propertyDescriptor.type;
  5392. if (sourceProperty !== undefined && sourceProperty !== null) {
  5393. var dest = destination;
  5394. switch (propertyType) {
  5395. case 0:// Value
  5396. dest[property] = sourceProperty;
  5397. break;
  5398. case 1:// Texture
  5399. if (scene) {
  5400. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  5401. }
  5402. break;
  5403. case 2:// Color3
  5404. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  5405. break;
  5406. case 3:// FresnelParameters
  5407. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  5408. break;
  5409. case 4:// Vector2
  5410. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  5411. break;
  5412. case 5:// Vector3
  5413. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  5414. break;
  5415. case 6:// Mesh reference
  5416. if (scene) {
  5417. dest[property] = scene.getLastMeshByID(sourceProperty);
  5418. }
  5419. break;
  5420. case 7:// Color Curves
  5421. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  5422. break;
  5423. case 8:// Color 4
  5424. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  5425. break;
  5426. case 9:// Image Processing
  5427. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  5428. break;
  5429. }
  5430. }
  5431. }
  5432. return destination;
  5433. };
  5434. SerializationHelper.Clone = function (creationFunction, source) {
  5435. return _copySource(creationFunction, source, false);
  5436. };
  5437. SerializationHelper.Instanciate = function (creationFunction, source) {
  5438. return _copySource(creationFunction, source, true);
  5439. };
  5440. return SerializationHelper;
  5441. }());
  5442. BABYLON.SerializationHelper = SerializationHelper;
  5443. })(BABYLON || (BABYLON = {}));
  5444. //# sourceMappingURL=babylon.decorators.js.map
  5445. var BABYLON;
  5446. (function (BABYLON) {
  5447. /**
  5448. * A class serves as a medium between the observable and its observers
  5449. */
  5450. var EventState = /** @class */ (function () {
  5451. /**
  5452. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  5453. */
  5454. function EventState(mask, skipNextObservers, target, currentTarget) {
  5455. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5456. this.initalize(mask, skipNextObservers, target, currentTarget);
  5457. }
  5458. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  5459. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5460. this.mask = mask;
  5461. this.skipNextObservers = skipNextObservers;
  5462. this.target = target;
  5463. this.currentTarget = currentTarget;
  5464. return this;
  5465. };
  5466. return EventState;
  5467. }());
  5468. BABYLON.EventState = EventState;
  5469. /**
  5470. * Represent an Observer registered to a given Observable object.
  5471. */
  5472. var Observer = /** @class */ (function () {
  5473. function Observer(callback, mask, scope) {
  5474. if (scope === void 0) { scope = null; }
  5475. this.callback = callback;
  5476. this.mask = mask;
  5477. this.scope = scope;
  5478. }
  5479. return Observer;
  5480. }());
  5481. BABYLON.Observer = Observer;
  5482. /**
  5483. * Represent a list of observers registered to multiple Observables object.
  5484. */
  5485. var MultiObserver = /** @class */ (function () {
  5486. function MultiObserver() {
  5487. }
  5488. MultiObserver.prototype.dispose = function () {
  5489. if (this._observers && this._observables) {
  5490. for (var index = 0; index < this._observers.length; index++) {
  5491. this._observables[index].remove(this._observers[index]);
  5492. }
  5493. }
  5494. this._observers = null;
  5495. this._observables = null;
  5496. };
  5497. MultiObserver.Watch = function (observables, callback, mask, scope) {
  5498. if (mask === void 0) { mask = -1; }
  5499. if (scope === void 0) { scope = null; }
  5500. var result = new MultiObserver();
  5501. result._observers = new Array();
  5502. result._observables = observables;
  5503. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  5504. var observable = observables_1[_i];
  5505. var observer = observable.add(callback, mask, false, scope);
  5506. if (observer) {
  5507. result._observers.push(observer);
  5508. }
  5509. }
  5510. return result;
  5511. };
  5512. return MultiObserver;
  5513. }());
  5514. BABYLON.MultiObserver = MultiObserver;
  5515. /**
  5516. * The Observable class is a simple implementation of the Observable pattern.
  5517. * 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.
  5518. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  5519. * 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).
  5520. * 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.
  5521. */
  5522. var Observable = /** @class */ (function () {
  5523. function Observable(onObserverAdded) {
  5524. this._observers = new Array();
  5525. this._eventState = new EventState(0);
  5526. if (onObserverAdded) {
  5527. this._onObserverAdded = onObserverAdded;
  5528. }
  5529. }
  5530. /**
  5531. * Create a new Observer with the specified callback
  5532. * @param callback the callback that will be executed for that Observer
  5533. * @param mask the mask used to filter observers
  5534. * @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.
  5535. * @param scope optional scope for the callback to be called from
  5536. */
  5537. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  5538. if (mask === void 0) { mask = -1; }
  5539. if (insertFirst === void 0) { insertFirst = false; }
  5540. if (scope === void 0) { scope = null; }
  5541. if (!callback) {
  5542. return null;
  5543. }
  5544. var observer = new Observer(callback, mask, scope);
  5545. if (insertFirst) {
  5546. this._observers.unshift(observer);
  5547. }
  5548. else {
  5549. this._observers.push(observer);
  5550. }
  5551. if (this._onObserverAdded) {
  5552. this._onObserverAdded(observer);
  5553. }
  5554. return observer;
  5555. };
  5556. /**
  5557. * Remove an Observer from the Observable object
  5558. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5559. */
  5560. Observable.prototype.remove = function (observer) {
  5561. if (!observer) {
  5562. return false;
  5563. }
  5564. var index = this._observers.indexOf(observer);
  5565. if (index !== -1) {
  5566. this._observers.splice(index, 1);
  5567. return true;
  5568. }
  5569. return false;
  5570. };
  5571. /**
  5572. * Remove a callback from the Observable object
  5573. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5574. */
  5575. Observable.prototype.removeCallback = function (callback) {
  5576. for (var index = 0; index < this._observers.length; index++) {
  5577. if (this._observers[index].callback === callback) {
  5578. this._observers.splice(index, 1);
  5579. return true;
  5580. }
  5581. }
  5582. return false;
  5583. };
  5584. /**
  5585. * Notify all Observers by calling their respective callback with the given data
  5586. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5587. * @param eventData
  5588. * @param mask
  5589. */
  5590. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  5591. if (mask === void 0) { mask = -1; }
  5592. if (!this._observers.length) {
  5593. return true;
  5594. }
  5595. var state = this._eventState;
  5596. state.mask = mask;
  5597. state.target = target;
  5598. state.currentTarget = currentTarget;
  5599. state.skipNextObservers = false;
  5600. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5601. var obs = _a[_i];
  5602. if (obs.mask & mask) {
  5603. if (obs.scope) {
  5604. obs.callback.apply(obs.scope, [eventData, state]);
  5605. }
  5606. else {
  5607. obs.callback(eventData, state);
  5608. }
  5609. }
  5610. if (state.skipNextObservers) {
  5611. return false;
  5612. }
  5613. }
  5614. return true;
  5615. };
  5616. /**
  5617. * Notify a specific observer
  5618. * @param eventData
  5619. * @param mask
  5620. */
  5621. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  5622. if (mask === void 0) { mask = -1; }
  5623. var state = this._eventState;
  5624. state.mask = mask;
  5625. state.skipNextObservers = false;
  5626. observer.callback(eventData, state);
  5627. };
  5628. /**
  5629. * return true is the Observable has at least one Observer registered
  5630. */
  5631. Observable.prototype.hasObservers = function () {
  5632. return this._observers.length > 0;
  5633. };
  5634. /**
  5635. * Clear the list of observers
  5636. */
  5637. Observable.prototype.clear = function () {
  5638. this._observers = new Array();
  5639. this._onObserverAdded = null;
  5640. };
  5641. /**
  5642. * Clone the current observable
  5643. */
  5644. Observable.prototype.clone = function () {
  5645. var result = new Observable();
  5646. result._observers = this._observers.slice(0);
  5647. return result;
  5648. };
  5649. /**
  5650. * Does this observable handles observer registered with a given mask
  5651. * @param {number} trigger - the mask to be tested
  5652. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5653. **/
  5654. Observable.prototype.hasSpecificMask = function (mask) {
  5655. if (mask === void 0) { mask = -1; }
  5656. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5657. var obs = _a[_i];
  5658. if (obs.mask & mask || obs.mask === mask) {
  5659. return true;
  5660. }
  5661. }
  5662. return false;
  5663. };
  5664. return Observable;
  5665. }());
  5666. BABYLON.Observable = Observable;
  5667. })(BABYLON || (BABYLON = {}));
  5668. //# sourceMappingURL=babylon.observable.js.map
  5669. var BABYLON;
  5670. (function (BABYLON) {
  5671. var SmartArray = /** @class */ (function () {
  5672. function SmartArray(capacity) {
  5673. this.length = 0;
  5674. this.data = new Array(capacity);
  5675. this._id = SmartArray._GlobalId++;
  5676. }
  5677. SmartArray.prototype.push = function (value) {
  5678. this.data[this.length++] = value;
  5679. if (this.length > this.data.length) {
  5680. this.data.length *= 2;
  5681. }
  5682. };
  5683. SmartArray.prototype.forEach = function (func) {
  5684. for (var index = 0; index < this.length; index++) {
  5685. func(this.data[index]);
  5686. }
  5687. };
  5688. SmartArray.prototype.sort = function (compareFn) {
  5689. this.data.sort(compareFn);
  5690. };
  5691. SmartArray.prototype.reset = function () {
  5692. this.length = 0;
  5693. };
  5694. SmartArray.prototype.dispose = function () {
  5695. this.reset();
  5696. if (this.data) {
  5697. this.data.length = 0;
  5698. this.data = [];
  5699. }
  5700. };
  5701. SmartArray.prototype.concat = function (array) {
  5702. if (array.length === 0) {
  5703. return;
  5704. }
  5705. if (this.length + array.length > this.data.length) {
  5706. this.data.length = (this.length + array.length) * 2;
  5707. }
  5708. for (var index = 0; index < array.length; index++) {
  5709. this.data[this.length++] = (array.data || array)[index];
  5710. }
  5711. };
  5712. SmartArray.prototype.indexOf = function (value) {
  5713. var position = this.data.indexOf(value);
  5714. if (position >= this.length) {
  5715. return -1;
  5716. }
  5717. return position;
  5718. };
  5719. SmartArray.prototype.contains = function (value) {
  5720. return this.data.indexOf(value) !== -1;
  5721. };
  5722. // Statics
  5723. SmartArray._GlobalId = 0;
  5724. return SmartArray;
  5725. }());
  5726. BABYLON.SmartArray = SmartArray;
  5727. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  5728. __extends(SmartArrayNoDuplicate, _super);
  5729. function SmartArrayNoDuplicate() {
  5730. var _this = _super !== null && _super.apply(this, arguments) || this;
  5731. _this._duplicateId = 0;
  5732. return _this;
  5733. }
  5734. SmartArrayNoDuplicate.prototype.push = function (value) {
  5735. _super.prototype.push.call(this, value);
  5736. if (!value.__smartArrayFlags) {
  5737. value.__smartArrayFlags = {};
  5738. }
  5739. value.__smartArrayFlags[this._id] = this._duplicateId;
  5740. };
  5741. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  5742. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5743. return false;
  5744. }
  5745. this.push(value);
  5746. return true;
  5747. };
  5748. SmartArrayNoDuplicate.prototype.reset = function () {
  5749. _super.prototype.reset.call(this);
  5750. this._duplicateId++;
  5751. };
  5752. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  5753. if (array.length === 0) {
  5754. return;
  5755. }
  5756. if (this.length + array.length > this.data.length) {
  5757. this.data.length = (this.length + array.length) * 2;
  5758. }
  5759. for (var index = 0; index < array.length; index++) {
  5760. var item = (array.data || array)[index];
  5761. this.pushNoDuplicate(item);
  5762. }
  5763. };
  5764. return SmartArrayNoDuplicate;
  5765. }(SmartArray));
  5766. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  5767. })(BABYLON || (BABYLON = {}));
  5768. //# sourceMappingURL=babylon.smartArray.js.map
  5769. var BABYLON;
  5770. (function (BABYLON) {
  5771. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  5772. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  5773. var LoadFileError = /** @class */ (function (_super) {
  5774. __extends(LoadFileError, _super);
  5775. function LoadFileError(message, request) {
  5776. var _this = _super.call(this, message) || this;
  5777. _this.request = request;
  5778. _this.name = "LoadFileError";
  5779. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  5780. return _this;
  5781. }
  5782. // Polyfill for Object.setPrototypeOf if necessary.
  5783. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  5784. return LoadFileError;
  5785. }(Error));
  5786. BABYLON.LoadFileError = LoadFileError;
  5787. var RetryStrategy = /** @class */ (function () {
  5788. function RetryStrategy() {
  5789. }
  5790. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  5791. if (maxRetries === void 0) { maxRetries = 3; }
  5792. if (baseInterval === void 0) { baseInterval = 500; }
  5793. return function (url, request, retryIndex) {
  5794. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  5795. return -1;
  5796. }
  5797. return Math.pow(2, retryIndex) * baseInterval;
  5798. };
  5799. };
  5800. return RetryStrategy;
  5801. }());
  5802. BABYLON.RetryStrategy = RetryStrategy;
  5803. // Screenshots
  5804. var screenshotCanvas;
  5805. var cloneValue = function (source, destinationObject) {
  5806. if (!source)
  5807. return null;
  5808. if (source instanceof BABYLON.Mesh) {
  5809. return null;
  5810. }
  5811. if (source instanceof BABYLON.SubMesh) {
  5812. return source.clone(destinationObject);
  5813. }
  5814. else if (source.clone) {
  5815. return source.clone();
  5816. }
  5817. return null;
  5818. };
  5819. var Tools = /** @class */ (function () {
  5820. function Tools() {
  5821. }
  5822. /**
  5823. * Interpolates between a and b via alpha
  5824. * @param a The lower value (returned when alpha = 0)
  5825. * @param b The upper value (returned when alpha = 1)
  5826. * @param alpha The interpolation-factor
  5827. * @return The mixed value
  5828. */
  5829. Tools.Mix = function (a, b, alpha) {
  5830. return a * (1 - alpha) + b * alpha;
  5831. };
  5832. Tools.Instantiate = function (className) {
  5833. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  5834. return Tools.RegisteredExternalClasses[className];
  5835. }
  5836. var arr = className.split(".");
  5837. var fn = (window || this);
  5838. for (var i = 0, len = arr.length; i < len; i++) {
  5839. fn = fn[arr[i]];
  5840. }
  5841. if (typeof fn !== "function") {
  5842. return null;
  5843. }
  5844. return fn;
  5845. };
  5846. Tools.SetImmediate = function (action) {
  5847. if (window.setImmediate) {
  5848. window.setImmediate(action);
  5849. }
  5850. else {
  5851. setTimeout(action, 1);
  5852. }
  5853. };
  5854. Tools.IsExponentOfTwo = function (value) {
  5855. var count = 1;
  5856. do {
  5857. count *= 2;
  5858. } while (count < value);
  5859. return count === value;
  5860. };
  5861. /**
  5862. * Find the next highest power of two.
  5863. * @param x Number to start search from.
  5864. * @return Next highest power of two.
  5865. */
  5866. Tools.CeilingPOT = function (x) {
  5867. x--;
  5868. x |= x >> 1;
  5869. x |= x >> 2;
  5870. x |= x >> 4;
  5871. x |= x >> 8;
  5872. x |= x >> 16;
  5873. x++;
  5874. return x;
  5875. };
  5876. /**
  5877. * Find the next lowest power of two.
  5878. * @param x Number to start search from.
  5879. * @return Next lowest power of two.
  5880. */
  5881. Tools.FloorPOT = function (x) {
  5882. x = x | (x >> 1);
  5883. x = x | (x >> 2);
  5884. x = x | (x >> 4);
  5885. x = x | (x >> 8);
  5886. x = x | (x >> 16);
  5887. return x - (x >> 1);
  5888. };
  5889. /**
  5890. * Find the nearest power of two.
  5891. * @param x Number to start search from.
  5892. * @return Next nearest power of two.
  5893. */
  5894. Tools.NearestPOT = function (x) {
  5895. var c = Tools.CeilingPOT(x);
  5896. var f = Tools.FloorPOT(x);
  5897. return (c - x) > (x - f) ? f : c;
  5898. };
  5899. Tools.GetExponentOfTwo = function (value, max, mode) {
  5900. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5901. var pot;
  5902. switch (mode) {
  5903. case BABYLON.Engine.SCALEMODE_FLOOR:
  5904. pot = Tools.FloorPOT(value);
  5905. break;
  5906. case BABYLON.Engine.SCALEMODE_NEAREST:
  5907. pot = Tools.NearestPOT(value);
  5908. break;
  5909. case BABYLON.Engine.SCALEMODE_CEILING:
  5910. default:
  5911. pot = Tools.CeilingPOT(value);
  5912. break;
  5913. }
  5914. return Math.min(pot, max);
  5915. };
  5916. Tools.GetFilename = function (path) {
  5917. var index = path.lastIndexOf("/");
  5918. if (index < 0)
  5919. return path;
  5920. return path.substring(index + 1);
  5921. };
  5922. Tools.GetFolderPath = function (uri) {
  5923. var index = uri.lastIndexOf("/");
  5924. if (index < 0)
  5925. return "";
  5926. return uri.substring(0, index + 1);
  5927. };
  5928. Tools.GetDOMTextContent = function (element) {
  5929. var result = "";
  5930. var child = element.firstChild;
  5931. while (child) {
  5932. if (child.nodeType === 3) {
  5933. result += child.textContent;
  5934. }
  5935. child = child.nextSibling;
  5936. }
  5937. return result;
  5938. };
  5939. Tools.ToDegrees = function (angle) {
  5940. return angle * 180 / Math.PI;
  5941. };
  5942. Tools.ToRadians = function (angle) {
  5943. return angle * Math.PI / 180;
  5944. };
  5945. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5946. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5947. var output = "";
  5948. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5949. var i = 0;
  5950. var bytes = new Uint8Array(buffer);
  5951. while (i < bytes.length) {
  5952. chr1 = bytes[i++];
  5953. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5954. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5955. enc1 = chr1 >> 2;
  5956. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5957. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5958. enc4 = chr3 & 63;
  5959. if (isNaN(chr2)) {
  5960. enc3 = enc4 = 64;
  5961. }
  5962. else if (isNaN(chr3)) {
  5963. enc4 = 64;
  5964. }
  5965. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5966. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5967. }
  5968. return "data:image/png;base64," + output;
  5969. };
  5970. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5971. if (bias === void 0) { bias = null; }
  5972. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5973. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5974. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5975. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5976. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5977. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5978. }
  5979. if (bias) {
  5980. minimum.x -= minimum.x * bias.x + bias.y;
  5981. minimum.y -= minimum.y * bias.x + bias.y;
  5982. minimum.z -= minimum.z * bias.x + bias.y;
  5983. maximum.x += maximum.x * bias.x + bias.y;
  5984. maximum.y += maximum.y * bias.x + bias.y;
  5985. maximum.z += maximum.z * bias.x + bias.y;
  5986. }
  5987. return {
  5988. minimum: minimum,
  5989. maximum: maximum
  5990. };
  5991. };
  5992. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5993. if (bias === void 0) { bias = null; }
  5994. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5995. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5996. if (!stride) {
  5997. stride = 3;
  5998. }
  5999. for (var index = start; index < start + count; index++) {
  6000. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  6001. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6002. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6003. }
  6004. if (bias) {
  6005. minimum.x -= minimum.x * bias.x + bias.y;
  6006. minimum.y -= minimum.y * bias.x + bias.y;
  6007. minimum.z -= minimum.z * bias.x + bias.y;
  6008. maximum.x += maximum.x * bias.x + bias.y;
  6009. maximum.y += maximum.y * bias.x + bias.y;
  6010. maximum.z += maximum.z * bias.x + bias.y;
  6011. }
  6012. return {
  6013. minimum: minimum,
  6014. maximum: maximum
  6015. };
  6016. };
  6017. Tools.Vector2ArrayFeeder = function (array) {
  6018. return function (index) {
  6019. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  6020. var length = isFloatArray ? array.length / 2 : array.length;
  6021. if (index >= length) {
  6022. return null;
  6023. }
  6024. if (isFloatArray) {
  6025. var fa = array;
  6026. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  6027. }
  6028. var a = array;
  6029. return a[index];
  6030. };
  6031. };
  6032. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  6033. if (bias === void 0) { bias = null; }
  6034. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  6035. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  6036. var i = 0;
  6037. var cur = feeder(i++);
  6038. while (cur) {
  6039. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  6040. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  6041. cur = feeder(i++);
  6042. }
  6043. if (bias) {
  6044. minimum.x -= minimum.x * bias.x + bias.y;
  6045. minimum.y -= minimum.y * bias.x + bias.y;
  6046. maximum.x += maximum.x * bias.x + bias.y;
  6047. maximum.y += maximum.y * bias.x + bias.y;
  6048. }
  6049. return {
  6050. minimum: minimum,
  6051. maximum: maximum
  6052. };
  6053. };
  6054. Tools.MakeArray = function (obj, allowsNullUndefined) {
  6055. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  6056. return null;
  6057. return Array.isArray(obj) ? obj : [obj];
  6058. };
  6059. // Misc.
  6060. Tools.GetPointerPrefix = function () {
  6061. var eventPrefix = "pointer";
  6062. // Check if pointer events are supported
  6063. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  6064. eventPrefix = "mouse";
  6065. }
  6066. return eventPrefix;
  6067. };
  6068. /**
  6069. * @param func - the function to be called
  6070. * @param requester - the object that will request the next frame. Falls back to window.
  6071. */
  6072. Tools.QueueNewFrame = function (func, requester) {
  6073. if (!Tools.IsWindowObjectExist()) {
  6074. return setTimeout(func, 16);
  6075. }
  6076. if (!requester) {
  6077. requester = window;
  6078. }
  6079. if (requester.requestAnimationFrame) {
  6080. return requester.requestAnimationFrame(func);
  6081. }
  6082. else if (requester.msRequestAnimationFrame) {
  6083. return requester.msRequestAnimationFrame(func);
  6084. }
  6085. else if (requester.webkitRequestAnimationFrame) {
  6086. return requester.webkitRequestAnimationFrame(func);
  6087. }
  6088. else if (requester.mozRequestAnimationFrame) {
  6089. return requester.mozRequestAnimationFrame(func);
  6090. }
  6091. else if (requester.oRequestAnimationFrame) {
  6092. return requester.oRequestAnimationFrame(func);
  6093. }
  6094. else {
  6095. return window.setTimeout(func, 16);
  6096. }
  6097. };
  6098. Tools.RequestFullscreen = function (element) {
  6099. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  6100. if (!requestFunction)
  6101. return;
  6102. requestFunction.call(element);
  6103. };
  6104. Tools.ExitFullscreen = function () {
  6105. if (document.exitFullscreen) {
  6106. document.exitFullscreen();
  6107. }
  6108. else if (document.mozCancelFullScreen) {
  6109. document.mozCancelFullScreen();
  6110. }
  6111. else if (document.webkitCancelFullScreen) {
  6112. document.webkitCancelFullScreen();
  6113. }
  6114. else if (document.msCancelFullScreen) {
  6115. document.msCancelFullScreen();
  6116. }
  6117. };
  6118. Tools.SetCorsBehavior = function (url, element) {
  6119. if (url && url.indexOf("data:") === 0) {
  6120. return;
  6121. }
  6122. if (Tools.CorsBehavior) {
  6123. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  6124. element.crossOrigin = Tools.CorsBehavior;
  6125. }
  6126. else {
  6127. var result = Tools.CorsBehavior(url);
  6128. if (result) {
  6129. element.crossOrigin = result;
  6130. }
  6131. }
  6132. }
  6133. };
  6134. // External files
  6135. Tools.CleanUrl = function (url) {
  6136. url = url.replace(/#/mg, "%23");
  6137. return url;
  6138. };
  6139. Tools.LoadImage = function (url, onLoad, onError, database) {
  6140. if (url instanceof ArrayBuffer) {
  6141. url = Tools.EncodeArrayBufferTobase64(url);
  6142. }
  6143. url = Tools.CleanUrl(url);
  6144. url = Tools.PreprocessUrl(url);
  6145. var img = new Image();
  6146. Tools.SetCorsBehavior(url, img);
  6147. img.onload = function () {
  6148. onLoad(img);
  6149. };
  6150. img.onerror = function (err) {
  6151. Tools.Error("Error while trying to load image: " + url);
  6152. if (onError) {
  6153. onError("Error while trying to load image: " + url, err);
  6154. }
  6155. };
  6156. var noIndexedDB = function () {
  6157. img.src = url;
  6158. };
  6159. var loadFromIndexedDB = function () {
  6160. if (database) {
  6161. database.loadImageFromDB(url, img);
  6162. }
  6163. };
  6164. //ANY database to do!
  6165. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  6166. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6167. }
  6168. else {
  6169. if (url.indexOf("file:") !== -1) {
  6170. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  6171. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  6172. try {
  6173. var blobURL;
  6174. try {
  6175. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  6176. }
  6177. catch (ex) {
  6178. // Chrome doesn't support oneTimeOnly parameter
  6179. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  6180. }
  6181. img.src = blobURL;
  6182. }
  6183. catch (e) {
  6184. img.src = "";
  6185. }
  6186. return img;
  6187. }
  6188. }
  6189. noIndexedDB();
  6190. }
  6191. return img;
  6192. };
  6193. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError, onRetry, retryStrategy) {
  6194. if (retryStrategy === void 0) { retryStrategy = null; }
  6195. url = Tools.CleanUrl(url);
  6196. url = Tools.PreprocessUrl(url);
  6197. var request = null;
  6198. var aborted = false;
  6199. var noIndexedDB = function (retryIndex) {
  6200. if (aborted) {
  6201. return;
  6202. }
  6203. var oldRequest = request;
  6204. request = new XMLHttpRequest();
  6205. var loadUrl = Tools.BaseUrl + url;
  6206. request.open('GET', loadUrl, true);
  6207. if (useArrayBuffer) {
  6208. request.responseType = "arraybuffer";
  6209. }
  6210. if (progressCallBack) {
  6211. request.onprogress = progressCallBack;
  6212. }
  6213. request.addEventListener("abort", function () {
  6214. aborted = true;
  6215. });
  6216. var onreadystatechange = function () {
  6217. var req = request;
  6218. // In case of undefined state in some browsers.
  6219. if (req.readyState === (XMLHttpRequest.DONE || 4)) {
  6220. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  6221. req.removeEventListener("readystatechange", onreadystatechange);
  6222. if (req.status >= 200 && req.status < 300 || (!Tools.IsWindowObjectExist() && (req.status === 0))) {
  6223. callback(!useArrayBuffer ? req.responseText : req.response, req.responseURL);
  6224. return;
  6225. }
  6226. retryStrategy = retryStrategy || Tools.DefaultRetryStrategy;
  6227. if (retryStrategy) {
  6228. var waitTime = retryStrategy(loadUrl, req, retryIndex || 0);
  6229. if (waitTime !== -1) {
  6230. setTimeout(function () { return noIndexedDB((retryIndex || 0) + 1); }, waitTime);
  6231. return;
  6232. }
  6233. }
  6234. var e = new LoadFileError("Error status: " + req.status + " - Unable to load " + loadUrl);
  6235. if (onError) {
  6236. onError(req, e);
  6237. }
  6238. else {
  6239. throw e;
  6240. }
  6241. }
  6242. };
  6243. request.addEventListener("readystatechange", onreadystatechange);
  6244. request.send();
  6245. if (oldRequest && onRetry) {
  6246. onRetry(oldRequest, request);
  6247. }
  6248. };
  6249. var loadFromIndexedDB = function () {
  6250. if (database) {
  6251. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  6252. }
  6253. };
  6254. // If file and file input are set
  6255. if (url.indexOf("file:") !== -1) {
  6256. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  6257. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  6258. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  6259. return request;
  6260. }
  6261. }
  6262. // Caching all files
  6263. if (database && database.enableSceneOffline) {
  6264. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6265. }
  6266. else {
  6267. noIndexedDB();
  6268. }
  6269. return request;
  6270. };
  6271. /**
  6272. * Load a script (identified by an url). When the url returns, the
  6273. * content of this file is added into a new script element, attached to the DOM (body element)
  6274. */
  6275. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  6276. var head = document.getElementsByTagName('head')[0];
  6277. var script = document.createElement('script');
  6278. script.type = 'text/javascript';
  6279. script.src = scriptUrl;
  6280. script.onload = function () {
  6281. if (onSuccess) {
  6282. onSuccess();
  6283. }
  6284. };
  6285. script.onerror = function (e) {
  6286. if (onError) {
  6287. onError("Unable to load script", e);
  6288. }
  6289. };
  6290. head.appendChild(script);
  6291. };
  6292. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  6293. var reader = new FileReader();
  6294. reader.onload = function (e) {
  6295. //target doesn't have result from ts 1.3
  6296. callback(e.target['result']);
  6297. };
  6298. reader.onprogress = progressCallback;
  6299. reader.readAsDataURL(fileToLoad);
  6300. };
  6301. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6302. var reader = new FileReader();
  6303. reader.onerror = function (e) {
  6304. Tools.Log("Error while reading file: " + fileToLoad.name);
  6305. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6306. };
  6307. reader.onload = function (e) {
  6308. //target doesn't have result from ts 1.3
  6309. callback(e.target['result']);
  6310. };
  6311. if (progressCallBack) {
  6312. reader.onprogress = progressCallBack;
  6313. }
  6314. if (!useArrayBuffer) {
  6315. // Asynchronous read
  6316. reader.readAsText(fileToLoad);
  6317. }
  6318. else {
  6319. reader.readAsArrayBuffer(fileToLoad);
  6320. }
  6321. };
  6322. //returns a downloadable url to a file content.
  6323. Tools.FileAsURL = function (content) {
  6324. var fileBlob = new Blob([content]);
  6325. var url = window.URL || window.webkitURL;
  6326. var link = url.createObjectURL(fileBlob);
  6327. return link;
  6328. };
  6329. // Misc.
  6330. Tools.Format = function (value, decimals) {
  6331. if (decimals === void 0) { decimals = 2; }
  6332. return value.toFixed(decimals);
  6333. };
  6334. Tools.CheckExtends = function (v, min, max) {
  6335. if (v.x < min.x)
  6336. min.x = v.x;
  6337. if (v.y < min.y)
  6338. min.y = v.y;
  6339. if (v.z < min.z)
  6340. min.z = v.z;
  6341. if (v.x > max.x)
  6342. max.x = v.x;
  6343. if (v.y > max.y)
  6344. max.y = v.y;
  6345. if (v.z > max.z)
  6346. max.z = v.z;
  6347. };
  6348. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6349. for (var prop in source) {
  6350. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6351. continue;
  6352. }
  6353. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6354. continue;
  6355. }
  6356. var sourceValue = source[prop];
  6357. var typeOfSourceValue = typeof sourceValue;
  6358. if (typeOfSourceValue === "function") {
  6359. continue;
  6360. }
  6361. if (typeOfSourceValue === "object") {
  6362. if (sourceValue instanceof Array) {
  6363. destination[prop] = [];
  6364. if (sourceValue.length > 0) {
  6365. if (typeof sourceValue[0] == "object") {
  6366. for (var index = 0; index < sourceValue.length; index++) {
  6367. var clonedValue = cloneValue(sourceValue[index], destination);
  6368. if (destination[prop].indexOf(clonedValue) === -1) {
  6369. destination[prop].push(clonedValue);
  6370. }
  6371. }
  6372. }
  6373. else {
  6374. destination[prop] = sourceValue.slice(0);
  6375. }
  6376. }
  6377. }
  6378. else {
  6379. destination[prop] = cloneValue(sourceValue, destination);
  6380. }
  6381. }
  6382. else {
  6383. destination[prop] = sourceValue;
  6384. }
  6385. }
  6386. };
  6387. Tools.IsEmpty = function (obj) {
  6388. for (var i in obj) {
  6389. if (obj.hasOwnProperty(i)) {
  6390. return false;
  6391. }
  6392. }
  6393. return true;
  6394. };
  6395. Tools.RegisterTopRootEvents = function (events) {
  6396. for (var index = 0; index < events.length; index++) {
  6397. var event = events[index];
  6398. window.addEventListener(event.name, event.handler, false);
  6399. try {
  6400. if (window.parent) {
  6401. window.parent.addEventListener(event.name, event.handler, false);
  6402. }
  6403. }
  6404. catch (e) {
  6405. // Silently fails...
  6406. }
  6407. }
  6408. };
  6409. Tools.UnregisterTopRootEvents = function (events) {
  6410. for (var index = 0; index < events.length; index++) {
  6411. var event = events[index];
  6412. window.removeEventListener(event.name, event.handler);
  6413. try {
  6414. if (window.parent) {
  6415. window.parent.removeEventListener(event.name, event.handler);
  6416. }
  6417. }
  6418. catch (e) {
  6419. // Silently fails...
  6420. }
  6421. }
  6422. };
  6423. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  6424. if (mimeType === void 0) { mimeType = "image/png"; }
  6425. // Read the contents of the framebuffer
  6426. var numberOfChannelsByLine = width * 4;
  6427. var halfHeight = height / 2;
  6428. //Reading datas from WebGL
  6429. var data = engine.readPixels(0, 0, width, height);
  6430. //To flip image on Y axis.
  6431. for (var i = 0; i < halfHeight; i++) {
  6432. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6433. var currentCell = j + i * numberOfChannelsByLine;
  6434. var targetLine = height - i - 1;
  6435. var targetCell = j + targetLine * numberOfChannelsByLine;
  6436. var temp = data[currentCell];
  6437. data[currentCell] = data[targetCell];
  6438. data[targetCell] = temp;
  6439. }
  6440. }
  6441. // Create a 2D canvas to store the result
  6442. if (!screenshotCanvas) {
  6443. screenshotCanvas = document.createElement('canvas');
  6444. }
  6445. screenshotCanvas.width = width;
  6446. screenshotCanvas.height = height;
  6447. var context = screenshotCanvas.getContext('2d');
  6448. if (context) {
  6449. // Copy the pixels to a 2D canvas
  6450. var imageData = context.createImageData(width, height);
  6451. var castData = (imageData.data);
  6452. castData.set(data);
  6453. context.putImageData(imageData, 0, 0);
  6454. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  6455. }
  6456. };
  6457. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  6458. if (mimeType === void 0) { mimeType = "image/png"; }
  6459. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6460. if (successCallback) {
  6461. successCallback(base64Image);
  6462. }
  6463. else {
  6464. // We need HTMLCanvasElement.toBlob for HD screenshots
  6465. if (!screenshotCanvas.toBlob) {
  6466. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  6467. screenshotCanvas.toBlob = function (callback, type, quality) {
  6468. var _this = this;
  6469. setTimeout(function () {
  6470. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  6471. for (var i = 0; i < len; i++) {
  6472. arr[i] = binStr.charCodeAt(i);
  6473. }
  6474. callback(new Blob([arr], { type: type || 'image/png' }));
  6475. });
  6476. };
  6477. }
  6478. screenshotCanvas.toBlob(function (blob) {
  6479. var url = URL.createObjectURL(blob);
  6480. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6481. if (("download" in document.createElement("a"))) {
  6482. var a = window.document.createElement("a");
  6483. a.href = url;
  6484. if (fileName) {
  6485. a.setAttribute("download", fileName);
  6486. }
  6487. else {
  6488. var date = new Date();
  6489. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6490. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6491. }
  6492. window.document.body.appendChild(a);
  6493. a.addEventListener("click", function () {
  6494. if (a.parentElement) {
  6495. a.parentElement.removeChild(a);
  6496. }
  6497. });
  6498. a.click();
  6499. }
  6500. else {
  6501. var newWindow = window.open("");
  6502. if (!newWindow)
  6503. return;
  6504. var img = newWindow.document.createElement("img");
  6505. img.onload = function () {
  6506. // no longer need to read the blob so it's revoked
  6507. URL.revokeObjectURL(url);
  6508. };
  6509. img.src = url;
  6510. newWindow.document.body.appendChild(img);
  6511. }
  6512. });
  6513. }
  6514. };
  6515. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6516. if (mimeType === void 0) { mimeType = "image/png"; }
  6517. var width;
  6518. var height;
  6519. // If a precision value is specified
  6520. if (size.precision) {
  6521. width = Math.round(engine.getRenderWidth() * size.precision);
  6522. height = Math.round(width / engine.getAspectRatio(camera));
  6523. }
  6524. else if (size.width && size.height) {
  6525. width = size.width;
  6526. height = size.height;
  6527. }
  6528. else if (size.width && !size.height) {
  6529. width = size.width;
  6530. height = Math.round(width / engine.getAspectRatio(camera));
  6531. }
  6532. else if (size.height && !size.width) {
  6533. height = size.height;
  6534. width = Math.round(height * engine.getAspectRatio(camera));
  6535. }
  6536. else if (!isNaN(size)) {
  6537. height = size;
  6538. width = size;
  6539. }
  6540. else {
  6541. Tools.Error("Invalid 'size' parameter !");
  6542. return;
  6543. }
  6544. if (!screenshotCanvas) {
  6545. screenshotCanvas = document.createElement('canvas');
  6546. }
  6547. screenshotCanvas.width = width;
  6548. screenshotCanvas.height = height;
  6549. var renderContext = screenshotCanvas.getContext("2d");
  6550. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6551. var newWidth = width;
  6552. var newHeight = newWidth / ratio;
  6553. if (newHeight > height) {
  6554. newHeight = height;
  6555. newWidth = newHeight * ratio;
  6556. }
  6557. var offsetX = Math.max(0, width - newWidth) / 2;
  6558. var offsetY = Math.max(0, height - newHeight) / 2;
  6559. var renderingCanvas = engine.getRenderingCanvas();
  6560. if (renderContext && renderingCanvas) {
  6561. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  6562. }
  6563. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6564. };
  6565. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  6566. if (mimeType === void 0) { mimeType = "image/png"; }
  6567. if (samples === void 0) { samples = 1; }
  6568. if (antialiasing === void 0) { antialiasing = false; }
  6569. var width;
  6570. var height;
  6571. //If a precision value is specified
  6572. if (size.precision) {
  6573. width = Math.round(engine.getRenderWidth() * size.precision);
  6574. height = Math.round(width / engine.getAspectRatio(camera));
  6575. size = { width: width, height: height };
  6576. }
  6577. else if (size.width && size.height) {
  6578. width = size.width;
  6579. height = size.height;
  6580. }
  6581. else if (size.width && !size.height) {
  6582. width = size.width;
  6583. height = Math.round(width / engine.getAspectRatio(camera));
  6584. size = { width: width, height: height };
  6585. }
  6586. else if (size.height && !size.width) {
  6587. height = size.height;
  6588. width = Math.round(height * engine.getAspectRatio(camera));
  6589. size = { width: width, height: height };
  6590. }
  6591. else if (!isNaN(size)) {
  6592. height = size;
  6593. width = size;
  6594. }
  6595. else {
  6596. Tools.Error("Invalid 'size' parameter !");
  6597. return;
  6598. }
  6599. var scene = camera.getScene();
  6600. var previousCamera = null;
  6601. if (scene.activeCamera !== camera) {
  6602. previousCamera = scene.activeCamera;
  6603. scene.activeCamera = camera;
  6604. }
  6605. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6606. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6607. texture.renderList = null;
  6608. texture.samples = samples;
  6609. if (antialiasing) {
  6610. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  6611. }
  6612. texture.onAfterRenderObservable.add(function () {
  6613. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  6614. });
  6615. scene.incrementRenderId();
  6616. scene.resetCachedMaterial();
  6617. texture.render(true);
  6618. texture.dispose();
  6619. if (previousCamera) {
  6620. scene.activeCamera = previousCamera;
  6621. }
  6622. camera.getProjectionMatrix(true); // Force cache refresh;
  6623. };
  6624. // XHR response validator for local file scenario
  6625. Tools.ValidateXHRData = function (xhr, dataType) {
  6626. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6627. if (dataType === void 0) { dataType = 7; }
  6628. try {
  6629. if (dataType & 1) {
  6630. if (xhr.responseText && xhr.responseText.length > 0) {
  6631. return true;
  6632. }
  6633. else if (dataType === 1) {
  6634. return false;
  6635. }
  6636. }
  6637. if (dataType & 2) {
  6638. // Check header width and height since there is no "TGA" magic number
  6639. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6640. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6641. return true;
  6642. }
  6643. else if (dataType === 2) {
  6644. return false;
  6645. }
  6646. }
  6647. if (dataType & 4) {
  6648. // Check for the "DDS" magic number
  6649. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6650. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6651. return true;
  6652. }
  6653. else {
  6654. return false;
  6655. }
  6656. }
  6657. }
  6658. catch (e) {
  6659. // Global protection
  6660. }
  6661. return false;
  6662. };
  6663. /**
  6664. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6665. * Be aware Math.random() could cause collisions, but:
  6666. * "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"
  6667. */
  6668. Tools.RandomId = function () {
  6669. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6670. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6671. return v.toString(16);
  6672. });
  6673. };
  6674. Object.defineProperty(Tools, "NoneLogLevel", {
  6675. get: function () {
  6676. return Tools._NoneLogLevel;
  6677. },
  6678. enumerable: true,
  6679. configurable: true
  6680. });
  6681. Object.defineProperty(Tools, "MessageLogLevel", {
  6682. get: function () {
  6683. return Tools._MessageLogLevel;
  6684. },
  6685. enumerable: true,
  6686. configurable: true
  6687. });
  6688. Object.defineProperty(Tools, "WarningLogLevel", {
  6689. get: function () {
  6690. return Tools._WarningLogLevel;
  6691. },
  6692. enumerable: true,
  6693. configurable: true
  6694. });
  6695. Object.defineProperty(Tools, "ErrorLogLevel", {
  6696. get: function () {
  6697. return Tools._ErrorLogLevel;
  6698. },
  6699. enumerable: true,
  6700. configurable: true
  6701. });
  6702. Object.defineProperty(Tools, "AllLogLevel", {
  6703. get: function () {
  6704. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6705. },
  6706. enumerable: true,
  6707. configurable: true
  6708. });
  6709. Tools._AddLogEntry = function (entry) {
  6710. Tools._LogCache = entry + Tools._LogCache;
  6711. if (Tools.OnNewCacheEntry) {
  6712. Tools.OnNewCacheEntry(entry);
  6713. }
  6714. };
  6715. Tools._FormatMessage = function (message) {
  6716. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6717. var date = new Date();
  6718. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6719. };
  6720. Tools._LogDisabled = function (message) {
  6721. // nothing to do
  6722. };
  6723. Tools._LogEnabled = function (message) {
  6724. var formattedMessage = Tools._FormatMessage(message);
  6725. console.log("BJS - " + formattedMessage);
  6726. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6727. Tools._AddLogEntry(entry);
  6728. };
  6729. Tools._WarnDisabled = function (message) {
  6730. // nothing to do
  6731. };
  6732. Tools._WarnEnabled = function (message) {
  6733. var formattedMessage = Tools._FormatMessage(message);
  6734. console.warn("BJS - " + formattedMessage);
  6735. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6736. Tools._AddLogEntry(entry);
  6737. };
  6738. Tools._ErrorDisabled = function (message) {
  6739. // nothing to do
  6740. };
  6741. Tools._ErrorEnabled = function (message) {
  6742. Tools.errorsCount++;
  6743. var formattedMessage = Tools._FormatMessage(message);
  6744. console.error("BJS - " + formattedMessage);
  6745. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6746. Tools._AddLogEntry(entry);
  6747. };
  6748. Object.defineProperty(Tools, "LogCache", {
  6749. get: function () {
  6750. return Tools._LogCache;
  6751. },
  6752. enumerable: true,
  6753. configurable: true
  6754. });
  6755. Tools.ClearLogCache = function () {
  6756. Tools._LogCache = "";
  6757. Tools.errorsCount = 0;
  6758. };
  6759. Object.defineProperty(Tools, "LogLevels", {
  6760. set: function (level) {
  6761. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6762. Tools.Log = Tools._LogEnabled;
  6763. }
  6764. else {
  6765. Tools.Log = Tools._LogDisabled;
  6766. }
  6767. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6768. Tools.Warn = Tools._WarnEnabled;
  6769. }
  6770. else {
  6771. Tools.Warn = Tools._WarnDisabled;
  6772. }
  6773. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6774. Tools.Error = Tools._ErrorEnabled;
  6775. }
  6776. else {
  6777. Tools.Error = Tools._ErrorDisabled;
  6778. }
  6779. },
  6780. enumerable: true,
  6781. configurable: true
  6782. });
  6783. Tools.IsWindowObjectExist = function () {
  6784. return (typeof window) !== "undefined";
  6785. };
  6786. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6787. get: function () {
  6788. return Tools._PerformanceNoneLogLevel;
  6789. },
  6790. enumerable: true,
  6791. configurable: true
  6792. });
  6793. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6794. get: function () {
  6795. return Tools._PerformanceUserMarkLogLevel;
  6796. },
  6797. enumerable: true,
  6798. configurable: true
  6799. });
  6800. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6801. get: function () {
  6802. return Tools._PerformanceConsoleLogLevel;
  6803. },
  6804. enumerable: true,
  6805. configurable: true
  6806. });
  6807. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6808. set: function (level) {
  6809. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6810. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6811. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6812. return;
  6813. }
  6814. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6815. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6816. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6817. return;
  6818. }
  6819. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6820. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6821. },
  6822. enumerable: true,
  6823. configurable: true
  6824. });
  6825. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6826. };
  6827. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6828. };
  6829. Tools._StartUserMark = function (counterName, condition) {
  6830. if (condition === void 0) { condition = true; }
  6831. if (!Tools._performance) {
  6832. if (!Tools.IsWindowObjectExist()) {
  6833. return;
  6834. }
  6835. Tools._performance = window.performance;
  6836. }
  6837. if (!condition || !Tools._performance.mark) {
  6838. return;
  6839. }
  6840. Tools._performance.mark(counterName + "-Begin");
  6841. };
  6842. Tools._EndUserMark = function (counterName, condition) {
  6843. if (condition === void 0) { condition = true; }
  6844. if (!condition || !Tools._performance.mark) {
  6845. return;
  6846. }
  6847. Tools._performance.mark(counterName + "-End");
  6848. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6849. };
  6850. Tools._StartPerformanceConsole = function (counterName, condition) {
  6851. if (condition === void 0) { condition = true; }
  6852. if (!condition) {
  6853. return;
  6854. }
  6855. Tools._StartUserMark(counterName, condition);
  6856. if (console.time) {
  6857. console.time(counterName);
  6858. }
  6859. };
  6860. Tools._EndPerformanceConsole = function (counterName, condition) {
  6861. if (condition === void 0) { condition = true; }
  6862. if (!condition) {
  6863. return;
  6864. }
  6865. Tools._EndUserMark(counterName, condition);
  6866. if (console.time) {
  6867. console.timeEnd(counterName);
  6868. }
  6869. };
  6870. Object.defineProperty(Tools, "Now", {
  6871. get: function () {
  6872. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  6873. return window.performance.now();
  6874. }
  6875. return new Date().getTime();
  6876. },
  6877. enumerable: true,
  6878. configurable: true
  6879. });
  6880. /**
  6881. * This method will return the name of the class used to create the instance of the given object.
  6882. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6883. * @param object the object to get the class name from
  6884. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6885. */
  6886. Tools.GetClassName = function (object, isType) {
  6887. if (isType === void 0) { isType = false; }
  6888. var name = null;
  6889. if (!isType && object.getClassName) {
  6890. name = object.getClassName();
  6891. }
  6892. else {
  6893. if (object instanceof Object) {
  6894. var classObj = isType ? object : Object.getPrototypeOf(object);
  6895. name = classObj.constructor["__bjsclassName__"];
  6896. }
  6897. if (!name) {
  6898. name = typeof object;
  6899. }
  6900. }
  6901. return name;
  6902. };
  6903. Tools.First = function (array, predicate) {
  6904. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6905. var el = array_1[_i];
  6906. if (predicate(el)) {
  6907. return el;
  6908. }
  6909. }
  6910. return null;
  6911. };
  6912. /**
  6913. * This method will return the name of the full name of the class, including its owning module (if any).
  6914. * 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).
  6915. * @param object the object to get the class name from
  6916. * @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.
  6917. */
  6918. Tools.getFullClassName = function (object, isType) {
  6919. if (isType === void 0) { isType = false; }
  6920. var className = null;
  6921. var moduleName = null;
  6922. if (!isType && object.getClassName) {
  6923. className = object.getClassName();
  6924. }
  6925. else {
  6926. if (object instanceof Object) {
  6927. var classObj = isType ? object : Object.getPrototypeOf(object);
  6928. className = classObj.constructor["__bjsclassName__"];
  6929. moduleName = classObj.constructor["__bjsmoduleName__"];
  6930. }
  6931. if (!className) {
  6932. className = typeof object;
  6933. }
  6934. }
  6935. if (!className) {
  6936. return null;
  6937. }
  6938. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6939. };
  6940. /**
  6941. * 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.
  6942. * @param array
  6943. */
  6944. Tools.arrayOrStringFeeder = function (array) {
  6945. return function (index) {
  6946. if (index >= array.length) {
  6947. return null;
  6948. }
  6949. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6950. if (val && val.getHashCode) {
  6951. val = val.getHashCode();
  6952. }
  6953. if (typeof val === "string") {
  6954. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6955. }
  6956. return val;
  6957. };
  6958. };
  6959. /**
  6960. * Compute the hashCode of a stream of number
  6961. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6962. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6963. * @return the hash code computed
  6964. */
  6965. Tools.hashCodeFromStream = function (feeder) {
  6966. // Based from here: http://stackoverflow.com/a/7616484/802124
  6967. var hash = 0;
  6968. var index = 0;
  6969. var chr = feeder(index++);
  6970. while (chr != null) {
  6971. hash = ((hash << 5) - hash) + chr;
  6972. hash |= 0; // Convert to 32bit integer
  6973. chr = feeder(index++);
  6974. }
  6975. return hash;
  6976. };
  6977. Tools.BaseUrl = "";
  6978. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  6979. /**
  6980. * Default behaviour for cors in the application.
  6981. * It can be a string if the expected behavior is identical in the entire app.
  6982. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  6983. */
  6984. Tools.CorsBehavior = "anonymous";
  6985. Tools.UseFallbackTexture = true;
  6986. /**
  6987. * Use this object to register external classes like custom textures or material
  6988. * to allow the laoders to instantiate them
  6989. */
  6990. Tools.RegisteredExternalClasses = {};
  6991. // Used in case of a texture loading problem
  6992. 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";
  6993. Tools.PreprocessUrl = function (url) {
  6994. return url;
  6995. };
  6996. // Logs
  6997. Tools._NoneLogLevel = 0;
  6998. Tools._MessageLogLevel = 1;
  6999. Tools._WarningLogLevel = 2;
  7000. Tools._ErrorLogLevel = 4;
  7001. Tools._LogCache = "";
  7002. Tools.errorsCount = 0;
  7003. Tools.Log = Tools._LogEnabled;
  7004. Tools.Warn = Tools._WarnEnabled;
  7005. Tools.Error = Tools._ErrorEnabled;
  7006. // Performances
  7007. Tools._PerformanceNoneLogLevel = 0;
  7008. Tools._PerformanceUserMarkLogLevel = 1;
  7009. Tools._PerformanceConsoleLogLevel = 2;
  7010. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7011. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7012. return Tools;
  7013. }());
  7014. BABYLON.Tools = Tools;
  7015. /**
  7016. * This class is used to track a performance counter which is number based.
  7017. * The user has access to many properties which give statistics of different nature
  7018. *
  7019. * The implementer can track two kinds of Performance Counter: time and count
  7020. * 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.
  7021. * 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.
  7022. */
  7023. var PerfCounter = /** @class */ (function () {
  7024. function PerfCounter() {
  7025. this._startMonitoringTime = 0;
  7026. this._min = 0;
  7027. this._max = 0;
  7028. this._average = 0;
  7029. this._lastSecAverage = 0;
  7030. this._current = 0;
  7031. this._totalValueCount = 0;
  7032. this._totalAccumulated = 0;
  7033. this._lastSecAccumulated = 0;
  7034. this._lastSecTime = 0;
  7035. this._lastSecValueCount = 0;
  7036. }
  7037. Object.defineProperty(PerfCounter.prototype, "min", {
  7038. /**
  7039. * Returns the smallest value ever
  7040. */
  7041. get: function () {
  7042. return this._min;
  7043. },
  7044. enumerable: true,
  7045. configurable: true
  7046. });
  7047. Object.defineProperty(PerfCounter.prototype, "max", {
  7048. /**
  7049. * Returns the biggest value ever
  7050. */
  7051. get: function () {
  7052. return this._max;
  7053. },
  7054. enumerable: true,
  7055. configurable: true
  7056. });
  7057. Object.defineProperty(PerfCounter.prototype, "average", {
  7058. /**
  7059. * Returns the average value since the performance counter is running
  7060. */
  7061. get: function () {
  7062. return this._average;
  7063. },
  7064. enumerable: true,
  7065. configurable: true
  7066. });
  7067. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  7068. /**
  7069. * Returns the average value of the last second the counter was monitored
  7070. */
  7071. get: function () {
  7072. return this._lastSecAverage;
  7073. },
  7074. enumerable: true,
  7075. configurable: true
  7076. });
  7077. Object.defineProperty(PerfCounter.prototype, "current", {
  7078. /**
  7079. * Returns the current value
  7080. */
  7081. get: function () {
  7082. return this._current;
  7083. },
  7084. enumerable: true,
  7085. configurable: true
  7086. });
  7087. Object.defineProperty(PerfCounter.prototype, "total", {
  7088. get: function () {
  7089. return this._totalAccumulated;
  7090. },
  7091. enumerable: true,
  7092. configurable: true
  7093. });
  7094. Object.defineProperty(PerfCounter.prototype, "count", {
  7095. get: function () {
  7096. return this._totalValueCount;
  7097. },
  7098. enumerable: true,
  7099. configurable: true
  7100. });
  7101. /**
  7102. * Call this method to start monitoring a new frame.
  7103. * 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.
  7104. */
  7105. PerfCounter.prototype.fetchNewFrame = function () {
  7106. this._totalValueCount++;
  7107. this._current = 0;
  7108. this._lastSecValueCount++;
  7109. };
  7110. /**
  7111. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  7112. * @param newCount the count value to add to the monitored count
  7113. * @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.
  7114. */
  7115. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  7116. if (!PerfCounter.Enabled) {
  7117. return;
  7118. }
  7119. this._current += newCount;
  7120. if (fetchResult) {
  7121. this._fetchResult();
  7122. }
  7123. };
  7124. /**
  7125. * Start monitoring this performance counter
  7126. */
  7127. PerfCounter.prototype.beginMonitoring = function () {
  7128. if (!PerfCounter.Enabled) {
  7129. return;
  7130. }
  7131. this._startMonitoringTime = Tools.Now;
  7132. };
  7133. /**
  7134. * Compute the time lapsed since the previous beginMonitoring() call.
  7135. * @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
  7136. */
  7137. PerfCounter.prototype.endMonitoring = function (newFrame) {
  7138. if (newFrame === void 0) { newFrame = true; }
  7139. if (!PerfCounter.Enabled) {
  7140. return;
  7141. }
  7142. if (newFrame) {
  7143. this.fetchNewFrame();
  7144. }
  7145. var currentTime = Tools.Now;
  7146. this._current = currentTime - this._startMonitoringTime;
  7147. if (newFrame) {
  7148. this._fetchResult();
  7149. }
  7150. };
  7151. PerfCounter.prototype._fetchResult = function () {
  7152. this._totalAccumulated += this._current;
  7153. this._lastSecAccumulated += this._current;
  7154. // Min/Max update
  7155. this._min = Math.min(this._min, this._current);
  7156. this._max = Math.max(this._max, this._current);
  7157. this._average = this._totalAccumulated / this._totalValueCount;
  7158. // Reset last sec?
  7159. var now = Tools.Now;
  7160. if ((now - this._lastSecTime) > 1000) {
  7161. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  7162. this._lastSecTime = now;
  7163. this._lastSecAccumulated = 0;
  7164. this._lastSecValueCount = 0;
  7165. }
  7166. };
  7167. PerfCounter.Enabled = true;
  7168. return PerfCounter;
  7169. }());
  7170. BABYLON.PerfCounter = PerfCounter;
  7171. /**
  7172. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  7173. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  7174. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  7175. * @param name The name of the class, case should be preserved
  7176. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  7177. */
  7178. function className(name, module) {
  7179. return function (target) {
  7180. target["__bjsclassName__"] = name;
  7181. target["__bjsmoduleName__"] = (module != null) ? module : null;
  7182. };
  7183. }
  7184. BABYLON.className = className;
  7185. /**
  7186. * An implementation of a loop for asynchronous functions.
  7187. */
  7188. var AsyncLoop = /** @class */ (function () {
  7189. /**
  7190. * Constroctor.
  7191. * @param iterations the number of iterations.
  7192. * @param _fn the function to run each iteration
  7193. * @param _successCallback the callback that will be called upon succesful execution
  7194. * @param offset starting offset.
  7195. */
  7196. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  7197. if (offset === void 0) { offset = 0; }
  7198. this.iterations = iterations;
  7199. this._fn = _fn;
  7200. this._successCallback = _successCallback;
  7201. this.index = offset - 1;
  7202. this._done = false;
  7203. }
  7204. /**
  7205. * Execute the next iteration. Must be called after the last iteration was finished.
  7206. */
  7207. AsyncLoop.prototype.executeNext = function () {
  7208. if (!this._done) {
  7209. if (this.index + 1 < this.iterations) {
  7210. ++this.index;
  7211. this._fn(this);
  7212. }
  7213. else {
  7214. this.breakLoop();
  7215. }
  7216. }
  7217. };
  7218. /**
  7219. * Break the loop and run the success callback.
  7220. */
  7221. AsyncLoop.prototype.breakLoop = function () {
  7222. this._done = true;
  7223. this._successCallback();
  7224. };
  7225. /**
  7226. * Helper function
  7227. */
  7228. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  7229. if (offset === void 0) { offset = 0; }
  7230. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  7231. loop.executeNext();
  7232. return loop;
  7233. };
  7234. /**
  7235. * A for-loop that will run a given number of iterations synchronous and the rest async.
  7236. * @param iterations total number of iterations
  7237. * @param syncedIterations number of synchronous iterations in each async iteration.
  7238. * @param fn the function to call each iteration.
  7239. * @param callback a success call back that will be called when iterating stops.
  7240. * @param breakFunction a break condition (optional)
  7241. * @param timeout timeout settings for the setTimeout function. default - 0.
  7242. * @constructor
  7243. */
  7244. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  7245. if (timeout === void 0) { timeout = 0; }
  7246. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  7247. if (breakFunction && breakFunction())
  7248. loop.breakLoop();
  7249. else {
  7250. setTimeout(function () {
  7251. for (var i = 0; i < syncedIterations; ++i) {
  7252. var iteration = (loop.index * syncedIterations) + i;
  7253. if (iteration >= iterations)
  7254. break;
  7255. fn(iteration);
  7256. if (breakFunction && breakFunction()) {
  7257. loop.breakLoop();
  7258. break;
  7259. }
  7260. }
  7261. loop.executeNext();
  7262. }, timeout);
  7263. }
  7264. }, callback);
  7265. };
  7266. return AsyncLoop;
  7267. }());
  7268. BABYLON.AsyncLoop = AsyncLoop;
  7269. })(BABYLON || (BABYLON = {}));
  7270. //# sourceMappingURL=babylon.tools.js.map
  7271. var BABYLON;
  7272. (function (BABYLON) {
  7273. var Internals;
  7274. (function (Internals) {
  7275. var _AlphaState = /** @class */ (function () {
  7276. /**
  7277. * Initializes the state.
  7278. */
  7279. function _AlphaState() {
  7280. this._isAlphaBlendDirty = false;
  7281. this._isBlendFunctionParametersDirty = false;
  7282. this._isBlendEquationParametersDirty = false;
  7283. this._isBlendConstantsDirty = false;
  7284. this._alphaBlend = false;
  7285. this._blendFunctionParameters = new Array(4);
  7286. this._blendEquationParameters = new Array(2);
  7287. this._blendConstants = new Array(4);
  7288. this.reset();
  7289. }
  7290. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  7291. get: function () {
  7292. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  7293. },
  7294. enumerable: true,
  7295. configurable: true
  7296. });
  7297. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  7298. get: function () {
  7299. return this._alphaBlend;
  7300. },
  7301. set: function (value) {
  7302. if (this._alphaBlend === value) {
  7303. return;
  7304. }
  7305. this._alphaBlend = value;
  7306. this._isAlphaBlendDirty = true;
  7307. },
  7308. enumerable: true,
  7309. configurable: true
  7310. });
  7311. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  7312. if (this._blendConstants[0] === r &&
  7313. this._blendConstants[1] === g &&
  7314. this._blendConstants[2] === b &&
  7315. this._blendConstants[3] === a) {
  7316. return;
  7317. }
  7318. this._blendConstants[0] = r;
  7319. this._blendConstants[1] = g;
  7320. this._blendConstants[2] = b;
  7321. this._blendConstants[3] = a;
  7322. this._isBlendConstantsDirty = true;
  7323. };
  7324. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  7325. if (this._blendFunctionParameters[0] === value0 &&
  7326. this._blendFunctionParameters[1] === value1 &&
  7327. this._blendFunctionParameters[2] === value2 &&
  7328. this._blendFunctionParameters[3] === value3) {
  7329. return;
  7330. }
  7331. this._blendFunctionParameters[0] = value0;
  7332. this._blendFunctionParameters[1] = value1;
  7333. this._blendFunctionParameters[2] = value2;
  7334. this._blendFunctionParameters[3] = value3;
  7335. this._isBlendFunctionParametersDirty = true;
  7336. };
  7337. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  7338. if (this._blendEquationParameters[0] === rgb &&
  7339. this._blendEquationParameters[1] === alpha) {
  7340. return;
  7341. }
  7342. this._blendEquationParameters[0] = rgb;
  7343. this._blendEquationParameters[1] = alpha;
  7344. this._isBlendEquationParametersDirty = true;
  7345. };
  7346. _AlphaState.prototype.reset = function () {
  7347. this._alphaBlend = false;
  7348. this._blendFunctionParameters[0] = null;
  7349. this._blendFunctionParameters[1] = null;
  7350. this._blendFunctionParameters[2] = null;
  7351. this._blendFunctionParameters[3] = null;
  7352. this._blendEquationParameters[0] = null;
  7353. this._blendEquationParameters[1] = null;
  7354. this._blendConstants[0] = null;
  7355. this._blendConstants[1] = null;
  7356. this._blendConstants[2] = null;
  7357. this._blendConstants[3] = null;
  7358. this._isAlphaBlendDirty = true;
  7359. this._isBlendFunctionParametersDirty = false;
  7360. this._isBlendEquationParametersDirty = false;
  7361. this._isBlendConstantsDirty = false;
  7362. };
  7363. _AlphaState.prototype.apply = function (gl) {
  7364. if (!this.isDirty) {
  7365. return;
  7366. }
  7367. // Alpha blend
  7368. if (this._isAlphaBlendDirty) {
  7369. if (this._alphaBlend) {
  7370. gl.enable(gl.BLEND);
  7371. }
  7372. else {
  7373. gl.disable(gl.BLEND);
  7374. }
  7375. this._isAlphaBlendDirty = false;
  7376. }
  7377. // Alpha function
  7378. if (this._isBlendFunctionParametersDirty) {
  7379. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7380. this._isBlendFunctionParametersDirty = false;
  7381. }
  7382. // Alpha equation
  7383. if (this._isBlendEquationParametersDirty) {
  7384. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  7385. this._isBlendEquationParametersDirty = false;
  7386. }
  7387. // Constants
  7388. if (this._isBlendConstantsDirty) {
  7389. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  7390. this._isBlendConstantsDirty = false;
  7391. }
  7392. };
  7393. return _AlphaState;
  7394. }());
  7395. Internals._AlphaState = _AlphaState;
  7396. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7397. })(BABYLON || (BABYLON = {}));
  7398. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7399. var BABYLON;
  7400. (function (BABYLON) {
  7401. var Internals;
  7402. (function (Internals) {
  7403. var _DepthCullingState = /** @class */ (function () {
  7404. /**
  7405. * Initializes the state.
  7406. */
  7407. function _DepthCullingState() {
  7408. this._isDepthTestDirty = false;
  7409. this._isDepthMaskDirty = false;
  7410. this._isDepthFuncDirty = false;
  7411. this._isCullFaceDirty = false;
  7412. this._isCullDirty = false;
  7413. this._isZOffsetDirty = false;
  7414. this._isFrontFaceDirty = false;
  7415. this.reset();
  7416. }
  7417. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7418. get: function () {
  7419. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  7420. },
  7421. enumerable: true,
  7422. configurable: true
  7423. });
  7424. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7425. get: function () {
  7426. return this._zOffset;
  7427. },
  7428. set: function (value) {
  7429. if (this._zOffset === value) {
  7430. return;
  7431. }
  7432. this._zOffset = value;
  7433. this._isZOffsetDirty = true;
  7434. },
  7435. enumerable: true,
  7436. configurable: true
  7437. });
  7438. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7439. get: function () {
  7440. return this._cullFace;
  7441. },
  7442. set: function (value) {
  7443. if (this._cullFace === value) {
  7444. return;
  7445. }
  7446. this._cullFace = value;
  7447. this._isCullFaceDirty = true;
  7448. },
  7449. enumerable: true,
  7450. configurable: true
  7451. });
  7452. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7453. get: function () {
  7454. return this._cull;
  7455. },
  7456. set: function (value) {
  7457. if (this._cull === value) {
  7458. return;
  7459. }
  7460. this._cull = value;
  7461. this._isCullDirty = true;
  7462. },
  7463. enumerable: true,
  7464. configurable: true
  7465. });
  7466. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7467. get: function () {
  7468. return this._depthFunc;
  7469. },
  7470. set: function (value) {
  7471. if (this._depthFunc === value) {
  7472. return;
  7473. }
  7474. this._depthFunc = value;
  7475. this._isDepthFuncDirty = true;
  7476. },
  7477. enumerable: true,
  7478. configurable: true
  7479. });
  7480. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7481. get: function () {
  7482. return this._depthMask;
  7483. },
  7484. set: function (value) {
  7485. if (this._depthMask === value) {
  7486. return;
  7487. }
  7488. this._depthMask = value;
  7489. this._isDepthMaskDirty = true;
  7490. },
  7491. enumerable: true,
  7492. configurable: true
  7493. });
  7494. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7495. get: function () {
  7496. return this._depthTest;
  7497. },
  7498. set: function (value) {
  7499. if (this._depthTest === value) {
  7500. return;
  7501. }
  7502. this._depthTest = value;
  7503. this._isDepthTestDirty = true;
  7504. },
  7505. enumerable: true,
  7506. configurable: true
  7507. });
  7508. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  7509. get: function () {
  7510. return this._frontFace;
  7511. },
  7512. set: function (value) {
  7513. if (this._frontFace === value) {
  7514. return;
  7515. }
  7516. this._frontFace = value;
  7517. this._isFrontFaceDirty = true;
  7518. },
  7519. enumerable: true,
  7520. configurable: true
  7521. });
  7522. _DepthCullingState.prototype.reset = function () {
  7523. this._depthMask = true;
  7524. this._depthTest = true;
  7525. this._depthFunc = null;
  7526. this._cullFace = null;
  7527. this._cull = null;
  7528. this._zOffset = 0;
  7529. this._frontFace = null;
  7530. this._isDepthTestDirty = true;
  7531. this._isDepthMaskDirty = true;
  7532. this._isDepthFuncDirty = false;
  7533. this._isCullFaceDirty = false;
  7534. this._isCullDirty = false;
  7535. this._isZOffsetDirty = false;
  7536. this._isFrontFaceDirty = false;
  7537. };
  7538. _DepthCullingState.prototype.apply = function (gl) {
  7539. if (!this.isDirty) {
  7540. return;
  7541. }
  7542. // Cull
  7543. if (this._isCullDirty) {
  7544. if (this.cull) {
  7545. gl.enable(gl.CULL_FACE);
  7546. }
  7547. else {
  7548. gl.disable(gl.CULL_FACE);
  7549. }
  7550. this._isCullDirty = false;
  7551. }
  7552. // Cull face
  7553. if (this._isCullFaceDirty) {
  7554. gl.cullFace(this.cullFace);
  7555. this._isCullFaceDirty = false;
  7556. }
  7557. // Depth mask
  7558. if (this._isDepthMaskDirty) {
  7559. gl.depthMask(this.depthMask);
  7560. this._isDepthMaskDirty = false;
  7561. }
  7562. // Depth test
  7563. if (this._isDepthTestDirty) {
  7564. if (this.depthTest) {
  7565. gl.enable(gl.DEPTH_TEST);
  7566. }
  7567. else {
  7568. gl.disable(gl.DEPTH_TEST);
  7569. }
  7570. this._isDepthTestDirty = false;
  7571. }
  7572. // Depth func
  7573. if (this._isDepthFuncDirty) {
  7574. gl.depthFunc(this.depthFunc);
  7575. this._isDepthFuncDirty = false;
  7576. }
  7577. // zOffset
  7578. if (this._isZOffsetDirty) {
  7579. if (this.zOffset) {
  7580. gl.enable(gl.POLYGON_OFFSET_FILL);
  7581. gl.polygonOffset(this.zOffset, 0);
  7582. }
  7583. else {
  7584. gl.disable(gl.POLYGON_OFFSET_FILL);
  7585. }
  7586. this._isZOffsetDirty = false;
  7587. }
  7588. // Front face
  7589. if (this._isFrontFaceDirty) {
  7590. gl.frontFace(this.frontFace);
  7591. this._isFrontFaceDirty = false;
  7592. }
  7593. };
  7594. return _DepthCullingState;
  7595. }());
  7596. Internals._DepthCullingState = _DepthCullingState;
  7597. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7598. })(BABYLON || (BABYLON = {}));
  7599. //# sourceMappingURL=babylon.depthCullingState.js.map
  7600. var BABYLON;
  7601. (function (BABYLON) {
  7602. var Internals;
  7603. (function (Internals) {
  7604. var _StencilState = /** @class */ (function () {
  7605. function _StencilState() {
  7606. this._isStencilTestDirty = false;
  7607. this._isStencilMaskDirty = false;
  7608. this._isStencilFuncDirty = false;
  7609. this._isStencilOpDirty = false;
  7610. this.reset();
  7611. }
  7612. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7613. get: function () {
  7614. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7615. },
  7616. enumerable: true,
  7617. configurable: true
  7618. });
  7619. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7620. get: function () {
  7621. return this._stencilFunc;
  7622. },
  7623. set: function (value) {
  7624. if (this._stencilFunc === value) {
  7625. return;
  7626. }
  7627. this._stencilFunc = value;
  7628. this._isStencilFuncDirty = true;
  7629. },
  7630. enumerable: true,
  7631. configurable: true
  7632. });
  7633. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7634. get: function () {
  7635. return this._stencilFuncRef;
  7636. },
  7637. set: function (value) {
  7638. if (this._stencilFuncRef === value) {
  7639. return;
  7640. }
  7641. this._stencilFuncRef = value;
  7642. this._isStencilFuncDirty = true;
  7643. },
  7644. enumerable: true,
  7645. configurable: true
  7646. });
  7647. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7648. get: function () {
  7649. return this._stencilFuncMask;
  7650. },
  7651. set: function (value) {
  7652. if (this._stencilFuncMask === value) {
  7653. return;
  7654. }
  7655. this._stencilFuncMask = value;
  7656. this._isStencilFuncDirty = true;
  7657. },
  7658. enumerable: true,
  7659. configurable: true
  7660. });
  7661. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7662. get: function () {
  7663. return this._stencilOpStencilFail;
  7664. },
  7665. set: function (value) {
  7666. if (this._stencilOpStencilFail === value) {
  7667. return;
  7668. }
  7669. this._stencilOpStencilFail = value;
  7670. this._isStencilOpDirty = true;
  7671. },
  7672. enumerable: true,
  7673. configurable: true
  7674. });
  7675. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7676. get: function () {
  7677. return this._stencilOpDepthFail;
  7678. },
  7679. set: function (value) {
  7680. if (this._stencilOpDepthFail === value) {
  7681. return;
  7682. }
  7683. this._stencilOpDepthFail = value;
  7684. this._isStencilOpDirty = true;
  7685. },
  7686. enumerable: true,
  7687. configurable: true
  7688. });
  7689. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7690. get: function () {
  7691. return this._stencilOpStencilDepthPass;
  7692. },
  7693. set: function (value) {
  7694. if (this._stencilOpStencilDepthPass === value) {
  7695. return;
  7696. }
  7697. this._stencilOpStencilDepthPass = value;
  7698. this._isStencilOpDirty = true;
  7699. },
  7700. enumerable: true,
  7701. configurable: true
  7702. });
  7703. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7704. get: function () {
  7705. return this._stencilMask;
  7706. },
  7707. set: function (value) {
  7708. if (this._stencilMask === value) {
  7709. return;
  7710. }
  7711. this._stencilMask = value;
  7712. this._isStencilMaskDirty = true;
  7713. },
  7714. enumerable: true,
  7715. configurable: true
  7716. });
  7717. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7718. get: function () {
  7719. return this._stencilTest;
  7720. },
  7721. set: function (value) {
  7722. if (this._stencilTest === value) {
  7723. return;
  7724. }
  7725. this._stencilTest = value;
  7726. this._isStencilTestDirty = true;
  7727. },
  7728. enumerable: true,
  7729. configurable: true
  7730. });
  7731. _StencilState.prototype.reset = function () {
  7732. this._stencilTest = false;
  7733. this._stencilMask = 0xFF;
  7734. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7735. this._stencilFuncRef = 1;
  7736. this._stencilFuncMask = 0xFF;
  7737. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7738. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7739. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7740. this._isStencilTestDirty = true;
  7741. this._isStencilMaskDirty = true;
  7742. this._isStencilFuncDirty = true;
  7743. this._isStencilOpDirty = true;
  7744. };
  7745. _StencilState.prototype.apply = function (gl) {
  7746. if (!this.isDirty) {
  7747. return;
  7748. }
  7749. // Stencil test
  7750. if (this._isStencilTestDirty) {
  7751. if (this.stencilTest) {
  7752. gl.enable(gl.STENCIL_TEST);
  7753. }
  7754. else {
  7755. gl.disable(gl.STENCIL_TEST);
  7756. }
  7757. this._isStencilTestDirty = false;
  7758. }
  7759. // Stencil mask
  7760. if (this._isStencilMaskDirty) {
  7761. gl.stencilMask(this.stencilMask);
  7762. this._isStencilMaskDirty = false;
  7763. }
  7764. // Stencil func
  7765. if (this._isStencilFuncDirty) {
  7766. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7767. this._isStencilFuncDirty = false;
  7768. }
  7769. // Stencil op
  7770. if (this._isStencilOpDirty) {
  7771. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7772. this._isStencilOpDirty = false;
  7773. }
  7774. };
  7775. return _StencilState;
  7776. }());
  7777. Internals._StencilState = _StencilState;
  7778. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7779. })(BABYLON || (BABYLON = {}));
  7780. //# sourceMappingURL=babylon.stencilState.js.map
  7781. var BABYLON;
  7782. (function (BABYLON) {
  7783. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7784. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  7785. };
  7786. var compileRawShader = function (gl, source, type) {
  7787. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7788. gl.shaderSource(shader, source);
  7789. gl.compileShader(shader);
  7790. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7791. var log = gl.getShaderInfoLog(shader);
  7792. if (log) {
  7793. throw new Error(log);
  7794. }
  7795. }
  7796. if (!shader) {
  7797. throw new Error("Something went wrong while compile the shader.");
  7798. }
  7799. return shader;
  7800. };
  7801. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7802. var magFilter = gl.NEAREST;
  7803. var minFilter = gl.NEAREST;
  7804. switch (samplingMode) {
  7805. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7806. magFilter = gl.LINEAR;
  7807. if (generateMipMaps) {
  7808. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7809. }
  7810. else {
  7811. minFilter = gl.LINEAR;
  7812. }
  7813. break;
  7814. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7815. magFilter = gl.LINEAR;
  7816. if (generateMipMaps) {
  7817. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7818. }
  7819. else {
  7820. minFilter = gl.LINEAR;
  7821. }
  7822. break;
  7823. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7824. magFilter = gl.NEAREST;
  7825. if (generateMipMaps) {
  7826. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7827. }
  7828. else {
  7829. minFilter = gl.NEAREST;
  7830. }
  7831. break;
  7832. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7833. magFilter = gl.NEAREST;
  7834. if (generateMipMaps) {
  7835. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7836. }
  7837. else {
  7838. minFilter = gl.NEAREST;
  7839. }
  7840. break;
  7841. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7842. magFilter = gl.NEAREST;
  7843. if (generateMipMaps) {
  7844. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7845. }
  7846. else {
  7847. minFilter = gl.LINEAR;
  7848. }
  7849. break;
  7850. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7851. magFilter = gl.NEAREST;
  7852. if (generateMipMaps) {
  7853. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7854. }
  7855. else {
  7856. minFilter = gl.LINEAR;
  7857. }
  7858. break;
  7859. case BABYLON.Texture.NEAREST_LINEAR:
  7860. magFilter = gl.NEAREST;
  7861. minFilter = gl.LINEAR;
  7862. break;
  7863. case BABYLON.Texture.NEAREST_NEAREST:
  7864. magFilter = gl.NEAREST;
  7865. minFilter = gl.NEAREST;
  7866. break;
  7867. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7868. magFilter = gl.LINEAR;
  7869. if (generateMipMaps) {
  7870. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7871. }
  7872. else {
  7873. minFilter = gl.NEAREST;
  7874. }
  7875. break;
  7876. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7877. magFilter = gl.LINEAR;
  7878. if (generateMipMaps) {
  7879. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7880. }
  7881. else {
  7882. minFilter = gl.NEAREST;
  7883. }
  7884. break;
  7885. case BABYLON.Texture.LINEAR_LINEAR:
  7886. magFilter = gl.LINEAR;
  7887. minFilter = gl.LINEAR;
  7888. break;
  7889. case BABYLON.Texture.LINEAR_NEAREST:
  7890. magFilter = gl.LINEAR;
  7891. minFilter = gl.NEAREST;
  7892. break;
  7893. }
  7894. return {
  7895. min: minFilter,
  7896. mag: magFilter
  7897. };
  7898. };
  7899. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7900. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7901. var img;
  7902. var onload = function () {
  7903. loadedImages[index] = img;
  7904. loadedImages._internalCount++;
  7905. if (scene) {
  7906. scene._removePendingData(img);
  7907. }
  7908. if (loadedImages._internalCount === 6) {
  7909. onfinish(loadedImages);
  7910. }
  7911. };
  7912. var onerror = function (message, exception) {
  7913. if (scene) {
  7914. scene._removePendingData(img);
  7915. }
  7916. if (onErrorCallBack) {
  7917. onErrorCallBack(message, exception);
  7918. }
  7919. };
  7920. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  7921. if (scene) {
  7922. scene._addPendingData(img);
  7923. }
  7924. };
  7925. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  7926. if (onError === void 0) { onError = null; }
  7927. var loadedImages = [];
  7928. loadedImages._internalCount = 0;
  7929. for (var index = 0; index < 6; index++) {
  7930. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  7931. }
  7932. };
  7933. var partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  7934. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7935. var onload = function (data) {
  7936. loadedFiles[index] = data;
  7937. loadedFiles._internalCount++;
  7938. if (loadedFiles._internalCount === 6) {
  7939. onfinish(loadedFiles);
  7940. }
  7941. };
  7942. var onerror = function (request, exception) {
  7943. if (onErrorCallBack && request) {
  7944. onErrorCallBack(request.status + " " + request.statusText, exception);
  7945. }
  7946. };
  7947. BABYLON.Tools.LoadFile(url, onload, undefined, undefined, true, onerror);
  7948. };
  7949. var cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  7950. if (onError === void 0) { onError = null; }
  7951. var loadedFiles = [];
  7952. loadedFiles._internalCount = 0;
  7953. for (var index = 0; index < 6; index++) {
  7954. partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  7955. }
  7956. };
  7957. var BufferPointer = /** @class */ (function () {
  7958. function BufferPointer() {
  7959. }
  7960. return BufferPointer;
  7961. }());
  7962. var InstancingAttributeInfo = /** @class */ (function () {
  7963. function InstancingAttributeInfo() {
  7964. }
  7965. return InstancingAttributeInfo;
  7966. }());
  7967. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7968. /**
  7969. * Define options used to create a render target texture
  7970. */
  7971. var RenderTargetCreationOptions = /** @class */ (function () {
  7972. function RenderTargetCreationOptions() {
  7973. }
  7974. return RenderTargetCreationOptions;
  7975. }());
  7976. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  7977. /**
  7978. * Regroup several parameters relative to the browser in use
  7979. */
  7980. var EngineCapabilities = /** @class */ (function () {
  7981. function EngineCapabilities() {
  7982. }
  7983. return EngineCapabilities;
  7984. }());
  7985. BABYLON.EngineCapabilities = EngineCapabilities;
  7986. /**
  7987. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7988. */
  7989. var Engine = /** @class */ (function () {
  7990. /**
  7991. * @constructor
  7992. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7993. * @param {boolean} [antialias] - enable antialias
  7994. * @param options - further options to be sent to the getContext function
  7995. */
  7996. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7997. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7998. var _this = this;
  7999. // Public members
  8000. this.forcePOTTextures = false;
  8001. this.isFullscreen = false;
  8002. this.isPointerLock = false;
  8003. this.cullBackFaces = true;
  8004. this.renderEvenInBackground = true;
  8005. this.preventCacheWipeBetweenFrames = false;
  8006. // To enable/disable IDB support and avoid XHR on .manifest
  8007. this.enableOfflineSupport = false;
  8008. this.scenes = new Array();
  8009. this.postProcesses = new Array();
  8010. // Observables
  8011. /**
  8012. * Observable event triggered each time the rendering canvas is resized
  8013. */
  8014. this.onResizeObservable = new BABYLON.Observable();
  8015. /**
  8016. * Observable event triggered each time the canvas loses focus
  8017. */
  8018. this.onCanvasBlurObservable = new BABYLON.Observable();
  8019. /**
  8020. * Observable event triggered each time the canvas gains focus
  8021. */
  8022. this.onCanvasFocusObservable = new BABYLON.Observable();
  8023. /**
  8024. * Observable event triggered each time the canvas receives pointerout event
  8025. */
  8026. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  8027. /**
  8028. * Observable event triggered before each texture is initialized
  8029. */
  8030. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  8031. //WebVR
  8032. this._vrDisplay = undefined;
  8033. this._vrSupported = false;
  8034. this._vrExclusivePointerMode = false;
  8035. // Uniform buffers list
  8036. this.disableUniformBuffers = false;
  8037. this._uniformBuffers = new Array();
  8038. // Observables
  8039. /**
  8040. * Observable raised when the engine begins a new frame
  8041. */
  8042. this.onBeginFrameObservable = new BABYLON.Observable();
  8043. /**
  8044. * Observable raised when the engine ends the current frame
  8045. */
  8046. this.onEndFrameObservable = new BABYLON.Observable();
  8047. /**
  8048. * Observable raised when the engine is about to compile a shader
  8049. */
  8050. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  8051. /**
  8052. * Observable raised when the engine has jsut compiled a shader
  8053. */
  8054. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  8055. this._windowIsBackground = false;
  8056. this._webGLVersion = 1.0;
  8057. this._badOS = false;
  8058. this._badDesktopOS = false;
  8059. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  8060. this.onVRRequestPresentComplete = new BABYLON.Observable();
  8061. this.onVRRequestPresentStart = new BABYLON.Observable();
  8062. this._colorWrite = true;
  8063. this._drawCalls = new BABYLON.PerfCounter();
  8064. this._renderingQueueLaunched = false;
  8065. this._activeRenderLoops = new Array();
  8066. // Deterministic lockstepMaxSteps
  8067. this._deterministicLockstep = false;
  8068. this._lockstepMaxSteps = 4;
  8069. // Lost context
  8070. this.onContextLostObservable = new BABYLON.Observable();
  8071. this.onContextRestoredObservable = new BABYLON.Observable();
  8072. this._contextWasLost = false;
  8073. this._doNotHandleContextLost = false;
  8074. // FPS
  8075. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  8076. this._fps = 60;
  8077. this._deltaTime = 0;
  8078. /**
  8079. * Turn this value on if you want to pause FPS computation when in background
  8080. */
  8081. this.disablePerformanceMonitorInBackground = false;
  8082. // States
  8083. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  8084. this._stencilState = new BABYLON.Internals._StencilState();
  8085. this._alphaState = new BABYLON.Internals._AlphaState();
  8086. this._alphaMode = Engine.ALPHA_DISABLE;
  8087. // Cache
  8088. this._internalTexturesCache = new Array();
  8089. this._boundTexturesCache = {};
  8090. this._boundTexturesOrder = new Array();
  8091. this._compiledEffects = {};
  8092. this._vertexAttribArraysEnabled = [];
  8093. this._uintIndicesCurrentlySet = false;
  8094. this._currentBoundBuffer = new Array();
  8095. this._currentBufferPointers = new Array();
  8096. this._currentInstanceLocations = new Array();
  8097. this._currentInstanceBuffers = new Array();
  8098. this._vaoRecordInProgress = false;
  8099. this._mustWipeVertexAttributes = false;
  8100. this._nextFreeTextureSlot = 0;
  8101. // Hardware supported Compressed Textures
  8102. this._texturesSupported = new Array();
  8103. this._onVRFullScreenTriggered = function () {
  8104. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  8105. //get the old size before we change
  8106. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  8107. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  8108. //get the width and height, change the render size
  8109. var leftEye = _this._vrDisplay.getEyeParameters('left');
  8110. _this.setHardwareScalingLevel(1);
  8111. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  8112. }
  8113. else {
  8114. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  8115. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  8116. }
  8117. };
  8118. this._boundUniforms = {};
  8119. var canvas = null;
  8120. Engine.Instances.push(this);
  8121. if (!canvasOrContext) {
  8122. return;
  8123. }
  8124. options = options || {};
  8125. if (canvasOrContext.getContext) {
  8126. canvas = canvasOrContext;
  8127. this._renderingCanvas = canvas;
  8128. if (antialias != null) {
  8129. options.antialias = antialias;
  8130. }
  8131. if (options.deterministicLockstep === undefined) {
  8132. options.deterministicLockstep = false;
  8133. }
  8134. if (options.lockstepMaxSteps === undefined) {
  8135. options.lockstepMaxSteps = 4;
  8136. }
  8137. if (options.preserveDrawingBuffer === undefined) {
  8138. options.preserveDrawingBuffer = false;
  8139. }
  8140. if (options.audioEngine === undefined) {
  8141. options.audioEngine = true;
  8142. }
  8143. if (options.stencil === undefined) {
  8144. options.stencil = true;
  8145. }
  8146. this._deterministicLockstep = options.deterministicLockstep;
  8147. this._lockstepMaxSteps = options.lockstepMaxSteps;
  8148. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  8149. // Exceptions
  8150. if (!options.disableWebGL2Support) {
  8151. if (navigator && navigator.userAgent) {
  8152. var ua = navigator.userAgent;
  8153. for (var _i = 0, _a = Engine.WebGL2UniformBuffersExceptionList; _i < _a.length; _i++) {
  8154. var exception = _a[_i];
  8155. if (ua.indexOf(exception) > -1) {
  8156. this.disableUniformBuffers = true;
  8157. break;
  8158. }
  8159. }
  8160. }
  8161. }
  8162. // GL
  8163. if (!options.disableWebGL2Support) {
  8164. try {
  8165. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  8166. if (this._gl) {
  8167. this._webGLVersion = 2.0;
  8168. }
  8169. }
  8170. catch (e) {
  8171. // Do nothing
  8172. }
  8173. }
  8174. if (!this._gl) {
  8175. if (!canvas) {
  8176. throw new Error("The provided canvas is null or undefined.");
  8177. }
  8178. try {
  8179. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  8180. }
  8181. catch (e) {
  8182. throw new Error("WebGL not supported");
  8183. }
  8184. }
  8185. if (!this._gl) {
  8186. throw new Error("WebGL not supported");
  8187. }
  8188. this._onCanvasFocus = function () {
  8189. _this.onCanvasFocusObservable.notifyObservers(_this);
  8190. };
  8191. this._onCanvasBlur = function () {
  8192. _this.onCanvasBlurObservable.notifyObservers(_this);
  8193. };
  8194. canvas.addEventListener("focus", this._onCanvasFocus);
  8195. canvas.addEventListener("blur", this._onCanvasBlur);
  8196. this._onBlur = function () {
  8197. if (_this.disablePerformanceMonitorInBackground) {
  8198. _this._performanceMonitor.disable();
  8199. }
  8200. _this._windowIsBackground = true;
  8201. };
  8202. this._onFocus = function () {
  8203. if (_this.disablePerformanceMonitorInBackground) {
  8204. _this._performanceMonitor.enable();
  8205. }
  8206. _this._windowIsBackground = false;
  8207. };
  8208. this._onCanvasPointerOut = function () {
  8209. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  8210. };
  8211. window.addEventListener("blur", this._onBlur);
  8212. window.addEventListener("focus", this._onFocus);
  8213. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  8214. // Context lost
  8215. if (!this._doNotHandleContextLost) {
  8216. this._onContextLost = function (evt) {
  8217. evt.preventDefault();
  8218. _this._contextWasLost = true;
  8219. BABYLON.Tools.Warn("WebGL context lost.");
  8220. _this.onContextLostObservable.notifyObservers(_this);
  8221. };
  8222. this._onContextRestored = function (evt) {
  8223. // Adding a timeout to avoid race condition at browser level
  8224. setTimeout(function () {
  8225. // Rebuild gl context
  8226. _this._initGLContext();
  8227. // Rebuild effects
  8228. _this._rebuildEffects();
  8229. // Rebuild textures
  8230. _this._rebuildInternalTextures();
  8231. // Rebuild buffers
  8232. _this._rebuildBuffers();
  8233. // Cache
  8234. _this.wipeCaches(true);
  8235. BABYLON.Tools.Warn("WebGL context successfully restored.");
  8236. _this.onContextRestoredObservable.notifyObservers(_this);
  8237. _this._contextWasLost = false;
  8238. }, 0);
  8239. };
  8240. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  8241. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  8242. }
  8243. }
  8244. else {
  8245. this._gl = canvasOrContext;
  8246. this._renderingCanvas = this._gl.canvas;
  8247. if (this._gl.renderbufferStorageMultisample) {
  8248. this._webGLVersion = 2.0;
  8249. }
  8250. options.stencil = this._gl.getContextAttributes().stencil;
  8251. }
  8252. // Viewport
  8253. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  8254. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  8255. this.resize();
  8256. this._isStencilEnable = options.stencil ? true : false;
  8257. this._initGLContext();
  8258. if (canvas) {
  8259. // Fullscreen
  8260. this._onFullscreenChange = function () {
  8261. if (document.fullscreen !== undefined) {
  8262. _this.isFullscreen = document.fullscreen;
  8263. }
  8264. else if (document.mozFullScreen !== undefined) {
  8265. _this.isFullscreen = document.mozFullScreen;
  8266. }
  8267. else if (document.webkitIsFullScreen !== undefined) {
  8268. _this.isFullscreen = document.webkitIsFullScreen;
  8269. }
  8270. else if (document.msIsFullScreen !== undefined) {
  8271. _this.isFullscreen = document.msIsFullScreen;
  8272. }
  8273. // Pointer lock
  8274. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  8275. canvas.requestPointerLock = canvas.requestPointerLock ||
  8276. canvas.msRequestPointerLock ||
  8277. canvas.mozRequestPointerLock ||
  8278. canvas.webkitRequestPointerLock;
  8279. if (canvas.requestPointerLock) {
  8280. canvas.requestPointerLock();
  8281. }
  8282. }
  8283. };
  8284. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  8285. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  8286. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  8287. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  8288. // Pointer lock
  8289. this._onPointerLockChange = function () {
  8290. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  8291. document.webkitPointerLockElement === canvas ||
  8292. document.msPointerLockElement === canvas ||
  8293. document.pointerLockElement === canvas);
  8294. };
  8295. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  8296. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  8297. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  8298. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  8299. this._onVRDisplayPointerRestricted = function () {
  8300. if (canvas) {
  8301. canvas.requestPointerLock();
  8302. }
  8303. };
  8304. this._onVRDisplayPointerUnrestricted = function () {
  8305. document.exitPointerLock();
  8306. };
  8307. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  8308. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  8309. }
  8310. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  8311. Engine.audioEngine = new BABYLON.AudioEngine();
  8312. }
  8313. // Prepare buffer pointers
  8314. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  8315. this._currentBufferPointers[i] = new BufferPointer();
  8316. }
  8317. // Load WebVR Devices
  8318. if (options.autoEnableWebVR) {
  8319. this.initWebVR();
  8320. }
  8321. // Detect if we are running on a faulty buggy OS.
  8322. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  8323. // Detect if we are running on a faulty buggy desktop OS.
  8324. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  8325. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  8326. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  8327. }
  8328. Object.defineProperty(Engine, "LastCreatedEngine", {
  8329. get: function () {
  8330. if (Engine.Instances.length === 0) {
  8331. return null;
  8332. }
  8333. return Engine.Instances[Engine.Instances.length - 1];
  8334. },
  8335. enumerable: true,
  8336. configurable: true
  8337. });
  8338. Object.defineProperty(Engine, "LastCreatedScene", {
  8339. get: function () {
  8340. var lastCreatedEngine = Engine.LastCreatedEngine;
  8341. if (!lastCreatedEngine) {
  8342. return null;
  8343. }
  8344. if (lastCreatedEngine.scenes.length === 0) {
  8345. return null;
  8346. }
  8347. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  8348. },
  8349. enumerable: true,
  8350. configurable: true
  8351. });
  8352. /**
  8353. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  8354. */
  8355. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  8356. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  8357. var engine = Engine.Instances[engineIndex];
  8358. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  8359. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  8360. }
  8361. }
  8362. };
  8363. Object.defineProperty(Engine, "NEVER", {
  8364. get: function () {
  8365. return Engine._NEVER;
  8366. },
  8367. enumerable: true,
  8368. configurable: true
  8369. });
  8370. Object.defineProperty(Engine, "ALWAYS", {
  8371. get: function () {
  8372. return Engine._ALWAYS;
  8373. },
  8374. enumerable: true,
  8375. configurable: true
  8376. });
  8377. Object.defineProperty(Engine, "LESS", {
  8378. get: function () {
  8379. return Engine._LESS;
  8380. },
  8381. enumerable: true,
  8382. configurable: true
  8383. });
  8384. Object.defineProperty(Engine, "EQUAL", {
  8385. get: function () {
  8386. return Engine._EQUAL;
  8387. },
  8388. enumerable: true,
  8389. configurable: true
  8390. });
  8391. Object.defineProperty(Engine, "LEQUAL", {
  8392. get: function () {
  8393. return Engine._LEQUAL;
  8394. },
  8395. enumerable: true,
  8396. configurable: true
  8397. });
  8398. Object.defineProperty(Engine, "GREATER", {
  8399. get: function () {
  8400. return Engine._GREATER;
  8401. },
  8402. enumerable: true,
  8403. configurable: true
  8404. });
  8405. Object.defineProperty(Engine, "GEQUAL", {
  8406. get: function () {
  8407. return Engine._GEQUAL;
  8408. },
  8409. enumerable: true,
  8410. configurable: true
  8411. });
  8412. Object.defineProperty(Engine, "NOTEQUAL", {
  8413. get: function () {
  8414. return Engine._NOTEQUAL;
  8415. },
  8416. enumerable: true,
  8417. configurable: true
  8418. });
  8419. Object.defineProperty(Engine, "KEEP", {
  8420. get: function () {
  8421. return Engine._KEEP;
  8422. },
  8423. enumerable: true,
  8424. configurable: true
  8425. });
  8426. Object.defineProperty(Engine, "REPLACE", {
  8427. get: function () {
  8428. return Engine._REPLACE;
  8429. },
  8430. enumerable: true,
  8431. configurable: true
  8432. });
  8433. Object.defineProperty(Engine, "INCR", {
  8434. get: function () {
  8435. return Engine._INCR;
  8436. },
  8437. enumerable: true,
  8438. configurable: true
  8439. });
  8440. Object.defineProperty(Engine, "DECR", {
  8441. get: function () {
  8442. return Engine._DECR;
  8443. },
  8444. enumerable: true,
  8445. configurable: true
  8446. });
  8447. Object.defineProperty(Engine, "INVERT", {
  8448. get: function () {
  8449. return Engine._INVERT;
  8450. },
  8451. enumerable: true,
  8452. configurable: true
  8453. });
  8454. Object.defineProperty(Engine, "INCR_WRAP", {
  8455. get: function () {
  8456. return Engine._INCR_WRAP;
  8457. },
  8458. enumerable: true,
  8459. configurable: true
  8460. });
  8461. Object.defineProperty(Engine, "DECR_WRAP", {
  8462. get: function () {
  8463. return Engine._DECR_WRAP;
  8464. },
  8465. enumerable: true,
  8466. configurable: true
  8467. });
  8468. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8469. get: function () {
  8470. return Engine._ALPHA_DISABLE;
  8471. },
  8472. enumerable: true,
  8473. configurable: true
  8474. });
  8475. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8476. get: function () {
  8477. return Engine._ALPHA_ONEONE;
  8478. },
  8479. enumerable: true,
  8480. configurable: true
  8481. });
  8482. Object.defineProperty(Engine, "ALPHA_ADD", {
  8483. get: function () {
  8484. return Engine._ALPHA_ADD;
  8485. },
  8486. enumerable: true,
  8487. configurable: true
  8488. });
  8489. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8490. get: function () {
  8491. return Engine._ALPHA_COMBINE;
  8492. },
  8493. enumerable: true,
  8494. configurable: true
  8495. });
  8496. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8497. get: function () {
  8498. return Engine._ALPHA_SUBTRACT;
  8499. },
  8500. enumerable: true,
  8501. configurable: true
  8502. });
  8503. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8504. get: function () {
  8505. return Engine._ALPHA_MULTIPLY;
  8506. },
  8507. enumerable: true,
  8508. configurable: true
  8509. });
  8510. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8511. get: function () {
  8512. return Engine._ALPHA_MAXIMIZED;
  8513. },
  8514. enumerable: true,
  8515. configurable: true
  8516. });
  8517. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8518. get: function () {
  8519. return Engine._ALPHA_PREMULTIPLIED;
  8520. },
  8521. enumerable: true,
  8522. configurable: true
  8523. });
  8524. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  8525. get: function () {
  8526. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  8527. },
  8528. enumerable: true,
  8529. configurable: true
  8530. });
  8531. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  8532. get: function () {
  8533. return Engine._ALPHA_INTERPOLATE;
  8534. },
  8535. enumerable: true,
  8536. configurable: true
  8537. });
  8538. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  8539. get: function () {
  8540. return Engine._ALPHA_SCREENMODE;
  8541. },
  8542. enumerable: true,
  8543. configurable: true
  8544. });
  8545. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8546. get: function () {
  8547. return Engine._DELAYLOADSTATE_NONE;
  8548. },
  8549. enumerable: true,
  8550. configurable: true
  8551. });
  8552. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8553. get: function () {
  8554. return Engine._DELAYLOADSTATE_LOADED;
  8555. },
  8556. enumerable: true,
  8557. configurable: true
  8558. });
  8559. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8560. get: function () {
  8561. return Engine._DELAYLOADSTATE_LOADING;
  8562. },
  8563. enumerable: true,
  8564. configurable: true
  8565. });
  8566. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8567. get: function () {
  8568. return Engine._DELAYLOADSTATE_NOTLOADED;
  8569. },
  8570. enumerable: true,
  8571. configurable: true
  8572. });
  8573. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8574. get: function () {
  8575. return Engine._TEXTUREFORMAT_ALPHA;
  8576. },
  8577. enumerable: true,
  8578. configurable: true
  8579. });
  8580. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8581. get: function () {
  8582. return Engine._TEXTUREFORMAT_LUMINANCE;
  8583. },
  8584. enumerable: true,
  8585. configurable: true
  8586. });
  8587. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8588. get: function () {
  8589. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8590. },
  8591. enumerable: true,
  8592. configurable: true
  8593. });
  8594. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8595. get: function () {
  8596. return Engine._TEXTUREFORMAT_RGB;
  8597. },
  8598. enumerable: true,
  8599. configurable: true
  8600. });
  8601. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8602. get: function () {
  8603. return Engine._TEXTUREFORMAT_RGBA;
  8604. },
  8605. enumerable: true,
  8606. configurable: true
  8607. });
  8608. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8609. get: function () {
  8610. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8611. },
  8612. enumerable: true,
  8613. configurable: true
  8614. });
  8615. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8616. get: function () {
  8617. return Engine._TEXTURETYPE_FLOAT;
  8618. },
  8619. enumerable: true,
  8620. configurable: true
  8621. });
  8622. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8623. get: function () {
  8624. return Engine._TEXTURETYPE_HALF_FLOAT;
  8625. },
  8626. enumerable: true,
  8627. configurable: true
  8628. });
  8629. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  8630. get: function () {
  8631. return Engine._SCALEMODE_FLOOR;
  8632. },
  8633. enumerable: true,
  8634. configurable: true
  8635. });
  8636. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  8637. get: function () {
  8638. return Engine._SCALEMODE_NEAREST;
  8639. },
  8640. enumerable: true,
  8641. configurable: true
  8642. });
  8643. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8644. get: function () {
  8645. return Engine._SCALEMODE_CEILING;
  8646. },
  8647. enumerable: true,
  8648. configurable: true
  8649. });
  8650. Object.defineProperty(Engine, "Version", {
  8651. get: function () {
  8652. return "3.2.0-alpha1";
  8653. },
  8654. enumerable: true,
  8655. configurable: true
  8656. });
  8657. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  8658. get: function () {
  8659. return this._vrExclusivePointerMode;
  8660. },
  8661. enumerable: true,
  8662. configurable: true
  8663. });
  8664. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  8665. get: function () {
  8666. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  8667. },
  8668. enumerable: true,
  8669. configurable: true
  8670. });
  8671. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8672. get: function () {
  8673. return this._webGLVersion < 2 || this.forcePOTTextures;
  8674. },
  8675. enumerable: true,
  8676. configurable: true
  8677. });
  8678. Object.defineProperty(Engine.prototype, "badOS", {
  8679. get: function () {
  8680. return this._badOS;
  8681. },
  8682. enumerable: true,
  8683. configurable: true
  8684. });
  8685. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8686. get: function () {
  8687. return this._badDesktopOS;
  8688. },
  8689. enumerable: true,
  8690. configurable: true
  8691. });
  8692. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8693. get: function () {
  8694. return this._performanceMonitor;
  8695. },
  8696. enumerable: true,
  8697. configurable: true
  8698. });
  8699. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8700. get: function () {
  8701. return this._texturesSupported;
  8702. },
  8703. enumerable: true,
  8704. configurable: true
  8705. });
  8706. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8707. get: function () {
  8708. return this._textureFormatInUse;
  8709. },
  8710. enumerable: true,
  8711. configurable: true
  8712. });
  8713. Object.defineProperty(Engine.prototype, "currentViewport", {
  8714. get: function () {
  8715. return this._cachedViewport;
  8716. },
  8717. enumerable: true,
  8718. configurable: true
  8719. });
  8720. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8721. // Empty texture
  8722. get: function () {
  8723. if (!this._emptyTexture) {
  8724. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8725. }
  8726. return this._emptyTexture;
  8727. },
  8728. enumerable: true,
  8729. configurable: true
  8730. });
  8731. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  8732. get: function () {
  8733. if (!this._emptyTexture3D) {
  8734. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8735. }
  8736. return this._emptyTexture3D;
  8737. },
  8738. enumerable: true,
  8739. configurable: true
  8740. });
  8741. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8742. get: function () {
  8743. if (!this._emptyCubeTexture) {
  8744. var faceData = new Uint8Array(4);
  8745. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8746. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8747. }
  8748. return this._emptyCubeTexture;
  8749. },
  8750. enumerable: true,
  8751. configurable: true
  8752. });
  8753. Engine.prototype._rebuildInternalTextures = function () {
  8754. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8755. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8756. var internalTexture = currentState_1[_i];
  8757. internalTexture._rebuild();
  8758. }
  8759. };
  8760. Engine.prototype._rebuildEffects = function () {
  8761. for (var key in this._compiledEffects) {
  8762. var effect = this._compiledEffects[key];
  8763. effect._prepareEffect();
  8764. }
  8765. BABYLON.Effect.ResetCache();
  8766. };
  8767. Engine.prototype._rebuildBuffers = function () {
  8768. // Index / Vertex
  8769. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8770. var scene = _a[_i];
  8771. scene.resetCachedMaterial();
  8772. scene._rebuildGeometries();
  8773. scene._rebuildTextures();
  8774. }
  8775. // Uniforms
  8776. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8777. var uniformBuffer = _c[_b];
  8778. uniformBuffer._rebuild();
  8779. }
  8780. };
  8781. Engine.prototype._initGLContext = function () {
  8782. // Caps
  8783. this._caps = new EngineCapabilities();
  8784. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8785. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8786. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8787. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8788. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8789. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8790. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8791. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8792. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8793. // Infos
  8794. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8795. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8796. if (rendererInfo != null) {
  8797. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8798. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8799. }
  8800. if (!this._glVendor) {
  8801. this._glVendor = "Unknown vendor";
  8802. }
  8803. if (!this._glRenderer) {
  8804. this._glRenderer = "Unknown renderer";
  8805. }
  8806. // Constants
  8807. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8808. if (this._gl.RGBA16F !== 0x881A) {
  8809. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8810. }
  8811. if (this._gl.RGBA32F !== 0x8814) {
  8812. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8813. }
  8814. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  8815. this._gl.DEPTH24_STENCIL8 = 35056;
  8816. }
  8817. // Extensions
  8818. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8819. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8820. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8821. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8822. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8823. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8824. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8825. 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');
  8826. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8827. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8828. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8829. this._caps.highPrecisionShaderSupported = true;
  8830. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  8831. if (this._caps.timerQuery) {
  8832. if (this._webGLVersion === 1) {
  8833. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  8834. }
  8835. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  8836. }
  8837. // Checks if some of the format renders first to allow the use of webgl inspector.
  8838. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8839. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8840. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8841. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8842. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8843. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8844. if (this._webGLVersion > 1) {
  8845. this._gl.HALF_FLOAT_OES = 0x140B;
  8846. }
  8847. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8848. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8849. // Draw buffers
  8850. if (this._webGLVersion > 1) {
  8851. this._caps.drawBuffersExtension = true;
  8852. }
  8853. else {
  8854. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  8855. if (drawBuffersExtension !== null) {
  8856. this._caps.drawBuffersExtension = true;
  8857. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  8858. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  8859. for (var i = 0; i < 16; i++) {
  8860. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  8861. }
  8862. }
  8863. else {
  8864. this._caps.drawBuffersExtension = false;
  8865. }
  8866. }
  8867. // Depth Texture
  8868. if (this._webGLVersion > 1) {
  8869. this._caps.depthTextureExtension = true;
  8870. }
  8871. else {
  8872. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  8873. if (depthTextureExtension != null) {
  8874. this._caps.depthTextureExtension = true;
  8875. }
  8876. }
  8877. // Vertex array object
  8878. if (this._webGLVersion > 1) {
  8879. this._caps.vertexArrayObject = true;
  8880. }
  8881. else {
  8882. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8883. if (vertexArrayObjectExtension != null) {
  8884. this._caps.vertexArrayObject = true;
  8885. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8886. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8887. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8888. }
  8889. else {
  8890. this._caps.vertexArrayObject = false;
  8891. }
  8892. }
  8893. // Instances count
  8894. if (this._webGLVersion > 1) {
  8895. this._caps.instancedArrays = true;
  8896. }
  8897. else {
  8898. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8899. if (instanceExtension != null) {
  8900. this._caps.instancedArrays = true;
  8901. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8902. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8903. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8904. }
  8905. else {
  8906. this._caps.instancedArrays = false;
  8907. }
  8908. }
  8909. // Intelligently add supported compressed formats in order to check for.
  8910. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8911. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8912. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8913. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8914. if (this._caps.astc)
  8915. this.texturesSupported.push('-astc.ktx');
  8916. if (this._caps.s3tc)
  8917. this.texturesSupported.push('-dxt.ktx');
  8918. if (this._caps.pvrtc)
  8919. this.texturesSupported.push('-pvrtc.ktx');
  8920. if (this._caps.etc2)
  8921. this.texturesSupported.push('-etc2.ktx');
  8922. if (this._caps.etc1)
  8923. this.texturesSupported.push('-etc1.ktx');
  8924. if (this._gl.getShaderPrecisionFormat) {
  8925. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8926. if (highp) {
  8927. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8928. }
  8929. }
  8930. // Depth buffer
  8931. this.setDepthBuffer(true);
  8932. this.setDepthFunctionToLessOrEqual();
  8933. this.setDepthWrite(true);
  8934. };
  8935. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8936. get: function () {
  8937. return this._webGLVersion;
  8938. },
  8939. enumerable: true,
  8940. configurable: true
  8941. });
  8942. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8943. /**
  8944. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8945. */
  8946. get: function () {
  8947. return this._isStencilEnable;
  8948. },
  8949. enumerable: true,
  8950. configurable: true
  8951. });
  8952. Engine.prototype._prepareWorkingCanvas = function () {
  8953. if (this._workingCanvas) {
  8954. return;
  8955. }
  8956. this._workingCanvas = document.createElement("canvas");
  8957. var context = this._workingCanvas.getContext("2d");
  8958. if (context) {
  8959. this._workingContext = context;
  8960. }
  8961. };
  8962. Engine.prototype.resetTextureCache = function () {
  8963. for (var key in this._boundTexturesCache) {
  8964. var boundTexture = this._boundTexturesCache[key];
  8965. if (boundTexture) {
  8966. this._removeDesignatedSlot(boundTexture);
  8967. }
  8968. this._boundTexturesCache[key] = null;
  8969. }
  8970. this._nextFreeTextureSlot = 0;
  8971. this._activeChannel = -1;
  8972. };
  8973. Engine.prototype.isDeterministicLockStep = function () {
  8974. return this._deterministicLockstep;
  8975. };
  8976. Engine.prototype.getLockstepMaxSteps = function () {
  8977. return this._lockstepMaxSteps;
  8978. };
  8979. Engine.prototype.getGlInfo = function () {
  8980. return {
  8981. vendor: this._glVendor,
  8982. renderer: this._glRenderer,
  8983. version: this._glVersion
  8984. };
  8985. };
  8986. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8987. if (useScreen === void 0) { useScreen = false; }
  8988. var viewport = camera.viewport;
  8989. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8990. };
  8991. Engine.prototype.getRenderWidth = function (useScreen) {
  8992. if (useScreen === void 0) { useScreen = false; }
  8993. if (!useScreen && this._currentRenderTarget) {
  8994. return this._currentRenderTarget.width;
  8995. }
  8996. return this._gl.drawingBufferWidth;
  8997. };
  8998. Engine.prototype.getRenderHeight = function (useScreen) {
  8999. if (useScreen === void 0) { useScreen = false; }
  9000. if (!useScreen && this._currentRenderTarget) {
  9001. return this._currentRenderTarget.height;
  9002. }
  9003. return this._gl.drawingBufferHeight;
  9004. };
  9005. Engine.prototype.getRenderingCanvas = function () {
  9006. return this._renderingCanvas;
  9007. };
  9008. Engine.prototype.getRenderingCanvasClientRect = function () {
  9009. if (!this._renderingCanvas) {
  9010. return null;
  9011. }
  9012. return this._renderingCanvas.getBoundingClientRect();
  9013. };
  9014. Engine.prototype.setHardwareScalingLevel = function (level) {
  9015. this._hardwareScalingLevel = level;
  9016. this.resize();
  9017. };
  9018. Engine.prototype.getHardwareScalingLevel = function () {
  9019. return this._hardwareScalingLevel;
  9020. };
  9021. Engine.prototype.getLoadedTexturesCache = function () {
  9022. return this._internalTexturesCache;
  9023. };
  9024. Engine.prototype.getCaps = function () {
  9025. return this._caps;
  9026. };
  9027. Object.defineProperty(Engine.prototype, "drawCalls", {
  9028. /** The number of draw calls submitted last frame */
  9029. get: function () {
  9030. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  9031. return 0;
  9032. },
  9033. enumerable: true,
  9034. configurable: true
  9035. });
  9036. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  9037. get: function () {
  9038. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  9039. return null;
  9040. },
  9041. enumerable: true,
  9042. configurable: true
  9043. });
  9044. Engine.prototype.getDepthFunction = function () {
  9045. return this._depthCullingState.depthFunc;
  9046. };
  9047. Engine.prototype.setDepthFunction = function (depthFunc) {
  9048. this._depthCullingState.depthFunc = depthFunc;
  9049. };
  9050. Engine.prototype.setDepthFunctionToGreater = function () {
  9051. this._depthCullingState.depthFunc = this._gl.GREATER;
  9052. };
  9053. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  9054. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  9055. };
  9056. Engine.prototype.setDepthFunctionToLess = function () {
  9057. this._depthCullingState.depthFunc = this._gl.LESS;
  9058. };
  9059. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  9060. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  9061. };
  9062. Engine.prototype.getStencilBuffer = function () {
  9063. return this._stencilState.stencilTest;
  9064. };
  9065. Engine.prototype.setStencilBuffer = function (enable) {
  9066. this._stencilState.stencilTest = enable;
  9067. };
  9068. Engine.prototype.getStencilMask = function () {
  9069. return this._stencilState.stencilMask;
  9070. };
  9071. Engine.prototype.setStencilMask = function (mask) {
  9072. this._stencilState.stencilMask = mask;
  9073. };
  9074. Engine.prototype.getStencilFunction = function () {
  9075. return this._stencilState.stencilFunc;
  9076. };
  9077. Engine.prototype.getStencilFunctionReference = function () {
  9078. return this._stencilState.stencilFuncRef;
  9079. };
  9080. Engine.prototype.getStencilFunctionMask = function () {
  9081. return this._stencilState.stencilFuncMask;
  9082. };
  9083. Engine.prototype.setStencilFunction = function (stencilFunc) {
  9084. this._stencilState.stencilFunc = stencilFunc;
  9085. };
  9086. Engine.prototype.setStencilFunctionReference = function (reference) {
  9087. this._stencilState.stencilFuncRef = reference;
  9088. };
  9089. Engine.prototype.setStencilFunctionMask = function (mask) {
  9090. this._stencilState.stencilFuncMask = mask;
  9091. };
  9092. Engine.prototype.getStencilOperationFail = function () {
  9093. return this._stencilState.stencilOpStencilFail;
  9094. };
  9095. Engine.prototype.getStencilOperationDepthFail = function () {
  9096. return this._stencilState.stencilOpDepthFail;
  9097. };
  9098. Engine.prototype.getStencilOperationPass = function () {
  9099. return this._stencilState.stencilOpStencilDepthPass;
  9100. };
  9101. Engine.prototype.setStencilOperationFail = function (operation) {
  9102. this._stencilState.stencilOpStencilFail = operation;
  9103. };
  9104. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  9105. this._stencilState.stencilOpDepthFail = operation;
  9106. };
  9107. Engine.prototype.setStencilOperationPass = function (operation) {
  9108. this._stencilState.stencilOpStencilDepthPass = operation;
  9109. };
  9110. Engine.prototype.setDitheringState = function (value) {
  9111. if (value) {
  9112. this._gl.enable(this._gl.DITHER);
  9113. }
  9114. else {
  9115. this._gl.disable(this._gl.DITHER);
  9116. }
  9117. };
  9118. Engine.prototype.setRasterizerState = function (value) {
  9119. if (value) {
  9120. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  9121. }
  9122. else {
  9123. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  9124. }
  9125. };
  9126. /**
  9127. * stop executing a render loop function and remove it from the execution array
  9128. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  9129. */
  9130. Engine.prototype.stopRenderLoop = function (renderFunction) {
  9131. if (!renderFunction) {
  9132. this._activeRenderLoops = [];
  9133. return;
  9134. }
  9135. var index = this._activeRenderLoops.indexOf(renderFunction);
  9136. if (index >= 0) {
  9137. this._activeRenderLoops.splice(index, 1);
  9138. }
  9139. };
  9140. Engine.prototype._renderLoop = function () {
  9141. if (!this._contextWasLost) {
  9142. var shouldRender = true;
  9143. if (!this.renderEvenInBackground && this._windowIsBackground) {
  9144. shouldRender = false;
  9145. }
  9146. if (shouldRender) {
  9147. // Start new frame
  9148. this.beginFrame();
  9149. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  9150. var renderFunction = this._activeRenderLoops[index];
  9151. renderFunction();
  9152. }
  9153. // Present
  9154. this.endFrame();
  9155. }
  9156. }
  9157. if (this._activeRenderLoops.length > 0) {
  9158. // Register new frame
  9159. var requester = null;
  9160. if (this._vrDisplay && this._vrDisplay.isPresenting)
  9161. requester = this._vrDisplay;
  9162. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  9163. }
  9164. else {
  9165. this._renderingQueueLaunched = false;
  9166. }
  9167. };
  9168. /**
  9169. * Register and execute a render loop. The engine can have more than one render function.
  9170. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  9171. * @example
  9172. * engine.runRenderLoop(function () {
  9173. * scene.render()
  9174. * })
  9175. */
  9176. Engine.prototype.runRenderLoop = function (renderFunction) {
  9177. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  9178. return;
  9179. }
  9180. this._activeRenderLoops.push(renderFunction);
  9181. if (!this._renderingQueueLaunched) {
  9182. this._renderingQueueLaunched = true;
  9183. this._bindedRenderFunction = this._renderLoop.bind(this);
  9184. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  9185. }
  9186. };
  9187. /**
  9188. * Toggle full screen mode.
  9189. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  9190. * @param {any} options - an options object to be sent to the requestFullscreen function
  9191. */
  9192. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  9193. if (this.isFullscreen) {
  9194. BABYLON.Tools.ExitFullscreen();
  9195. }
  9196. else {
  9197. this._pointerLockRequested = requestPointerLock;
  9198. if (this._renderingCanvas) {
  9199. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  9200. }
  9201. }
  9202. };
  9203. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  9204. if (stencil === void 0) { stencil = false; }
  9205. this.applyStates();
  9206. var mode = 0;
  9207. if (backBuffer && color) {
  9208. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  9209. mode |= this._gl.COLOR_BUFFER_BIT;
  9210. }
  9211. if (depth) {
  9212. this._gl.clearDepth(1.0);
  9213. mode |= this._gl.DEPTH_BUFFER_BIT;
  9214. }
  9215. if (stencil) {
  9216. this._gl.clearStencil(0);
  9217. mode |= this._gl.STENCIL_BUFFER_BIT;
  9218. }
  9219. this._gl.clear(mode);
  9220. };
  9221. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  9222. var gl = this._gl;
  9223. // Save state
  9224. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  9225. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  9226. // Change state
  9227. gl.enable(gl.SCISSOR_TEST);
  9228. gl.scissor(x, y, width, height);
  9229. // Clear
  9230. this.clear(clearColor, true, true, true);
  9231. // Restore state
  9232. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  9233. if (curScissor === true) {
  9234. gl.enable(gl.SCISSOR_TEST);
  9235. }
  9236. else {
  9237. gl.disable(gl.SCISSOR_TEST);
  9238. }
  9239. };
  9240. /**
  9241. * Set the WebGL's viewport
  9242. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  9243. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  9244. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  9245. */
  9246. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  9247. var width = requiredWidth || this.getRenderWidth();
  9248. var height = requiredHeight || this.getRenderHeight();
  9249. var x = viewport.x || 0;
  9250. var y = viewport.y || 0;
  9251. this._cachedViewport = viewport;
  9252. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  9253. };
  9254. /**
  9255. * Directly set the WebGL Viewport
  9256. * The x, y, width & height are directly passed to the WebGL call
  9257. * @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.
  9258. */
  9259. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  9260. var currentViewport = this._cachedViewport;
  9261. this._cachedViewport = null;
  9262. this._gl.viewport(x, y, width, height);
  9263. return currentViewport;
  9264. };
  9265. Engine.prototype.beginFrame = function () {
  9266. this.onBeginFrameObservable.notifyObservers(this);
  9267. this._measureFps();
  9268. };
  9269. Engine.prototype.endFrame = function () {
  9270. //force a flush in case we are using a bad OS.
  9271. if (this._badOS) {
  9272. this.flushFramebuffer();
  9273. }
  9274. //submit frame to the vr device, if enabled
  9275. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9276. // TODO: We should only submit the frame if we read frameData successfully.
  9277. this._vrDisplay.submitFrame();
  9278. }
  9279. this.onEndFrameObservable.notifyObservers(this);
  9280. };
  9281. /**
  9282. * resize the view according to the canvas' size.
  9283. * @example
  9284. * window.addEventListener("resize", function () {
  9285. * engine.resize();
  9286. * });
  9287. */
  9288. Engine.prototype.resize = function () {
  9289. // We're not resizing the size of the canvas while in VR mode & presenting
  9290. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  9291. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  9292. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  9293. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  9294. }
  9295. };
  9296. /**
  9297. * force a specific size of the canvas
  9298. * @param {number} width - the new canvas' width
  9299. * @param {number} height - the new canvas' height
  9300. */
  9301. Engine.prototype.setSize = function (width, height) {
  9302. if (!this._renderingCanvas) {
  9303. return;
  9304. }
  9305. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  9306. return;
  9307. }
  9308. this._renderingCanvas.width = width;
  9309. this._renderingCanvas.height = height;
  9310. for (var index = 0; index < this.scenes.length; index++) {
  9311. var scene = this.scenes[index];
  9312. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  9313. var cam = scene.cameras[camIndex];
  9314. cam._currentRenderId = 0;
  9315. }
  9316. }
  9317. if (this.onResizeObservable.hasObservers) {
  9318. this.onResizeObservable.notifyObservers(this);
  9319. }
  9320. };
  9321. // WebVR functions
  9322. Engine.prototype.isVRDevicePresent = function () {
  9323. return !!this._vrDisplay;
  9324. };
  9325. Engine.prototype.getVRDevice = function () {
  9326. return this._vrDisplay;
  9327. };
  9328. Engine.prototype.initWebVR = function () {
  9329. var _this = this;
  9330. var notifyObservers = function () {
  9331. var eventArgs = {
  9332. vrDisplay: _this._vrDisplay,
  9333. vrSupported: _this._vrSupported
  9334. };
  9335. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  9336. };
  9337. if (!this._onVrDisplayConnect) {
  9338. this._onVrDisplayConnect = function (event) {
  9339. _this._vrDisplay = event.display;
  9340. notifyObservers();
  9341. };
  9342. this._onVrDisplayDisconnect = function () {
  9343. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  9344. _this._vrDisplay = undefined;
  9345. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  9346. notifyObservers();
  9347. };
  9348. this._onVrDisplayPresentChange = function () {
  9349. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  9350. };
  9351. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  9352. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  9353. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  9354. }
  9355. this._getVRDisplays(notifyObservers);
  9356. return this.onVRDisplayChangedObservable;
  9357. };
  9358. Engine.prototype.enableVR = function () {
  9359. var _this = this;
  9360. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  9361. var onResolved = function () {
  9362. _this.onVRRequestPresentComplete.notifyObservers(true);
  9363. _this._onVRFullScreenTriggered();
  9364. };
  9365. var onRejected = function () {
  9366. _this.onVRRequestPresentComplete.notifyObservers(false);
  9367. };
  9368. this.onVRRequestPresentStart.notifyObservers(this);
  9369. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  9370. }
  9371. };
  9372. Engine.prototype.disableVR = function () {
  9373. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9374. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  9375. }
  9376. };
  9377. Engine.prototype._getVRDisplays = function (callback) {
  9378. var _this = this;
  9379. var getWebVRDevices = function (devices) {
  9380. _this._vrSupported = true;
  9381. // note that devices may actually be an empty array. This is fine;
  9382. // we expect this._vrDisplay to be undefined in this case.
  9383. return _this._vrDisplay = devices[0];
  9384. };
  9385. if (navigator.getVRDisplays) {
  9386. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  9387. // TODO: System CANNOT support WebVR, despite API presence.
  9388. _this._vrSupported = false;
  9389. callback();
  9390. });
  9391. }
  9392. else {
  9393. // TODO: Browser does not support WebVR
  9394. this._vrDisplay = undefined;
  9395. this._vrSupported = false;
  9396. callback();
  9397. }
  9398. };
  9399. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  9400. if (this._currentRenderTarget) {
  9401. this.unBindFramebuffer(this._currentRenderTarget);
  9402. }
  9403. this._currentRenderTarget = texture;
  9404. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  9405. var gl = this._gl;
  9406. if (texture.isCube) {
  9407. if (faceIndex === undefined) {
  9408. faceIndex = 0;
  9409. }
  9410. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  9411. }
  9412. if (this._cachedViewport && !forceFullscreenViewport) {
  9413. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  9414. }
  9415. else {
  9416. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  9417. }
  9418. this.wipeCaches();
  9419. };
  9420. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  9421. if (this._currentFramebuffer !== framebuffer) {
  9422. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  9423. this._currentFramebuffer = framebuffer;
  9424. }
  9425. };
  9426. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  9427. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  9428. this._currentRenderTarget = null;
  9429. // If MSAA, we need to bitblt back to main texture
  9430. var gl = this._gl;
  9431. if (texture._MSAAFramebuffer) {
  9432. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  9433. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  9434. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  9435. }
  9436. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  9437. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9438. gl.generateMipmap(gl.TEXTURE_2D);
  9439. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9440. }
  9441. if (onBeforeUnbind) {
  9442. if (texture._MSAAFramebuffer) {
  9443. // Bind the correct framebuffer
  9444. this.bindUnboundFramebuffer(texture._framebuffer);
  9445. }
  9446. onBeforeUnbind();
  9447. }
  9448. this.bindUnboundFramebuffer(null);
  9449. };
  9450. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  9451. if (texture.generateMipMaps) {
  9452. var gl = this._gl;
  9453. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9454. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9455. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9456. }
  9457. };
  9458. Engine.prototype.flushFramebuffer = function () {
  9459. this._gl.flush();
  9460. };
  9461. Engine.prototype.restoreDefaultFramebuffer = function () {
  9462. if (this._currentRenderTarget) {
  9463. this.unBindFramebuffer(this._currentRenderTarget);
  9464. }
  9465. else {
  9466. this.bindUnboundFramebuffer(null);
  9467. }
  9468. if (this._cachedViewport) {
  9469. this.setViewport(this._cachedViewport);
  9470. }
  9471. this.wipeCaches();
  9472. };
  9473. // UBOs
  9474. Engine.prototype.createUniformBuffer = function (elements) {
  9475. var ubo = this._gl.createBuffer();
  9476. if (!ubo) {
  9477. throw new Error("Unable to create uniform buffer");
  9478. }
  9479. this.bindUniformBuffer(ubo);
  9480. if (elements instanceof Float32Array) {
  9481. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  9482. }
  9483. else {
  9484. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  9485. }
  9486. this.bindUniformBuffer(null);
  9487. ubo.references = 1;
  9488. return ubo;
  9489. };
  9490. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  9491. var ubo = this._gl.createBuffer();
  9492. if (!ubo) {
  9493. throw new Error("Unable to create dynamic uniform buffer");
  9494. }
  9495. this.bindUniformBuffer(ubo);
  9496. if (elements instanceof Float32Array) {
  9497. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  9498. }
  9499. else {
  9500. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  9501. }
  9502. this.bindUniformBuffer(null);
  9503. ubo.references = 1;
  9504. return ubo;
  9505. };
  9506. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  9507. this.bindUniformBuffer(uniformBuffer);
  9508. if (offset === undefined) {
  9509. offset = 0;
  9510. }
  9511. if (count === undefined) {
  9512. if (elements instanceof Float32Array) {
  9513. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  9514. }
  9515. else {
  9516. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  9517. }
  9518. }
  9519. else {
  9520. if (elements instanceof Float32Array) {
  9521. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  9522. }
  9523. else {
  9524. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  9525. }
  9526. }
  9527. this.bindUniformBuffer(null);
  9528. };
  9529. // VBOs
  9530. Engine.prototype._resetVertexBufferBinding = function () {
  9531. this.bindArrayBuffer(null);
  9532. this._cachedVertexBuffers = null;
  9533. };
  9534. Engine.prototype.createVertexBuffer = function (vertices) {
  9535. var vbo = this._gl.createBuffer();
  9536. if (!vbo) {
  9537. throw new Error("Unable to create vertex buffer");
  9538. }
  9539. this.bindArrayBuffer(vbo);
  9540. if (vertices instanceof Float32Array) {
  9541. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  9542. }
  9543. else {
  9544. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  9545. }
  9546. this._resetVertexBufferBinding();
  9547. vbo.references = 1;
  9548. return vbo;
  9549. };
  9550. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  9551. var vbo = this._gl.createBuffer();
  9552. if (!vbo) {
  9553. throw new Error("Unable to create dynamic vertex buffer");
  9554. }
  9555. this.bindArrayBuffer(vbo);
  9556. if (vertices instanceof Float32Array) {
  9557. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  9558. }
  9559. else {
  9560. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  9561. }
  9562. this._resetVertexBufferBinding();
  9563. vbo.references = 1;
  9564. return vbo;
  9565. };
  9566. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  9567. if (offset === void 0) { offset = 0; }
  9568. // Force cache update
  9569. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  9570. this.bindIndexBuffer(indexBuffer);
  9571. var arrayBuffer;
  9572. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  9573. arrayBuffer = indices;
  9574. }
  9575. else {
  9576. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9577. }
  9578. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  9579. this._resetIndexBufferBinding();
  9580. };
  9581. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  9582. this.bindArrayBuffer(vertexBuffer);
  9583. if (offset === undefined) {
  9584. offset = 0;
  9585. }
  9586. if (count === undefined) {
  9587. if (vertices instanceof Float32Array) {
  9588. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  9589. }
  9590. else {
  9591. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  9592. }
  9593. }
  9594. else {
  9595. if (vertices instanceof Float32Array) {
  9596. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  9597. }
  9598. else {
  9599. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  9600. }
  9601. }
  9602. this._resetVertexBufferBinding();
  9603. };
  9604. Engine.prototype._resetIndexBufferBinding = function () {
  9605. this.bindIndexBuffer(null);
  9606. this._cachedIndexBuffer = null;
  9607. };
  9608. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  9609. var vbo = this._gl.createBuffer();
  9610. if (!vbo) {
  9611. throw new Error("Unable to create index buffer");
  9612. }
  9613. this.bindIndexBuffer(vbo);
  9614. // Check for 32 bits indices
  9615. var arrayBuffer;
  9616. var need32Bits = false;
  9617. if (indices instanceof Uint16Array) {
  9618. arrayBuffer = indices;
  9619. }
  9620. else {
  9621. //check 32 bit support
  9622. if (this._caps.uintIndices) {
  9623. if (indices instanceof Uint32Array) {
  9624. arrayBuffer = indices;
  9625. need32Bits = true;
  9626. }
  9627. else {
  9628. //number[] or Int32Array, check if 32 bit is necessary
  9629. for (var index = 0; index < indices.length; index++) {
  9630. if (indices[index] > 65535) {
  9631. need32Bits = true;
  9632. break;
  9633. }
  9634. }
  9635. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9636. }
  9637. }
  9638. else {
  9639. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  9640. arrayBuffer = new Uint16Array(indices);
  9641. }
  9642. }
  9643. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  9644. this._resetIndexBufferBinding();
  9645. vbo.references = 1;
  9646. vbo.is32Bits = need32Bits;
  9647. return vbo;
  9648. };
  9649. Engine.prototype.bindArrayBuffer = function (buffer) {
  9650. if (!this._vaoRecordInProgress) {
  9651. this._unbindVertexArrayObject();
  9652. }
  9653. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  9654. };
  9655. Engine.prototype.bindUniformBuffer = function (buffer) {
  9656. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  9657. };
  9658. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  9659. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  9660. };
  9661. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  9662. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  9663. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  9664. };
  9665. ;
  9666. Engine.prototype.bindIndexBuffer = function (buffer) {
  9667. if (!this._vaoRecordInProgress) {
  9668. this._unbindVertexArrayObject();
  9669. }
  9670. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  9671. };
  9672. Engine.prototype.bindBuffer = function (buffer, target) {
  9673. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  9674. this._gl.bindBuffer(target, buffer);
  9675. this._currentBoundBuffer[target] = buffer;
  9676. }
  9677. };
  9678. Engine.prototype.updateArrayBuffer = function (data) {
  9679. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9680. };
  9681. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  9682. var pointer = this._currentBufferPointers[indx];
  9683. var changed = false;
  9684. if (!pointer.active) {
  9685. changed = true;
  9686. pointer.active = true;
  9687. pointer.index = indx;
  9688. pointer.size = size;
  9689. pointer.type = type;
  9690. pointer.normalized = normalized;
  9691. pointer.stride = stride;
  9692. pointer.offset = offset;
  9693. pointer.buffer = buffer;
  9694. }
  9695. else {
  9696. if (pointer.buffer !== buffer) {
  9697. pointer.buffer = buffer;
  9698. changed = true;
  9699. }
  9700. if (pointer.size !== size) {
  9701. pointer.size = size;
  9702. changed = true;
  9703. }
  9704. if (pointer.type !== type) {
  9705. pointer.type = type;
  9706. changed = true;
  9707. }
  9708. if (pointer.normalized !== normalized) {
  9709. pointer.normalized = normalized;
  9710. changed = true;
  9711. }
  9712. if (pointer.stride !== stride) {
  9713. pointer.stride = stride;
  9714. changed = true;
  9715. }
  9716. if (pointer.offset !== offset) {
  9717. pointer.offset = offset;
  9718. changed = true;
  9719. }
  9720. }
  9721. if (changed || this._vaoRecordInProgress) {
  9722. this.bindArrayBuffer(buffer);
  9723. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9724. }
  9725. };
  9726. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9727. if (indexBuffer == null) {
  9728. return;
  9729. }
  9730. if (this._cachedIndexBuffer !== indexBuffer) {
  9731. this._cachedIndexBuffer = indexBuffer;
  9732. this.bindIndexBuffer(indexBuffer);
  9733. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9734. }
  9735. };
  9736. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9737. var attributes = effect.getAttributesNames();
  9738. if (!this._vaoRecordInProgress) {
  9739. this._unbindVertexArrayObject();
  9740. }
  9741. this.unbindAllAttributes();
  9742. for (var index = 0; index < attributes.length; index++) {
  9743. var order = effect.getAttributeLocation(index);
  9744. if (order >= 0) {
  9745. var vertexBuffer = vertexBuffers[attributes[index]];
  9746. if (!vertexBuffer) {
  9747. continue;
  9748. }
  9749. this._gl.enableVertexAttribArray(order);
  9750. if (!this._vaoRecordInProgress) {
  9751. this._vertexAttribArraysEnabled[order] = true;
  9752. }
  9753. var buffer = vertexBuffer.getBuffer();
  9754. if (buffer) {
  9755. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9756. if (vertexBuffer.getIsInstanced()) {
  9757. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  9758. if (!this._vaoRecordInProgress) {
  9759. this._currentInstanceLocations.push(order);
  9760. this._currentInstanceBuffers.push(buffer);
  9761. }
  9762. }
  9763. }
  9764. }
  9765. }
  9766. };
  9767. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9768. var vao = this._gl.createVertexArray();
  9769. this._vaoRecordInProgress = true;
  9770. this._gl.bindVertexArray(vao);
  9771. this._mustWipeVertexAttributes = true;
  9772. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9773. this.bindIndexBuffer(indexBuffer);
  9774. this._vaoRecordInProgress = false;
  9775. this._gl.bindVertexArray(null);
  9776. return vao;
  9777. };
  9778. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9779. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9780. this._cachedVertexArrayObject = vertexArrayObject;
  9781. this._gl.bindVertexArray(vertexArrayObject);
  9782. this._cachedVertexBuffers = null;
  9783. this._cachedIndexBuffer = null;
  9784. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9785. this._mustWipeVertexAttributes = true;
  9786. }
  9787. };
  9788. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9789. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9790. this._cachedVertexBuffers = vertexBuffer;
  9791. this._cachedEffectForVertexBuffers = effect;
  9792. var attributesCount = effect.getAttributesCount();
  9793. this._unbindVertexArrayObject();
  9794. this.unbindAllAttributes();
  9795. var offset = 0;
  9796. for (var index = 0; index < attributesCount; index++) {
  9797. if (index < vertexDeclaration.length) {
  9798. var order = effect.getAttributeLocation(index);
  9799. if (order >= 0) {
  9800. this._gl.enableVertexAttribArray(order);
  9801. this._vertexAttribArraysEnabled[order] = true;
  9802. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9803. }
  9804. offset += vertexDeclaration[index] * 4;
  9805. }
  9806. }
  9807. }
  9808. this._bindIndexBufferWithCache(indexBuffer);
  9809. };
  9810. Engine.prototype._unbindVertexArrayObject = function () {
  9811. if (!this._cachedVertexArrayObject) {
  9812. return;
  9813. }
  9814. this._cachedVertexArrayObject = null;
  9815. this._gl.bindVertexArray(null);
  9816. };
  9817. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9818. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9819. this._cachedVertexBuffers = vertexBuffers;
  9820. this._cachedEffectForVertexBuffers = effect;
  9821. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9822. }
  9823. this._bindIndexBufferWithCache(indexBuffer);
  9824. };
  9825. Engine.prototype.unbindInstanceAttributes = function () {
  9826. var boundBuffer;
  9827. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9828. var instancesBuffer = this._currentInstanceBuffers[i];
  9829. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9830. boundBuffer = instancesBuffer;
  9831. this.bindArrayBuffer(instancesBuffer);
  9832. }
  9833. var offsetLocation = this._currentInstanceLocations[i];
  9834. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9835. }
  9836. this._currentInstanceBuffers.length = 0;
  9837. this._currentInstanceLocations.length = 0;
  9838. };
  9839. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9840. this._gl.deleteVertexArray(vao);
  9841. };
  9842. Engine.prototype._releaseBuffer = function (buffer) {
  9843. buffer.references--;
  9844. if (buffer.references === 0) {
  9845. this._gl.deleteBuffer(buffer);
  9846. return true;
  9847. }
  9848. return false;
  9849. };
  9850. Engine.prototype.createInstancesBuffer = function (capacity) {
  9851. var buffer = this._gl.createBuffer();
  9852. if (!buffer) {
  9853. throw new Error("Unable to create instance buffer");
  9854. }
  9855. buffer.capacity = capacity;
  9856. this.bindArrayBuffer(buffer);
  9857. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9858. return buffer;
  9859. };
  9860. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9861. this._gl.deleteBuffer(buffer);
  9862. };
  9863. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9864. this.bindArrayBuffer(instancesBuffer);
  9865. if (data) {
  9866. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9867. }
  9868. if (offsetLocations[0].index !== undefined) {
  9869. var stride = 0;
  9870. for (var i = 0; i < offsetLocations.length; i++) {
  9871. var ai = offsetLocations[i];
  9872. stride += ai.attributeSize * 4;
  9873. }
  9874. for (var i = 0; i < offsetLocations.length; i++) {
  9875. var ai = offsetLocations[i];
  9876. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9877. this._gl.enableVertexAttribArray(ai.index);
  9878. this._vertexAttribArraysEnabled[ai.index] = true;
  9879. }
  9880. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9881. this._gl.vertexAttribDivisor(ai.index, 1);
  9882. this._currentInstanceLocations.push(ai.index);
  9883. this._currentInstanceBuffers.push(instancesBuffer);
  9884. }
  9885. }
  9886. else {
  9887. for (var index = 0; index < 4; index++) {
  9888. var offsetLocation = offsetLocations[index];
  9889. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9890. this._gl.enableVertexAttribArray(offsetLocation);
  9891. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9892. }
  9893. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9894. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9895. this._currentInstanceLocations.push(offsetLocation);
  9896. this._currentInstanceBuffers.push(instancesBuffer);
  9897. }
  9898. }
  9899. };
  9900. Engine.prototype.applyStates = function () {
  9901. this._depthCullingState.apply(this._gl);
  9902. this._stencilState.apply(this._gl);
  9903. this._alphaState.apply(this._gl);
  9904. };
  9905. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9906. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  9907. };
  9908. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9909. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  9910. };
  9911. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9912. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  9913. };
  9914. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  9915. // Apply states
  9916. this.applyStates();
  9917. this._drawCalls.addCount(1, false);
  9918. // Render
  9919. var drawMode = this.DrawMode(fillMode);
  9920. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9921. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9922. if (instancesCount) {
  9923. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  9924. }
  9925. else {
  9926. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  9927. }
  9928. };
  9929. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  9930. // Apply states
  9931. this.applyStates();
  9932. this._drawCalls.addCount(1, false);
  9933. var drawMode = this.DrawMode(fillMode);
  9934. if (instancesCount) {
  9935. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  9936. }
  9937. else {
  9938. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  9939. }
  9940. };
  9941. Engine.prototype.DrawMode = function (fillMode) {
  9942. switch (fillMode) {
  9943. // Triangle views
  9944. case BABYLON.Material.TriangleFillMode:
  9945. return this._gl.TRIANGLES;
  9946. case BABYLON.Material.PointFillMode:
  9947. return this._gl.POINTS;
  9948. case BABYLON.Material.WireFrameFillMode:
  9949. return this._gl.LINES;
  9950. // Draw modes
  9951. case BABYLON.Material.PointListDrawMode:
  9952. return this._gl.POINTS;
  9953. case BABYLON.Material.LineListDrawMode:
  9954. return this._gl.LINES;
  9955. case BABYLON.Material.LineLoopDrawMode:
  9956. return this._gl.LINE_LOOP;
  9957. case BABYLON.Material.LineStripDrawMode:
  9958. return this._gl.LINE_STRIP;
  9959. case BABYLON.Material.TriangleStripDrawMode:
  9960. return this._gl.TRIANGLE_STRIP;
  9961. case BABYLON.Material.TriangleFanDrawMode:
  9962. return this._gl.TRIANGLE_FAN;
  9963. default:
  9964. return this._gl.TRIANGLES;
  9965. }
  9966. };
  9967. // Shaders
  9968. Engine.prototype._releaseEffect = function (effect) {
  9969. if (this._compiledEffects[effect._key]) {
  9970. delete this._compiledEffects[effect._key];
  9971. this._deleteProgram(effect.getProgram());
  9972. }
  9973. };
  9974. Engine.prototype._deleteProgram = function (program) {
  9975. if (program) {
  9976. program.__SPECTOR_rebuildProgram = null;
  9977. if (program.transformFeedback) {
  9978. this.deleteTransformFeedback(program.transformFeedback);
  9979. program.transformFeedback = null;
  9980. }
  9981. this._gl.deleteProgram(program);
  9982. }
  9983. };
  9984. /**
  9985. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9986. * @param samplers An array of string used to represent textures
  9987. */
  9988. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9989. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9990. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9991. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9992. if (this._compiledEffects[name]) {
  9993. var compiledEffect = this._compiledEffects[name];
  9994. if (onCompiled && compiledEffect.isReady()) {
  9995. onCompiled(compiledEffect);
  9996. }
  9997. return compiledEffect;
  9998. }
  9999. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  10000. effect._key = name;
  10001. this._compiledEffects[name] = effect;
  10002. return effect;
  10003. };
  10004. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  10005. if (uniformsNames === void 0) { uniformsNames = []; }
  10006. if (samplers === void 0) { samplers = []; }
  10007. if (defines === void 0) { defines = ""; }
  10008. return this.createEffect({
  10009. vertex: "particles",
  10010. fragmentElement: fragmentName
  10011. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  10012. };
  10013. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  10014. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10015. context = context || this._gl;
  10016. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  10017. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  10018. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  10019. };
  10020. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  10021. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10022. context = context || this._gl;
  10023. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  10024. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  10025. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  10026. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  10027. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  10028. this.onAfterShaderCompilationObservable.notifyObservers(this);
  10029. return program;
  10030. };
  10031. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  10032. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10033. var shaderProgram = context.createProgram();
  10034. if (!shaderProgram) {
  10035. throw new Error("Unable to create program");
  10036. }
  10037. context.attachShader(shaderProgram, vertexShader);
  10038. context.attachShader(shaderProgram, fragmentShader);
  10039. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  10040. var transformFeedback = this.createTransformFeedback();
  10041. this.bindTransformFeedback(transformFeedback);
  10042. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  10043. shaderProgram.transformFeedback = transformFeedback;
  10044. }
  10045. context.linkProgram(shaderProgram);
  10046. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  10047. this.bindTransformFeedback(null);
  10048. }
  10049. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  10050. if (!linked) {
  10051. context.validateProgram(shaderProgram);
  10052. var error = context.getProgramInfoLog(shaderProgram);
  10053. if (error) {
  10054. throw new Error(error);
  10055. }
  10056. }
  10057. context.deleteShader(vertexShader);
  10058. context.deleteShader(fragmentShader);
  10059. return shaderProgram;
  10060. };
  10061. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  10062. var results = new Array();
  10063. for (var index = 0; index < uniformsNames.length; index++) {
  10064. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  10065. }
  10066. return results;
  10067. };
  10068. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  10069. var results = [];
  10070. for (var index = 0; index < attributesNames.length; index++) {
  10071. try {
  10072. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  10073. }
  10074. catch (e) {
  10075. results.push(-1);
  10076. }
  10077. }
  10078. return results;
  10079. };
  10080. Engine.prototype.enableEffect = function (effect) {
  10081. if (!effect) {
  10082. return;
  10083. }
  10084. // Use program
  10085. this.bindSamplers(effect);
  10086. this._currentEffect = effect;
  10087. if (effect.onBind) {
  10088. effect.onBind(effect);
  10089. }
  10090. effect.onBindObservable.notifyObservers(effect);
  10091. };
  10092. Engine.prototype.setIntArray = function (uniform, array) {
  10093. if (!uniform)
  10094. return;
  10095. this._gl.uniform1iv(uniform, array);
  10096. };
  10097. Engine.prototype.setIntArray2 = function (uniform, array) {
  10098. if (!uniform || array.length % 2 !== 0)
  10099. return;
  10100. this._gl.uniform2iv(uniform, array);
  10101. };
  10102. Engine.prototype.setIntArray3 = function (uniform, array) {
  10103. if (!uniform || array.length % 3 !== 0)
  10104. return;
  10105. this._gl.uniform3iv(uniform, array);
  10106. };
  10107. Engine.prototype.setIntArray4 = function (uniform, array) {
  10108. if (!uniform || array.length % 4 !== 0)
  10109. return;
  10110. this._gl.uniform4iv(uniform, array);
  10111. };
  10112. Engine.prototype.setFloatArray = function (uniform, array) {
  10113. if (!uniform)
  10114. return;
  10115. this._gl.uniform1fv(uniform, array);
  10116. };
  10117. Engine.prototype.setFloatArray2 = function (uniform, array) {
  10118. if (!uniform || array.length % 2 !== 0)
  10119. return;
  10120. this._gl.uniform2fv(uniform, array);
  10121. };
  10122. Engine.prototype.setFloatArray3 = function (uniform, array) {
  10123. if (!uniform || array.length % 3 !== 0)
  10124. return;
  10125. this._gl.uniform3fv(uniform, array);
  10126. };
  10127. Engine.prototype.setFloatArray4 = function (uniform, array) {
  10128. if (!uniform || array.length % 4 !== 0)
  10129. return;
  10130. this._gl.uniform4fv(uniform, array);
  10131. };
  10132. Engine.prototype.setArray = function (uniform, array) {
  10133. if (!uniform)
  10134. return;
  10135. this._gl.uniform1fv(uniform, array);
  10136. };
  10137. Engine.prototype.setArray2 = function (uniform, array) {
  10138. if (!uniform || array.length % 2 !== 0)
  10139. return;
  10140. this._gl.uniform2fv(uniform, array);
  10141. };
  10142. Engine.prototype.setArray3 = function (uniform, array) {
  10143. if (!uniform || array.length % 3 !== 0)
  10144. return;
  10145. this._gl.uniform3fv(uniform, array);
  10146. };
  10147. Engine.prototype.setArray4 = function (uniform, array) {
  10148. if (!uniform || array.length % 4 !== 0)
  10149. return;
  10150. this._gl.uniform4fv(uniform, array);
  10151. };
  10152. Engine.prototype.setMatrices = function (uniform, matrices) {
  10153. if (!uniform)
  10154. return;
  10155. this._gl.uniformMatrix4fv(uniform, false, matrices);
  10156. };
  10157. Engine.prototype.setMatrix = function (uniform, matrix) {
  10158. if (!uniform)
  10159. return;
  10160. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  10161. };
  10162. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  10163. if (!uniform)
  10164. return;
  10165. this._gl.uniformMatrix3fv(uniform, false, matrix);
  10166. };
  10167. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  10168. if (!uniform)
  10169. return;
  10170. this._gl.uniformMatrix2fv(uniform, false, matrix);
  10171. };
  10172. Engine.prototype.setInt = function (uniform, value) {
  10173. if (!uniform)
  10174. return;
  10175. this._gl.uniform1i(uniform, value);
  10176. };
  10177. Engine.prototype.setFloat = function (uniform, value) {
  10178. if (!uniform)
  10179. return;
  10180. this._gl.uniform1f(uniform, value);
  10181. };
  10182. Engine.prototype.setFloat2 = function (uniform, x, y) {
  10183. if (!uniform)
  10184. return;
  10185. this._gl.uniform2f(uniform, x, y);
  10186. };
  10187. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  10188. if (!uniform)
  10189. return;
  10190. this._gl.uniform3f(uniform, x, y, z);
  10191. };
  10192. Engine.prototype.setBool = function (uniform, bool) {
  10193. if (!uniform)
  10194. return;
  10195. this._gl.uniform1i(uniform, bool);
  10196. };
  10197. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  10198. if (!uniform)
  10199. return;
  10200. this._gl.uniform4f(uniform, x, y, z, w);
  10201. };
  10202. Engine.prototype.setColor3 = function (uniform, color3) {
  10203. if (!uniform)
  10204. return;
  10205. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  10206. };
  10207. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  10208. if (!uniform)
  10209. return;
  10210. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  10211. };
  10212. // States
  10213. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  10214. if (zOffset === void 0) { zOffset = 0; }
  10215. if (reverseSide === void 0) { reverseSide = false; }
  10216. // Culling
  10217. if (this._depthCullingState.cull !== culling || force) {
  10218. this._depthCullingState.cull = culling;
  10219. }
  10220. // Cull face
  10221. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  10222. if (this._depthCullingState.cullFace !== cullFace || force) {
  10223. this._depthCullingState.cullFace = cullFace;
  10224. }
  10225. // Z offset
  10226. this.setZOffset(zOffset);
  10227. // Front face
  10228. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  10229. if (this._depthCullingState.frontFace !== frontFace || force) {
  10230. this._depthCullingState.frontFace = frontFace;
  10231. }
  10232. };
  10233. Engine.prototype.setZOffset = function (value) {
  10234. this._depthCullingState.zOffset = value;
  10235. };
  10236. Engine.prototype.getZOffset = function () {
  10237. return this._depthCullingState.zOffset;
  10238. };
  10239. Engine.prototype.setDepthBuffer = function (enable) {
  10240. this._depthCullingState.depthTest = enable;
  10241. };
  10242. Engine.prototype.getDepthWrite = function () {
  10243. return this._depthCullingState.depthMask;
  10244. };
  10245. Engine.prototype.setDepthWrite = function (enable) {
  10246. this._depthCullingState.depthMask = enable;
  10247. };
  10248. Engine.prototype.setColorWrite = function (enable) {
  10249. this._gl.colorMask(enable, enable, enable, enable);
  10250. this._colorWrite = enable;
  10251. };
  10252. Engine.prototype.getColorWrite = function () {
  10253. return this._colorWrite;
  10254. };
  10255. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  10256. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  10257. };
  10258. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  10259. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  10260. if (this._alphaMode === mode) {
  10261. return;
  10262. }
  10263. switch (mode) {
  10264. case Engine.ALPHA_DISABLE:
  10265. this._alphaState.alphaBlend = false;
  10266. break;
  10267. case Engine.ALPHA_PREMULTIPLIED:
  10268. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  10269. this._alphaState.alphaBlend = true;
  10270. break;
  10271. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  10272. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  10273. this._alphaState.alphaBlend = true;
  10274. break;
  10275. case Engine.ALPHA_COMBINE:
  10276. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  10277. this._alphaState.alphaBlend = true;
  10278. break;
  10279. case Engine.ALPHA_ONEONE:
  10280. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10281. this._alphaState.alphaBlend = true;
  10282. break;
  10283. case Engine.ALPHA_ADD:
  10284. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10285. this._alphaState.alphaBlend = true;
  10286. break;
  10287. case Engine.ALPHA_SUBTRACT:
  10288. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10289. this._alphaState.alphaBlend = true;
  10290. break;
  10291. case Engine.ALPHA_MULTIPLY:
  10292. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  10293. this._alphaState.alphaBlend = true;
  10294. break;
  10295. case Engine.ALPHA_MAXIMIZED:
  10296. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10297. this._alphaState.alphaBlend = true;
  10298. break;
  10299. case Engine.ALPHA_INTERPOLATE:
  10300. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  10301. this._alphaState.alphaBlend = true;
  10302. break;
  10303. case Engine.ALPHA_SCREENMODE:
  10304. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  10305. this._alphaState.alphaBlend = true;
  10306. break;
  10307. }
  10308. if (!noDepthWriteChange) {
  10309. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  10310. }
  10311. this._alphaMode = mode;
  10312. };
  10313. Engine.prototype.getAlphaMode = function () {
  10314. return this._alphaMode;
  10315. };
  10316. Engine.prototype.setAlphaTesting = function (enable) {
  10317. this._alphaTest = enable;
  10318. };
  10319. Engine.prototype.getAlphaTesting = function () {
  10320. return !!this._alphaTest;
  10321. };
  10322. // Textures
  10323. Engine.prototype.wipeCaches = function (bruteForce) {
  10324. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  10325. return;
  10326. }
  10327. this.resetTextureCache();
  10328. this._currentEffect = null;
  10329. // 6/8/2017: deltakosh: Should not be required anymore.
  10330. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  10331. if (bruteForce) {
  10332. this._currentProgram = null;
  10333. this._stencilState.reset();
  10334. this._depthCullingState.reset();
  10335. this.setDepthFunctionToLessOrEqual();
  10336. this._alphaState.reset();
  10337. }
  10338. this._cachedVertexBuffers = null;
  10339. this._cachedIndexBuffer = null;
  10340. this._cachedEffectForVertexBuffers = null;
  10341. this._unbindVertexArrayObject();
  10342. this.bindIndexBuffer(null);
  10343. this.bindArrayBuffer(null);
  10344. };
  10345. /**
  10346. * Set the compressed texture format to use, based on the formats you have, and the formats
  10347. * supported by the hardware / browser.
  10348. *
  10349. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  10350. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  10351. * to API arguments needed to compressed textures. This puts the burden on the container
  10352. * generator to house the arcane code for determining these for current & future formats.
  10353. *
  10354. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  10355. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  10356. *
  10357. * Note: The result of this call is not taken into account when a texture is base64.
  10358. *
  10359. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  10360. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  10361. *
  10362. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  10363. * @returns The extension selected.
  10364. */
  10365. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  10366. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  10367. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  10368. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  10369. return this._textureFormatInUse = this._texturesSupported[i];
  10370. }
  10371. }
  10372. }
  10373. // actively set format to nothing, to allow this to be called more than once
  10374. // and possibly fail the 2nd time
  10375. this._textureFormatInUse = null;
  10376. return null;
  10377. };
  10378. Engine.prototype._createTexture = function () {
  10379. var texture = this._gl.createTexture();
  10380. if (!texture) {
  10381. throw new Error("Unable to create texture");
  10382. }
  10383. return texture;
  10384. };
  10385. /**
  10386. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  10387. * @param {string} urlArg- This contains one of the following:
  10388. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  10389. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  10390. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  10391. *
  10392. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  10393. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  10394. * @param {Scene} scene- Needed for loading to the correct scene.
  10395. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  10396. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  10397. * @param {callback} onError- Optional callback to be called upon failure.
  10398. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  10399. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  10400. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  10401. *
  10402. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  10403. */
  10404. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  10405. var _this = this;
  10406. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10407. if (onLoad === void 0) { onLoad = null; }
  10408. if (onError === void 0) { onError = null; }
  10409. if (buffer === void 0) { buffer = null; }
  10410. if (fallBack === void 0) { fallBack = null; }
  10411. if (format === void 0) { format = null; }
  10412. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  10413. var fromData = url.substr(0, 5) === "data:";
  10414. var fromBlob = url.substr(0, 5) === "blob:";
  10415. var isBase64 = fromData && url.indexOf("base64") !== -1;
  10416. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  10417. // establish the file extension, if possible
  10418. var lastDot = url.lastIndexOf('.');
  10419. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  10420. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  10421. var isTGA = (extension === ".tga");
  10422. // determine if a ktx file should be substituted
  10423. var isKTX = false;
  10424. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  10425. url = url.substring(0, lastDot) + this._textureFormatInUse;
  10426. isKTX = true;
  10427. }
  10428. if (scene) {
  10429. scene._addPendingData(texture);
  10430. }
  10431. texture.url = url;
  10432. texture.generateMipMaps = !noMipmap;
  10433. texture.samplingMode = samplingMode;
  10434. texture.invertY = invertY;
  10435. if (!this._doNotHandleContextLost) {
  10436. // Keep a link to the buffer only if we plan to handle context lost
  10437. texture._buffer = buffer;
  10438. }
  10439. var onLoadObserver = null;
  10440. if (onLoad && !fallBack) {
  10441. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  10442. }
  10443. if (!fallBack)
  10444. this._internalTexturesCache.push(texture);
  10445. var onerror = function (message, exception) {
  10446. if (scene) {
  10447. scene._removePendingData(texture);
  10448. }
  10449. if (onLoadObserver) {
  10450. texture.onLoadedObservable.remove(onLoadObserver);
  10451. }
  10452. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  10453. if (isKTX) {
  10454. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10455. }
  10456. else if (BABYLON.Tools.UseFallbackTexture) {
  10457. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10458. }
  10459. if (onError) {
  10460. onError(message || "Unknown error", exception);
  10461. }
  10462. };
  10463. var callback = null;
  10464. // processing for non-image formats
  10465. if (isKTX || isTGA || isDDS) {
  10466. if (isKTX) {
  10467. callback = function (data) {
  10468. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  10469. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  10470. ktx.uploadLevels(_this._gl, !noMipmap);
  10471. return false;
  10472. }, samplingMode);
  10473. };
  10474. }
  10475. else if (isTGA) {
  10476. callback = function (arrayBuffer) {
  10477. var data = new Uint8Array(arrayBuffer);
  10478. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  10479. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  10480. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  10481. return false;
  10482. }, samplingMode);
  10483. };
  10484. }
  10485. else if (isDDS) {
  10486. callback = function (data) {
  10487. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10488. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  10489. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  10490. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  10491. return false;
  10492. }, samplingMode);
  10493. };
  10494. }
  10495. if (!buffer) {
  10496. BABYLON.Tools.LoadFile(url, function (data) {
  10497. if (callback) {
  10498. callback(data);
  10499. }
  10500. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  10501. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  10502. });
  10503. }
  10504. else {
  10505. if (callback) {
  10506. callback(buffer);
  10507. }
  10508. }
  10509. // image format processing
  10510. }
  10511. else {
  10512. var onload = function (img) {
  10513. if (fromBlob && !_this._doNotHandleContextLost) {
  10514. // We need to store the image if we need to rebuild the texture
  10515. // in case of a webgl context lost
  10516. texture._buffer = img;
  10517. }
  10518. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  10519. var gl = _this._gl;
  10520. var isPot = (img.width === potWidth && img.height === potHeight);
  10521. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  10522. if (isPot) {
  10523. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10524. return false;
  10525. }
  10526. // Using shaders to rescale because canvas.drawImage is lossy
  10527. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10528. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  10529. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10530. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10531. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10532. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10533. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10534. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  10535. _this._releaseTexture(source);
  10536. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10537. continuationCallback();
  10538. });
  10539. return true;
  10540. }, samplingMode);
  10541. };
  10542. if (!fromData || isBase64)
  10543. if (buffer instanceof HTMLImageElement) {
  10544. onload(buffer);
  10545. }
  10546. else {
  10547. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10548. }
  10549. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  10550. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  10551. else
  10552. onload(buffer);
  10553. }
  10554. return texture;
  10555. };
  10556. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  10557. var _this = this;
  10558. var rtt = this.createRenderTargetTexture({
  10559. width: destination.width,
  10560. height: destination.height,
  10561. }, {
  10562. generateMipMaps: false,
  10563. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  10564. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  10565. generateDepthBuffer: false,
  10566. generateStencilBuffer: false
  10567. });
  10568. if (!this._rescalePostProcess) {
  10569. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  10570. }
  10571. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  10572. _this._rescalePostProcess.onApply = function (effect) {
  10573. effect._bindTexture("textureSampler", source);
  10574. };
  10575. var hostingScene = scene;
  10576. if (!hostingScene) {
  10577. hostingScene = _this.scenes[_this.scenes.length - 1];
  10578. }
  10579. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  10580. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  10581. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  10582. _this.unBindFramebuffer(rtt);
  10583. _this._releaseTexture(rtt);
  10584. if (onComplete) {
  10585. onComplete();
  10586. }
  10587. });
  10588. };
  10589. Engine.prototype._getInternalFormat = function (format) {
  10590. var internalFormat = this._gl.RGBA;
  10591. switch (format) {
  10592. case Engine.TEXTUREFORMAT_ALPHA:
  10593. internalFormat = this._gl.ALPHA;
  10594. break;
  10595. case Engine.TEXTUREFORMAT_LUMINANCE:
  10596. internalFormat = this._gl.LUMINANCE;
  10597. break;
  10598. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  10599. internalFormat = this._gl.LUMINANCE_ALPHA;
  10600. break;
  10601. case Engine.TEXTUREFORMAT_RGB:
  10602. internalFormat = this._gl.RGB;
  10603. break;
  10604. case Engine.TEXTUREFORMAT_RGBA:
  10605. internalFormat = this._gl.RGBA;
  10606. break;
  10607. }
  10608. return internalFormat;
  10609. };
  10610. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  10611. if (compression === void 0) { compression = null; }
  10612. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  10613. if (!texture) {
  10614. return;
  10615. }
  10616. var internalFormat = this._getInternalFormat(format);
  10617. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10618. var textureType = this._getWebGLTextureType(type);
  10619. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10620. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10621. if (!this._doNotHandleContextLost) {
  10622. texture._bufferView = data;
  10623. texture.format = format;
  10624. texture.type = type;
  10625. texture.invertY = invertY;
  10626. texture._compression = compression;
  10627. }
  10628. if (texture.width % 4 !== 0) {
  10629. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  10630. }
  10631. if (compression && data) {
  10632. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  10633. }
  10634. else {
  10635. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  10636. }
  10637. if (texture.generateMipMaps) {
  10638. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10639. }
  10640. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10641. this.resetTextureCache();
  10642. texture.isReady = true;
  10643. };
  10644. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  10645. if (compression === void 0) { compression = null; }
  10646. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  10647. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  10648. texture.baseWidth = width;
  10649. texture.baseHeight = height;
  10650. texture.width = width;
  10651. texture.height = height;
  10652. texture.format = format;
  10653. texture.generateMipMaps = generateMipMaps;
  10654. texture.samplingMode = samplingMode;
  10655. texture.invertY = invertY;
  10656. texture._compression = compression;
  10657. texture.type = type;
  10658. if (!this._doNotHandleContextLost) {
  10659. texture._bufferView = data;
  10660. }
  10661. this.updateRawTexture(texture, data, format, invertY, compression, type);
  10662. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10663. // Filters
  10664. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  10665. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10666. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10667. if (generateMipMaps) {
  10668. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10669. }
  10670. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10671. this._internalTexturesCache.push(texture);
  10672. return texture;
  10673. };
  10674. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  10675. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  10676. texture.baseWidth = width;
  10677. texture.baseHeight = height;
  10678. if (generateMipMaps) {
  10679. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  10680. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  10681. }
  10682. this.resetTextureCache();
  10683. texture.width = width;
  10684. texture.height = height;
  10685. texture.isReady = false;
  10686. texture.generateMipMaps = generateMipMaps;
  10687. texture.samplingMode = samplingMode;
  10688. this.updateTextureSamplingMode(samplingMode, texture);
  10689. this._internalTexturesCache.push(texture);
  10690. return texture;
  10691. };
  10692. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  10693. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  10694. if (texture.isCube) {
  10695. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10696. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10697. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10698. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10699. }
  10700. else if (texture.is3D) {
  10701. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  10702. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10703. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10704. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  10705. }
  10706. else {
  10707. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10708. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10709. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10710. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10711. }
  10712. texture.samplingMode = samplingMode;
  10713. };
  10714. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  10715. if (premulAlpha === void 0) { premulAlpha = false; }
  10716. if (!texture) {
  10717. return;
  10718. }
  10719. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10720. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  10721. if (premulAlpha) {
  10722. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  10723. }
  10724. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  10725. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  10726. if (texture.generateMipMaps) {
  10727. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10728. }
  10729. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10730. if (premulAlpha) {
  10731. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  10732. }
  10733. this.resetTextureCache();
  10734. texture.isReady = true;
  10735. };
  10736. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  10737. if (!texture || texture._isDisabled) {
  10738. return;
  10739. }
  10740. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10741. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  10742. try {
  10743. // Testing video texture support
  10744. if (this._videoTextureSupported === undefined) {
  10745. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10746. if (this._gl.getError() !== 0) {
  10747. this._videoTextureSupported = false;
  10748. }
  10749. else {
  10750. this._videoTextureSupported = true;
  10751. }
  10752. }
  10753. // Copy video through the current working canvas if video texture is not supported
  10754. if (!this._videoTextureSupported) {
  10755. if (!texture._workingCanvas) {
  10756. texture._workingCanvas = document.createElement("canvas");
  10757. var context = texture._workingCanvas.getContext("2d");
  10758. if (!context) {
  10759. throw new Error("Unable to get 2d context");
  10760. }
  10761. texture._workingContext = context;
  10762. texture._workingCanvas.width = texture.width;
  10763. texture._workingCanvas.height = texture.height;
  10764. }
  10765. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  10766. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  10767. }
  10768. else {
  10769. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10770. }
  10771. if (texture.generateMipMaps) {
  10772. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10773. }
  10774. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10775. this.resetTextureCache();
  10776. texture.isReady = true;
  10777. }
  10778. catch (ex) {
  10779. // Something unexpected
  10780. // Let's disable the texture
  10781. texture._isDisabled = true;
  10782. }
  10783. };
  10784. Engine.prototype.createRenderTargetTexture = function (size, options) {
  10785. var fullOptions = new RenderTargetCreationOptions();
  10786. if (options !== undefined && typeof options === "object") {
  10787. fullOptions.generateMipMaps = options.generateMipMaps;
  10788. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10789. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  10790. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  10791. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  10792. }
  10793. else {
  10794. fullOptions.generateMipMaps = options;
  10795. fullOptions.generateDepthBuffer = true;
  10796. fullOptions.generateStencilBuffer = false;
  10797. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10798. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10799. }
  10800. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10801. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10802. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10803. }
  10804. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10805. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10806. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10807. }
  10808. var gl = this._gl;
  10809. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10810. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10811. var width = size.width || size;
  10812. var height = size.height || size;
  10813. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  10814. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10815. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10816. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10817. }
  10818. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10819. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10820. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10821. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10822. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  10823. // Create the framebuffer
  10824. var framebuffer = gl.createFramebuffer();
  10825. this.bindUnboundFramebuffer(framebuffer);
  10826. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10827. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  10828. if (fullOptions.generateMipMaps) {
  10829. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10830. }
  10831. // Unbind
  10832. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10833. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10834. this.bindUnboundFramebuffer(null);
  10835. texture._framebuffer = framebuffer;
  10836. texture.baseWidth = width;
  10837. texture.baseHeight = height;
  10838. texture.width = width;
  10839. texture.height = height;
  10840. texture.isReady = true;
  10841. texture.samples = 1;
  10842. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  10843. texture.samplingMode = fullOptions.samplingMode;
  10844. texture.type = fullOptions.type;
  10845. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  10846. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  10847. this.resetTextureCache();
  10848. this._internalTexturesCache.push(texture);
  10849. return texture;
  10850. };
  10851. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  10852. var generateMipMaps = false;
  10853. var generateDepthBuffer = true;
  10854. var generateStencilBuffer = false;
  10855. var generateDepthTexture = false;
  10856. var textureCount = 1;
  10857. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  10858. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10859. var types = [], samplingModes = [];
  10860. if (options !== undefined) {
  10861. generateMipMaps = options.generateMipMaps;
  10862. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10863. generateStencilBuffer = options.generateStencilBuffer;
  10864. generateDepthTexture = options.generateDepthTexture;
  10865. textureCount = options.textureCount || 1;
  10866. if (options.types) {
  10867. types = options.types;
  10868. }
  10869. if (options.samplingModes) {
  10870. samplingModes = options.samplingModes;
  10871. }
  10872. }
  10873. var gl = this._gl;
  10874. // Create the framebuffer
  10875. var framebuffer = gl.createFramebuffer();
  10876. this.bindUnboundFramebuffer(framebuffer);
  10877. var width = size.width || size;
  10878. var height = size.height || size;
  10879. var textures = [];
  10880. var attachments = [];
  10881. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  10882. for (var i = 0; i < textureCount; i++) {
  10883. var samplingMode = samplingModes[i] || defaultSamplingMode;
  10884. var type = types[i] || defaultType;
  10885. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10886. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10887. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10888. }
  10889. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10890. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10891. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10892. }
  10893. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10894. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10895. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10896. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10897. }
  10898. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10899. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10900. textures.push(texture);
  10901. attachments.push(attachment);
  10902. gl.activeTexture(gl["TEXTURE" + i]);
  10903. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  10904. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10905. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10906. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10907. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10908. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10909. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10910. if (generateMipMaps) {
  10911. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10912. }
  10913. // Unbind
  10914. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10915. texture._framebuffer = framebuffer;
  10916. texture._depthStencilBuffer = depthStencilBuffer;
  10917. texture.baseWidth = width;
  10918. texture.baseHeight = height;
  10919. texture.width = width;
  10920. texture.height = height;
  10921. texture.isReady = true;
  10922. texture.samples = 1;
  10923. texture.generateMipMaps = generateMipMaps;
  10924. texture.samplingMode = samplingMode;
  10925. texture.type = type;
  10926. texture._generateDepthBuffer = generateDepthBuffer;
  10927. texture._generateStencilBuffer = generateStencilBuffer;
  10928. this._internalTexturesCache.push(texture);
  10929. }
  10930. if (generateDepthTexture && this._caps.depthTextureExtension) {
  10931. // Depth texture
  10932. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10933. gl.activeTexture(gl.TEXTURE0);
  10934. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  10935. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10936. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10937. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10938. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10939. 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);
  10940. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10941. depthTexture._framebuffer = framebuffer;
  10942. depthTexture.baseWidth = width;
  10943. depthTexture.baseHeight = height;
  10944. depthTexture.width = width;
  10945. depthTexture.height = height;
  10946. depthTexture.isReady = true;
  10947. depthTexture.samples = 1;
  10948. depthTexture.generateMipMaps = generateMipMaps;
  10949. depthTexture.samplingMode = gl.NEAREST;
  10950. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10951. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10952. textures.push(depthTexture);
  10953. this._internalTexturesCache.push(depthTexture);
  10954. }
  10955. gl.drawBuffers(attachments);
  10956. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10957. this.bindUnboundFramebuffer(null);
  10958. this.resetTextureCache();
  10959. return textures;
  10960. };
  10961. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10962. if (samples === void 0) { samples = 1; }
  10963. var depthStencilBuffer = null;
  10964. var gl = this._gl;
  10965. // Create the depth/stencil buffer
  10966. if (generateStencilBuffer) {
  10967. depthStencilBuffer = gl.createRenderbuffer();
  10968. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10969. if (samples > 1) {
  10970. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10971. }
  10972. else {
  10973. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10974. }
  10975. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10976. }
  10977. else if (generateDepthBuffer) {
  10978. depthStencilBuffer = gl.createRenderbuffer();
  10979. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10980. if (samples > 1) {
  10981. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10982. }
  10983. else {
  10984. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10985. }
  10986. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10987. }
  10988. return depthStencilBuffer;
  10989. };
  10990. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10991. if (this.webGLVersion < 2 || !texture) {
  10992. return 1;
  10993. }
  10994. if (texture.samples === samples) {
  10995. return samples;
  10996. }
  10997. var gl = this._gl;
  10998. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10999. // Dispose previous render buffers
  11000. if (texture._depthStencilBuffer) {
  11001. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  11002. }
  11003. if (texture._MSAAFramebuffer) {
  11004. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  11005. }
  11006. if (texture._MSAARenderBuffer) {
  11007. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  11008. }
  11009. if (samples > 1) {
  11010. var framebuffer = gl.createFramebuffer();
  11011. if (!framebuffer) {
  11012. throw new Error("Unable to create multi sampled framebuffer");
  11013. }
  11014. texture._MSAAFramebuffer = framebuffer;
  11015. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  11016. var colorRenderbuffer = gl.createRenderbuffer();
  11017. if (!colorRenderbuffer) {
  11018. throw new Error("Unable to create multi sampled framebuffer");
  11019. }
  11020. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  11021. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  11022. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  11023. texture._MSAARenderBuffer = colorRenderbuffer;
  11024. }
  11025. else {
  11026. this.bindUnboundFramebuffer(texture._framebuffer);
  11027. }
  11028. texture.samples = samples;
  11029. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  11030. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11031. this.bindUnboundFramebuffer(null);
  11032. return samples;
  11033. };
  11034. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  11035. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  11036. };
  11037. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  11038. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  11039. };
  11040. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  11041. var gl = this._gl;
  11042. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  11043. var generateMipMaps = true;
  11044. var generateDepthBuffer = true;
  11045. var generateStencilBuffer = false;
  11046. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  11047. if (options !== undefined) {
  11048. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  11049. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  11050. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  11051. if (options.samplingMode !== undefined) {
  11052. samplingMode = options.samplingMode;
  11053. }
  11054. }
  11055. texture.isCube = true;
  11056. texture.generateMipMaps = generateMipMaps;
  11057. texture.samples = 1;
  11058. texture.samplingMode = samplingMode;
  11059. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11060. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11061. for (var face = 0; face < 6; face++) {
  11062. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  11063. }
  11064. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  11065. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  11066. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11067. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11068. // Create the framebuffer
  11069. var framebuffer = gl.createFramebuffer();
  11070. this.bindUnboundFramebuffer(framebuffer);
  11071. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  11072. // Mipmaps
  11073. if (texture.generateMipMaps) {
  11074. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11075. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11076. }
  11077. // Unbind
  11078. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11079. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11080. this.bindUnboundFramebuffer(null);
  11081. texture._framebuffer = framebuffer;
  11082. texture.width = size;
  11083. texture.height = size;
  11084. texture.isReady = true;
  11085. this.resetTextureCache();
  11086. this._internalTexturesCache.push(texture);
  11087. return texture;
  11088. };
  11089. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  11090. var _this = this;
  11091. if (onLoad === void 0) { onLoad = null; }
  11092. if (onError === void 0) { onError = null; }
  11093. if (forcedExtension === void 0) { forcedExtension = null; }
  11094. var callback = function (loadData) {
  11095. if (!loadData) {
  11096. if (onLoad) {
  11097. onLoad(null);
  11098. }
  11099. return;
  11100. }
  11101. var texture = loadData.texture;
  11102. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  11103. texture._lodGenerationScale = scale;
  11104. texture._lodGenerationOffset = offset;
  11105. if (_this._caps.textureLOD) {
  11106. // Do not add extra process if texture lod is supported.
  11107. if (onLoad) {
  11108. onLoad(texture);
  11109. }
  11110. return;
  11111. }
  11112. var mipSlices = 3;
  11113. var gl = _this._gl;
  11114. var width = loadData.width;
  11115. if (!width) {
  11116. return;
  11117. }
  11118. var textures = [];
  11119. for (var i = 0; i < mipSlices; i++) {
  11120. //compute LOD from even spacing in smoothness (matching shader calculation)
  11121. var smoothness = i / (mipSlices - 1);
  11122. var roughness = 1 - smoothness;
  11123. var minLODIndex = offset; // roughness = 0
  11124. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  11125. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  11126. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  11127. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  11128. glTextureFromLod.isCube = true;
  11129. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  11130. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11131. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  11132. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11133. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11134. if (loadData.isDDS) {
  11135. var info = loadData.info;
  11136. var data = loadData.data;
  11137. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  11138. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  11139. }
  11140. else {
  11141. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  11142. }
  11143. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11144. // Wrap in a base texture for easy binding.
  11145. var lodTexture = new BABYLON.BaseTexture(scene);
  11146. lodTexture.isCube = true;
  11147. lodTexture._texture = glTextureFromLod;
  11148. glTextureFromLod.isReady = true;
  11149. textures.push(lodTexture);
  11150. }
  11151. texture._lodTextureHigh = textures[2];
  11152. texture._lodTextureMid = textures[1];
  11153. texture._lodTextureLow = textures[0];
  11154. if (onLoad) {
  11155. onLoad(texture);
  11156. }
  11157. };
  11158. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  11159. };
  11160. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  11161. var _this = this;
  11162. if (onLoad === void 0) { onLoad = null; }
  11163. if (onError === void 0) { onError = null; }
  11164. if (forcedExtension === void 0) { forcedExtension = null; }
  11165. var gl = this._gl;
  11166. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  11167. texture.isCube = true;
  11168. texture.url = rootUrl;
  11169. texture.generateMipMaps = !noMipmap;
  11170. if (!this._doNotHandleContextLost) {
  11171. texture._extension = forcedExtension;
  11172. texture._files = files;
  11173. }
  11174. var isKTX = false;
  11175. var isDDS = false;
  11176. var lastDot = rootUrl.lastIndexOf('.');
  11177. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  11178. if (this._textureFormatInUse) {
  11179. extension = this._textureFormatInUse;
  11180. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  11181. isKTX = true;
  11182. }
  11183. else {
  11184. isDDS = (extension === ".dds");
  11185. }
  11186. var onerror = function (request, exception) {
  11187. if (onError && request) {
  11188. onError(request.status + " " + request.statusText, exception);
  11189. }
  11190. };
  11191. if (isKTX) {
  11192. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  11193. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  11194. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  11195. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11196. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  11197. ktx.uploadLevels(_this._gl, !noMipmap);
  11198. _this.setCubeMapTextureParams(gl, loadMipmap);
  11199. texture.width = ktx.pixelWidth;
  11200. texture.height = ktx.pixelHeight;
  11201. texture.isReady = true;
  11202. }, undefined, undefined, true, onerror);
  11203. }
  11204. else if (isDDS) {
  11205. if (files && files.length === 6) {
  11206. cascadeLoadFiles(rootUrl, scene, function (imgs) {
  11207. var info;
  11208. var loadMipmap = false;
  11209. var width = 0;
  11210. for (var index = 0; index < imgs.length; index++) {
  11211. var data = imgs[index];
  11212. info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  11213. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  11214. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11215. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  11216. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  11217. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  11218. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11219. }
  11220. texture.width = info.width;
  11221. texture.height = info.height;
  11222. texture.type = info.textureType;
  11223. width = info.width;
  11224. }
  11225. _this.setCubeMapTextureParams(gl, loadMipmap);
  11226. texture.isReady = true;
  11227. if (onLoad) {
  11228. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  11229. }
  11230. }, files, onError);
  11231. }
  11232. else {
  11233. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  11234. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  11235. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  11236. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11237. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  11238. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  11239. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  11240. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11241. }
  11242. _this.setCubeMapTextureParams(gl, loadMipmap);
  11243. texture.width = info.width;
  11244. texture.height = info.height;
  11245. texture.isReady = true;
  11246. texture.type = info.textureType;
  11247. if (onLoad) {
  11248. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  11249. }
  11250. }, undefined, undefined, true, onerror);
  11251. }
  11252. }
  11253. else {
  11254. if (!files) {
  11255. throw new Error("Cannot load cubemap because files were not defined");
  11256. }
  11257. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  11258. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  11259. var height = width;
  11260. _this._prepareWorkingCanvas();
  11261. if (!_this._workingCanvas || !_this._workingContext) {
  11262. return;
  11263. }
  11264. _this._workingCanvas.width = width;
  11265. _this._workingCanvas.height = height;
  11266. var faces = [
  11267. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  11268. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  11269. ];
  11270. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11271. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  11272. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  11273. for (var index = 0; index < faces.length; index++) {
  11274. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  11275. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  11276. }
  11277. if (!noMipmap) {
  11278. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11279. }
  11280. _this.setCubeMapTextureParams(gl, !noMipmap);
  11281. texture.width = width;
  11282. texture.height = height;
  11283. texture.isReady = true;
  11284. if (format) {
  11285. texture.format = format;
  11286. }
  11287. texture.onLoadedObservable.notifyObservers(texture);
  11288. texture.onLoadedObservable.clear();
  11289. if (onLoad) {
  11290. onLoad();
  11291. }
  11292. }, files, onError);
  11293. }
  11294. this._internalTexturesCache.push(texture);
  11295. return texture;
  11296. };
  11297. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  11298. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11299. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  11300. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11301. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11302. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11303. this.resetTextureCache();
  11304. };
  11305. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  11306. if (compression === void 0) { compression = null; }
  11307. if (level === void 0) { level = 0; }
  11308. texture._bufferViewArray = data;
  11309. texture.format = format;
  11310. texture.type = type;
  11311. texture.invertY = invertY;
  11312. texture._compression = compression;
  11313. var gl = this._gl;
  11314. var textureType = this._getWebGLTextureType(type);
  11315. var internalFormat = this._getInternalFormat(format);
  11316. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  11317. var needConversion = false;
  11318. if (internalFormat === gl.RGB) {
  11319. internalFormat = gl.RGBA;
  11320. needConversion = true;
  11321. }
  11322. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11323. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11324. if (texture.width % 4 !== 0) {
  11325. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  11326. }
  11327. // Data are known to be in +X +Y +Z -X -Y -Z
  11328. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11329. var faceData = data[faceIndex];
  11330. if (compression) {
  11331. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  11332. }
  11333. else {
  11334. if (needConversion) {
  11335. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  11336. }
  11337. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  11338. }
  11339. }
  11340. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11341. if (isPot && texture.generateMipMaps && level === 0) {
  11342. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11343. }
  11344. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11345. this.resetTextureCache();
  11346. texture.isReady = true;
  11347. };
  11348. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  11349. if (compression === void 0) { compression = null; }
  11350. var gl = this._gl;
  11351. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  11352. texture.isCube = true;
  11353. texture.generateMipMaps = generateMipMaps;
  11354. texture.format = format;
  11355. texture.type = type;
  11356. if (!this._doNotHandleContextLost) {
  11357. texture._bufferViewArray = data;
  11358. }
  11359. var textureType = this._getWebGLTextureType(type);
  11360. var internalFormat = this._getInternalFormat(format);
  11361. if (internalFormat === gl.RGB) {
  11362. internalFormat = gl.RGBA;
  11363. }
  11364. var width = size;
  11365. var height = width;
  11366. texture.width = width;
  11367. texture.height = height;
  11368. // Double check on POT to generate Mips.
  11369. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11370. if (!isPot) {
  11371. generateMipMaps = false;
  11372. }
  11373. // Upload data if needed. The texture won't be ready until then.
  11374. if (data) {
  11375. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  11376. }
  11377. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  11378. // Filters
  11379. if (data && generateMipMaps) {
  11380. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11381. }
  11382. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  11383. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11384. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11385. }
  11386. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  11387. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11388. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11389. }
  11390. else {
  11391. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11392. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  11393. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  11394. }
  11395. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11396. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11397. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11398. return texture;
  11399. };
  11400. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  11401. var _this = this;
  11402. if (onLoad === void 0) { onLoad = null; }
  11403. if (onError === void 0) { onError = null; }
  11404. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11405. if (invertY === void 0) { invertY = false; }
  11406. var gl = this._gl;
  11407. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  11408. scene._addPendingData(texture);
  11409. texture.url = url;
  11410. this._internalTexturesCache.push(texture);
  11411. var onerror = function (request, exception) {
  11412. scene._removePendingData(texture);
  11413. if (onError && request) {
  11414. onError(request.status + " " + request.statusText, exception);
  11415. }
  11416. };
  11417. var internalCallback = function (data) {
  11418. var width = texture.width;
  11419. var faceDataArrays = callback(data);
  11420. if (!faceDataArrays) {
  11421. return;
  11422. }
  11423. if (mipmmapGenerator) {
  11424. var textureType = _this._getWebGLTextureType(type);
  11425. var internalFormat = _this._getInternalFormat(format);
  11426. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  11427. var needConversion = false;
  11428. if (internalFormat === gl.RGB) {
  11429. internalFormat = gl.RGBA;
  11430. needConversion = true;
  11431. }
  11432. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11433. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  11434. var mipData = mipmmapGenerator(faceDataArrays);
  11435. for (var level = 0; level < mipData.length; level++) {
  11436. var mipSize = width >> level;
  11437. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11438. var mipFaceData = mipData[level][faceIndex];
  11439. if (needConversion) {
  11440. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  11441. }
  11442. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  11443. }
  11444. }
  11445. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11446. }
  11447. else {
  11448. texture.generateMipMaps = !noMipmap;
  11449. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  11450. }
  11451. texture.isReady = true;
  11452. _this.resetTextureCache();
  11453. scene._removePendingData(texture);
  11454. if (onLoad) {
  11455. onLoad();
  11456. }
  11457. };
  11458. BABYLON.Tools.LoadFile(url, function (data) {
  11459. internalCallback(data);
  11460. }, undefined, scene.database, true, onerror);
  11461. return texture;
  11462. };
  11463. ;
  11464. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  11465. if (compression === void 0) { compression = null; }
  11466. var internalFormat = this._getInternalFormat(format);
  11467. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11468. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11469. if (!this._doNotHandleContextLost) {
  11470. texture._bufferView = data;
  11471. texture.format = format;
  11472. texture.invertY = invertY;
  11473. texture._compression = compression;
  11474. }
  11475. if (texture.width % 4 !== 0) {
  11476. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  11477. }
  11478. if (compression && data) {
  11479. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  11480. }
  11481. else {
  11482. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  11483. }
  11484. if (texture.generateMipMaps) {
  11485. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11486. }
  11487. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11488. this.resetTextureCache();
  11489. texture.isReady = true;
  11490. };
  11491. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  11492. if (compression === void 0) { compression = null; }
  11493. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  11494. texture.baseWidth = width;
  11495. texture.baseHeight = height;
  11496. texture.baseDepth = depth;
  11497. texture.width = width;
  11498. texture.height = height;
  11499. texture.depth = depth;
  11500. texture.format = format;
  11501. texture.generateMipMaps = generateMipMaps;
  11502. texture.samplingMode = samplingMode;
  11503. texture.is3D = true;
  11504. if (!this._doNotHandleContextLost) {
  11505. texture._bufferView = data;
  11506. }
  11507. this.updateRawTexture3D(texture, data, format, invertY, compression);
  11508. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11509. // Filters
  11510. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  11511. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11512. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11513. if (generateMipMaps) {
  11514. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11515. }
  11516. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11517. this._internalTexturesCache.push(texture);
  11518. return texture;
  11519. };
  11520. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  11521. var gl = this._gl;
  11522. if (!gl) {
  11523. return;
  11524. }
  11525. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  11526. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11527. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11528. if (!noMipmap && !isCompressed) {
  11529. gl.generateMipmap(gl.TEXTURE_2D);
  11530. }
  11531. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11532. this.resetTextureCache();
  11533. if (scene) {
  11534. scene._removePendingData(texture);
  11535. }
  11536. texture.onLoadedObservable.notifyObservers(texture);
  11537. texture.onLoadedObservable.clear();
  11538. };
  11539. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  11540. var _this = this;
  11541. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11542. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  11543. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  11544. var gl = this._gl;
  11545. if (!gl) {
  11546. return;
  11547. }
  11548. if (!texture._webGLTexture) {
  11549. this.resetTextureCache();
  11550. if (scene) {
  11551. scene._removePendingData(texture);
  11552. }
  11553. return;
  11554. }
  11555. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11556. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11557. texture.baseWidth = width;
  11558. texture.baseHeight = height;
  11559. texture.width = potWidth;
  11560. texture.height = potHeight;
  11561. texture.isReady = true;
  11562. if (processFunction(potWidth, potHeight, function () {
  11563. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11564. })) {
  11565. // Returning as texture needs extra async steps
  11566. return;
  11567. }
  11568. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11569. };
  11570. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  11571. // Create new RGBA data container.
  11572. var rgbaData;
  11573. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  11574. rgbaData = new Float32Array(width * height * 4);
  11575. }
  11576. else {
  11577. rgbaData = new Uint32Array(width * height * 4);
  11578. }
  11579. // Convert each pixel.
  11580. for (var x = 0; x < width; x++) {
  11581. for (var y = 0; y < height; y++) {
  11582. var index = (y * width + x) * 3;
  11583. var newIndex = (y * width + x) * 4;
  11584. // Map Old Value to new value.
  11585. rgbaData[newIndex + 0] = rgbData[index + 0];
  11586. rgbaData[newIndex + 1] = rgbData[index + 1];
  11587. rgbaData[newIndex + 2] = rgbData[index + 2];
  11588. // Add fully opaque alpha channel.
  11589. rgbaData[newIndex + 3] = 1;
  11590. }
  11591. }
  11592. return rgbaData;
  11593. };
  11594. Engine.prototype._releaseFramebufferObjects = function (texture) {
  11595. var gl = this._gl;
  11596. if (texture._framebuffer) {
  11597. gl.deleteFramebuffer(texture._framebuffer);
  11598. texture._framebuffer = null;
  11599. }
  11600. if (texture._depthStencilBuffer) {
  11601. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  11602. texture._depthStencilBuffer = null;
  11603. }
  11604. if (texture._MSAAFramebuffer) {
  11605. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  11606. texture._MSAAFramebuffer = null;
  11607. }
  11608. if (texture._MSAARenderBuffer) {
  11609. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  11610. texture._MSAARenderBuffer = null;
  11611. }
  11612. };
  11613. Engine.prototype._releaseTexture = function (texture) {
  11614. var gl = this._gl;
  11615. this._releaseFramebufferObjects(texture);
  11616. gl.deleteTexture(texture._webGLTexture);
  11617. // Unbind channels
  11618. this.unbindAllTextures();
  11619. var index = this._internalTexturesCache.indexOf(texture);
  11620. if (index !== -1) {
  11621. this._internalTexturesCache.splice(index, 1);
  11622. }
  11623. // Integrated fixed lod samplers.
  11624. if (texture._lodTextureHigh) {
  11625. texture._lodTextureHigh.dispose();
  11626. }
  11627. if (texture._lodTextureMid) {
  11628. texture._lodTextureMid.dispose();
  11629. }
  11630. if (texture._lodTextureLow) {
  11631. texture._lodTextureLow.dispose();
  11632. }
  11633. };
  11634. Engine.prototype.setProgram = function (program) {
  11635. if (this._currentProgram !== program) {
  11636. this._gl.useProgram(program);
  11637. this._currentProgram = program;
  11638. }
  11639. };
  11640. Engine.prototype.bindSamplers = function (effect) {
  11641. this.setProgram(effect.getProgram());
  11642. var samplers = effect.getSamplers();
  11643. for (var index = 0; index < samplers.length; index++) {
  11644. var uniform = effect.getUniform(samplers[index]);
  11645. if (uniform) {
  11646. this._boundUniforms[index] = uniform;
  11647. }
  11648. }
  11649. this._currentEffect = null;
  11650. };
  11651. Engine.prototype._activateTextureChannel = function (channel) {
  11652. if (this._activeChannel !== channel) {
  11653. this._gl.activeTexture(this._gl.TEXTURE0 + channel);
  11654. this._activeChannel = channel;
  11655. }
  11656. };
  11657. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  11658. var index = this._boundTexturesOrder.indexOf(internalTexture);
  11659. if (index > -1 && index !== this._boundTexturesOrder.length - 1) {
  11660. this._boundTexturesOrder.splice(index, 1);
  11661. this._boundTexturesOrder.push(internalTexture);
  11662. }
  11663. };
  11664. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  11665. var currentSlot = internalTexture._designatedSlot;
  11666. internalTexture._designatedSlot = -1;
  11667. var index = this._boundTexturesOrder.indexOf(internalTexture);
  11668. if (index > -1) {
  11669. this._boundTexturesOrder.splice(index, 1);
  11670. }
  11671. return currentSlot;
  11672. };
  11673. Engine.prototype._bindTextureDirectly = function (target, texture, isPartOfTextureArray) {
  11674. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  11675. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  11676. var isTextureForRendering = texture && texture._initialSlot > -1;
  11677. if (currentTextureBound !== texture) {
  11678. if (currentTextureBound) {
  11679. this._removeDesignatedSlot(currentTextureBound);
  11680. }
  11681. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  11682. if (this._activeChannel >= 0) {
  11683. this._boundTexturesCache[this._activeChannel] = texture;
  11684. if (isTextureForRendering) {
  11685. this._boundTexturesOrder.push(texture);
  11686. }
  11687. }
  11688. }
  11689. if (isTextureForRendering && this._activeChannel > -1) {
  11690. texture._designatedSlot = this._activeChannel;
  11691. if (!isPartOfTextureArray) {
  11692. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  11693. }
  11694. }
  11695. };
  11696. Engine.prototype._bindTexture = function (channel, texture) {
  11697. if (channel < 0) {
  11698. return;
  11699. }
  11700. if (texture) {
  11701. channel = this._getCorrectTextureChannel(channel, texture);
  11702. }
  11703. this._activateTextureChannel(channel);
  11704. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  11705. };
  11706. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  11707. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  11708. };
  11709. Engine.prototype.unbindAllTextures = function () {
  11710. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  11711. this._activateTextureChannel(channel);
  11712. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11713. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11714. if (this.webGLVersion > 1) {
  11715. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11716. }
  11717. }
  11718. };
  11719. Engine.prototype.setTexture = function (channel, uniform, texture) {
  11720. if (channel < 0) {
  11721. return;
  11722. }
  11723. if (uniform) {
  11724. this._boundUniforms[channel] = uniform;
  11725. }
  11726. this._setTexture(channel, texture);
  11727. };
  11728. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  11729. if (!internalTexture) {
  11730. return -1;
  11731. }
  11732. internalTexture._initialSlot = channel;
  11733. if (channel !== internalTexture._designatedSlot) {
  11734. if (internalTexture._designatedSlot > -1) {
  11735. channel = internalTexture._designatedSlot;
  11736. }
  11737. else {
  11738. if (this._nextFreeTextureSlot > -1) {
  11739. channel = this._nextFreeTextureSlot;
  11740. this._nextFreeTextureSlot++;
  11741. if (this._nextFreeTextureSlot >= this._caps.maxTexturesImageUnits) {
  11742. this._nextFreeTextureSlot = -1; // No more free slots, we will recycle
  11743. }
  11744. }
  11745. else {
  11746. channel = this._removeDesignatedSlot(this._boundTexturesOrder[0]);
  11747. }
  11748. }
  11749. }
  11750. return channel;
  11751. };
  11752. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  11753. var uniform = this._boundUniforms[sourceSlot];
  11754. this._gl.uniform1i(uniform, destination);
  11755. };
  11756. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  11757. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  11758. // Not ready?
  11759. if (!texture) {
  11760. if (this._boundTexturesCache[channel] != null) {
  11761. this._activateTextureChannel(channel);
  11762. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11763. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11764. if (this.webGLVersion > 1) {
  11765. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11766. }
  11767. }
  11768. return false;
  11769. }
  11770. // Video
  11771. var alreadyActivated = false;
  11772. if (texture.video) {
  11773. this._activateTextureChannel(channel);
  11774. alreadyActivated = true;
  11775. texture.update();
  11776. }
  11777. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  11778. texture.delayLoad();
  11779. return false;
  11780. }
  11781. var internalTexture;
  11782. if (texture.isReady()) {
  11783. internalTexture = texture.getInternalTexture();
  11784. }
  11785. else if (texture.isCube) {
  11786. internalTexture = this.emptyCubeTexture;
  11787. }
  11788. else if (texture.is3D) {
  11789. internalTexture = this.emptyTexture3D;
  11790. }
  11791. else {
  11792. internalTexture = this.emptyTexture;
  11793. }
  11794. if (!isPartOfTextureArray) {
  11795. channel = this._getCorrectTextureChannel(channel, internalTexture);
  11796. }
  11797. if (this._boundTexturesCache[channel] === internalTexture) {
  11798. this._moveBoundTextureOnTop(internalTexture);
  11799. if (!isPartOfTextureArray) {
  11800. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  11801. }
  11802. return false;
  11803. }
  11804. if (!alreadyActivated) {
  11805. this._activateTextureChannel(channel);
  11806. }
  11807. if (internalTexture && internalTexture.is3D) {
  11808. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  11809. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11810. internalTexture._cachedWrapU = texture.wrapU;
  11811. switch (texture.wrapU) {
  11812. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11813. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11814. break;
  11815. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11816. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11817. break;
  11818. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11819. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11820. break;
  11821. }
  11822. }
  11823. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11824. internalTexture._cachedWrapV = texture.wrapV;
  11825. switch (texture.wrapV) {
  11826. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11827. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11828. break;
  11829. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11830. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11831. break;
  11832. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11833. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11834. break;
  11835. }
  11836. }
  11837. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  11838. internalTexture._cachedWrapR = texture.wrapR;
  11839. switch (texture.wrapV) {
  11840. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11841. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  11842. break;
  11843. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11844. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  11845. break;
  11846. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11847. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  11848. break;
  11849. }
  11850. }
  11851. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  11852. }
  11853. else if (internalTexture && internalTexture.isCube) {
  11854. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  11855. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  11856. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  11857. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  11858. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  11859. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  11860. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  11861. }
  11862. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  11863. }
  11864. else {
  11865. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  11866. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11867. internalTexture._cachedWrapU = texture.wrapU;
  11868. switch (texture.wrapU) {
  11869. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11870. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11871. break;
  11872. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11873. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11874. break;
  11875. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11876. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11877. break;
  11878. }
  11879. }
  11880. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11881. internalTexture._cachedWrapV = texture.wrapV;
  11882. switch (texture.wrapV) {
  11883. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11884. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11885. break;
  11886. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11887. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11888. break;
  11889. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11890. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11891. break;
  11892. }
  11893. }
  11894. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  11895. }
  11896. return true;
  11897. };
  11898. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  11899. if (channel < 0 || !uniform) {
  11900. return;
  11901. }
  11902. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  11903. this._textureUnits = new Int32Array(textures.length);
  11904. }
  11905. for (var i = 0; i < textures.length; i++) {
  11906. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  11907. }
  11908. this._gl.uniform1iv(uniform, this._textureUnits);
  11909. for (var index = 0; index < textures.length; index++) {
  11910. this._setTexture(this._textureUnits[index], textures[index], true);
  11911. }
  11912. };
  11913. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  11914. var internalTexture = texture.getInternalTexture();
  11915. if (!internalTexture) {
  11916. return;
  11917. }
  11918. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  11919. var value = texture.anisotropicFilteringLevel;
  11920. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  11921. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  11922. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  11923. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  11924. }
  11925. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  11926. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  11927. internalTexture._cachedAnisotropicFilteringLevel = value;
  11928. }
  11929. };
  11930. Engine.prototype.readPixels = function (x, y, width, height) {
  11931. var data = new Uint8Array(height * width * 4);
  11932. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  11933. return data;
  11934. };
  11935. /**
  11936. * Add an externaly attached data from its key.
  11937. * This method call will fail and return false, if such key already exists.
  11938. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  11939. * @param key the unique key that identifies the data
  11940. * @param data the data object to associate to the key for this Engine instance
  11941. * @return true if no such key were already present and the data was added successfully, false otherwise
  11942. */
  11943. Engine.prototype.addExternalData = function (key, data) {
  11944. if (!this._externalData) {
  11945. this._externalData = new BABYLON.StringDictionary();
  11946. }
  11947. return this._externalData.add(key, data);
  11948. };
  11949. /**
  11950. * Get an externaly attached data from its key
  11951. * @param key the unique key that identifies the data
  11952. * @return the associated data, if present (can be null), or undefined if not present
  11953. */
  11954. Engine.prototype.getExternalData = function (key) {
  11955. if (!this._externalData) {
  11956. this._externalData = new BABYLON.StringDictionary();
  11957. }
  11958. return this._externalData.get(key);
  11959. };
  11960. /**
  11961. * Get an externaly attached data from its key, create it using a factory if it's not already present
  11962. * @param key the unique key that identifies the data
  11963. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  11964. * @return the associated data, can be null if the factory returned null.
  11965. */
  11966. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  11967. if (!this._externalData) {
  11968. this._externalData = new BABYLON.StringDictionary();
  11969. }
  11970. return this._externalData.getOrAddWithFactory(key, factory);
  11971. };
  11972. /**
  11973. * Remove an externaly attached data from the Engine instance
  11974. * @param key the unique key that identifies the data
  11975. * @return true if the data was successfully removed, false if it doesn't exist
  11976. */
  11977. Engine.prototype.removeExternalData = function (key) {
  11978. if (!this._externalData) {
  11979. this._externalData = new BABYLON.StringDictionary();
  11980. }
  11981. return this._externalData.remove(key);
  11982. };
  11983. Engine.prototype.unbindAllAttributes = function () {
  11984. if (this._mustWipeVertexAttributes) {
  11985. this._mustWipeVertexAttributes = false;
  11986. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11987. this._gl.disableVertexAttribArray(i);
  11988. this._vertexAttribArraysEnabled[i] = false;
  11989. this._currentBufferPointers[i].active = false;
  11990. }
  11991. return;
  11992. }
  11993. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  11994. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  11995. continue;
  11996. }
  11997. this._gl.disableVertexAttribArray(i);
  11998. this._vertexAttribArraysEnabled[i] = false;
  11999. this._currentBufferPointers[i].active = false;
  12000. }
  12001. };
  12002. Engine.prototype.releaseEffects = function () {
  12003. for (var name in this._compiledEffects) {
  12004. this._deleteProgram(this._compiledEffects[name]._program);
  12005. }
  12006. this._compiledEffects = {};
  12007. };
  12008. // Dispose
  12009. Engine.prototype.dispose = function () {
  12010. this.hideLoadingUI();
  12011. this.stopRenderLoop();
  12012. // Release postProcesses
  12013. while (this.postProcesses.length) {
  12014. this.postProcesses[0].dispose();
  12015. }
  12016. // Empty texture
  12017. if (this._emptyTexture) {
  12018. this._releaseTexture(this._emptyTexture);
  12019. this._emptyTexture = null;
  12020. }
  12021. if (this._emptyCubeTexture) {
  12022. this._releaseTexture(this._emptyCubeTexture);
  12023. this._emptyCubeTexture = null;
  12024. }
  12025. // Rescale PP
  12026. if (this._rescalePostProcess) {
  12027. this._rescalePostProcess.dispose();
  12028. }
  12029. // Release scenes
  12030. while (this.scenes.length) {
  12031. this.scenes[0].dispose();
  12032. }
  12033. // Release audio engine
  12034. if (Engine.audioEngine) {
  12035. Engine.audioEngine.dispose();
  12036. }
  12037. // Release effects
  12038. this.releaseEffects();
  12039. // Unbind
  12040. this.unbindAllAttributes();
  12041. if (this._dummyFramebuffer) {
  12042. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  12043. }
  12044. //WebVR
  12045. this.disableVR();
  12046. // Events
  12047. if (BABYLON.Tools.IsWindowObjectExist()) {
  12048. window.removeEventListener("blur", this._onBlur);
  12049. window.removeEventListener("focus", this._onFocus);
  12050. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  12051. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  12052. if (this._renderingCanvas) {
  12053. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  12054. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  12055. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  12056. if (!this._doNotHandleContextLost) {
  12057. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  12058. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  12059. }
  12060. }
  12061. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  12062. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  12063. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  12064. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  12065. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  12066. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  12067. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  12068. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  12069. if (this._onVrDisplayConnect) {
  12070. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12071. if (this._onVrDisplayDisconnect) {
  12072. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12073. }
  12074. if (this._onVrDisplayPresentChange) {
  12075. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12076. }
  12077. this._onVrDisplayConnect = null;
  12078. this._onVrDisplayDisconnect = null;
  12079. }
  12080. }
  12081. // Remove from Instances
  12082. var index = Engine.Instances.indexOf(this);
  12083. if (index >= 0) {
  12084. Engine.Instances.splice(index, 1);
  12085. }
  12086. this._workingCanvas = null;
  12087. this._workingContext = null;
  12088. this._currentBufferPointers = [];
  12089. this._renderingCanvas = null;
  12090. this._currentProgram = null;
  12091. this.onResizeObservable.clear();
  12092. this.onCanvasBlurObservable.clear();
  12093. this.onCanvasFocusObservable.clear();
  12094. this.onCanvasPointerOutObservable.clear();
  12095. this.onBeginFrameObservable.clear();
  12096. this.onEndFrameObservable.clear();
  12097. BABYLON.Effect.ResetCache();
  12098. };
  12099. // Loading screen
  12100. Engine.prototype.displayLoadingUI = function () {
  12101. if (!BABYLON.Tools.IsWindowObjectExist()) {
  12102. return;
  12103. }
  12104. var loadingScreen = this.loadingScreen;
  12105. if (loadingScreen) {
  12106. loadingScreen.displayLoadingUI();
  12107. }
  12108. };
  12109. Engine.prototype.hideLoadingUI = function () {
  12110. if (!BABYLON.Tools.IsWindowObjectExist()) {
  12111. return;
  12112. }
  12113. var loadingScreen = this.loadingScreen;
  12114. if (loadingScreen) {
  12115. loadingScreen.hideLoadingUI();
  12116. }
  12117. };
  12118. Object.defineProperty(Engine.prototype, "loadingScreen", {
  12119. get: function () {
  12120. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  12121. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  12122. return this._loadingScreen;
  12123. },
  12124. set: function (loadingScreen) {
  12125. this._loadingScreen = loadingScreen;
  12126. },
  12127. enumerable: true,
  12128. configurable: true
  12129. });
  12130. Object.defineProperty(Engine.prototype, "loadingUIText", {
  12131. set: function (text) {
  12132. this.loadingScreen.loadingUIText = text;
  12133. },
  12134. enumerable: true,
  12135. configurable: true
  12136. });
  12137. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  12138. set: function (color) {
  12139. this.loadingScreen.loadingUIBackgroundColor = color;
  12140. },
  12141. enumerable: true,
  12142. configurable: true
  12143. });
  12144. Engine.prototype.attachContextLostEvent = function (callback) {
  12145. if (this._renderingCanvas) {
  12146. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  12147. }
  12148. };
  12149. Engine.prototype.attachContextRestoredEvent = function (callback) {
  12150. if (this._renderingCanvas) {
  12151. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  12152. }
  12153. };
  12154. Engine.prototype.getVertexShaderSource = function (program) {
  12155. var shaders = this._gl.getAttachedShaders(program);
  12156. if (!shaders) {
  12157. return null;
  12158. }
  12159. return this._gl.getShaderSource(shaders[0]);
  12160. };
  12161. Engine.prototype.getFragmentShaderSource = function (program) {
  12162. var shaders = this._gl.getAttachedShaders(program);
  12163. if (!shaders) {
  12164. return null;
  12165. }
  12166. return this._gl.getShaderSource(shaders[1]);
  12167. };
  12168. Engine.prototype.getError = function () {
  12169. return this._gl.getError();
  12170. };
  12171. // FPS
  12172. Engine.prototype.getFps = function () {
  12173. return this._fps;
  12174. };
  12175. Engine.prototype.getDeltaTime = function () {
  12176. return this._deltaTime;
  12177. };
  12178. Engine.prototype._measureFps = function () {
  12179. this._performanceMonitor.sampleFrame();
  12180. this._fps = this._performanceMonitor.averageFPS;
  12181. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  12182. };
  12183. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  12184. if (faceIndex === void 0) { faceIndex = -1; }
  12185. var gl = this._gl;
  12186. if (!this._dummyFramebuffer) {
  12187. var dummy = gl.createFramebuffer();
  12188. if (!dummy) {
  12189. throw new Error("Unable to create dummy framebuffer");
  12190. }
  12191. this._dummyFramebuffer = dummy;
  12192. }
  12193. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  12194. if (faceIndex > -1) {
  12195. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12196. }
  12197. else {
  12198. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  12199. }
  12200. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  12201. var buffer;
  12202. switch (readType) {
  12203. case gl.UNSIGNED_BYTE:
  12204. buffer = new Uint8Array(4 * width * height);
  12205. readType = gl.UNSIGNED_BYTE;
  12206. break;
  12207. default:
  12208. buffer = new Float32Array(4 * width * height);
  12209. readType = gl.FLOAT;
  12210. break;
  12211. }
  12212. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  12213. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  12214. return buffer;
  12215. };
  12216. Engine.prototype._canRenderToFloatFramebuffer = function () {
  12217. if (this._webGLVersion > 1) {
  12218. return this._caps.colorBufferFloat;
  12219. }
  12220. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  12221. };
  12222. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  12223. if (this._webGLVersion > 1) {
  12224. return this._caps.colorBufferFloat;
  12225. }
  12226. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  12227. };
  12228. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  12229. Engine.prototype._canRenderToFramebuffer = function (type) {
  12230. var gl = this._gl;
  12231. //clear existing errors
  12232. while (gl.getError() !== gl.NO_ERROR) { }
  12233. var successful = true;
  12234. var texture = gl.createTexture();
  12235. gl.bindTexture(gl.TEXTURE_2D, texture);
  12236. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  12237. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12238. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12239. var fb = gl.createFramebuffer();
  12240. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  12241. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  12242. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  12243. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  12244. successful = successful && (gl.getError() === gl.NO_ERROR);
  12245. //try render by clearing frame buffer's color buffer
  12246. if (successful) {
  12247. gl.clear(gl.COLOR_BUFFER_BIT);
  12248. successful = successful && (gl.getError() === gl.NO_ERROR);
  12249. }
  12250. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  12251. if (successful) {
  12252. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  12253. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  12254. var readFormat = gl.RGBA;
  12255. var readType = gl.UNSIGNED_BYTE;
  12256. var buffer = new Uint8Array(4);
  12257. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  12258. successful = successful && (gl.getError() === gl.NO_ERROR);
  12259. }
  12260. //clean up
  12261. gl.deleteTexture(texture);
  12262. gl.deleteFramebuffer(fb);
  12263. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  12264. //clear accumulated errors
  12265. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  12266. return successful;
  12267. };
  12268. Engine.prototype._getWebGLTextureType = function (type) {
  12269. if (type === Engine.TEXTURETYPE_FLOAT) {
  12270. return this._gl.FLOAT;
  12271. }
  12272. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  12273. // Add Half Float Constant.
  12274. return this._gl.HALF_FLOAT_OES;
  12275. }
  12276. return this._gl.UNSIGNED_BYTE;
  12277. };
  12278. ;
  12279. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  12280. if (this._webGLVersion === 1) {
  12281. return this._gl.RGBA;
  12282. }
  12283. if (type === Engine.TEXTURETYPE_FLOAT) {
  12284. return this._gl.RGBA32F;
  12285. }
  12286. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  12287. return this._gl.RGBA16F;
  12288. }
  12289. return this._gl.RGBA;
  12290. };
  12291. ;
  12292. Engine.prototype.createQuery = function () {
  12293. return this._gl.createQuery();
  12294. };
  12295. Engine.prototype.deleteQuery = function (query) {
  12296. this._gl.deleteQuery(query);
  12297. return this;
  12298. };
  12299. Engine.prototype.isQueryResultAvailable = function (query) {
  12300. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  12301. };
  12302. Engine.prototype.getQueryResult = function (query) {
  12303. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  12304. };
  12305. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  12306. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  12307. this._gl.beginQuery(glAlgorithm, query);
  12308. return this;
  12309. };
  12310. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  12311. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  12312. this._gl.endQuery(glAlgorithm);
  12313. return this;
  12314. };
  12315. /* Time queries */
  12316. Engine.prototype._createTimeQuery = function () {
  12317. var timerQuery = this._caps.timerQuery;
  12318. if (timerQuery.createQueryEXT) {
  12319. return timerQuery.createQueryEXT();
  12320. }
  12321. return this.createQuery();
  12322. };
  12323. Engine.prototype._deleteTimeQuery = function (query) {
  12324. var timerQuery = this._caps.timerQuery;
  12325. if (timerQuery.deleteQueryEXT) {
  12326. timerQuery.deleteQueryEXT(query);
  12327. return;
  12328. }
  12329. this.deleteQuery(query);
  12330. };
  12331. Engine.prototype._getTimeQueryResult = function (query) {
  12332. var timerQuery = this._caps.timerQuery;
  12333. if (timerQuery.getQueryObjectEXT) {
  12334. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  12335. }
  12336. return this.getQueryResult(query);
  12337. };
  12338. Engine.prototype._getTimeQueryAvailability = function (query) {
  12339. var timerQuery = this._caps.timerQuery;
  12340. if (timerQuery.getQueryObjectEXT) {
  12341. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  12342. }
  12343. return this.isQueryResultAvailable(query);
  12344. };
  12345. Engine.prototype.startTimeQuery = function () {
  12346. var timerQuery = this._caps.timerQuery;
  12347. if (!timerQuery) {
  12348. return null;
  12349. }
  12350. var token = new BABYLON._TimeToken();
  12351. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  12352. if (this._caps.canUseTimestampForTimerQuery) {
  12353. token._startTimeQuery = this._createTimeQuery();
  12354. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  12355. }
  12356. else {
  12357. if (this._currentNonTimestampToken) {
  12358. return this._currentNonTimestampToken;
  12359. }
  12360. token._timeElapsedQuery = this._createTimeQuery();
  12361. if (timerQuery.beginQueryEXT) {
  12362. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  12363. }
  12364. else {
  12365. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  12366. }
  12367. this._currentNonTimestampToken = token;
  12368. }
  12369. return token;
  12370. };
  12371. Engine.prototype.endTimeQuery = function (token) {
  12372. var timerQuery = this._caps.timerQuery;
  12373. if (!timerQuery || !token) {
  12374. return -1;
  12375. }
  12376. if (this._caps.canUseTimestampForTimerQuery) {
  12377. if (!token._startTimeQuery) {
  12378. return -1;
  12379. }
  12380. if (!token._endTimeQuery) {
  12381. token._endTimeQuery = this._createTimeQuery();
  12382. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  12383. }
  12384. }
  12385. else if (!token._timeElapsedQueryEnded) {
  12386. if (!token._timeElapsedQuery) {
  12387. return -1;
  12388. }
  12389. if (timerQuery.endQueryEXT) {
  12390. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  12391. }
  12392. else {
  12393. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  12394. }
  12395. token._timeElapsedQueryEnded = true;
  12396. }
  12397. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  12398. var available = false;
  12399. if (token._endTimeQuery) {
  12400. available = this._getTimeQueryAvailability(token._endTimeQuery);
  12401. }
  12402. else if (token._timeElapsedQuery) {
  12403. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  12404. }
  12405. if (available && !disjoint) {
  12406. var result = 0;
  12407. if (this._caps.canUseTimestampForTimerQuery) {
  12408. if (!token._startTimeQuery || !token._endTimeQuery) {
  12409. return -1;
  12410. }
  12411. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  12412. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  12413. result = timeEnd - timeStart;
  12414. this._deleteTimeQuery(token._startTimeQuery);
  12415. this._deleteTimeQuery(token._endTimeQuery);
  12416. token._startTimeQuery = null;
  12417. token._endTimeQuery = null;
  12418. }
  12419. else {
  12420. if (!token._timeElapsedQuery) {
  12421. return -1;
  12422. }
  12423. result = this._getTimeQueryResult(token._timeElapsedQuery);
  12424. this._deleteTimeQuery(token._timeElapsedQuery);
  12425. token._timeElapsedQuery = null;
  12426. token._timeElapsedQueryEnded = false;
  12427. this._currentNonTimestampToken = null;
  12428. }
  12429. return result;
  12430. }
  12431. return -1;
  12432. };
  12433. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  12434. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  12435. };
  12436. // Transform feedback
  12437. Engine.prototype.createTransformFeedback = function () {
  12438. return this._gl.createTransformFeedback();
  12439. };
  12440. Engine.prototype.deleteTransformFeedback = function (value) {
  12441. this._gl.deleteTransformFeedback(value);
  12442. };
  12443. Engine.prototype.bindTransformFeedback = function (value) {
  12444. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  12445. };
  12446. Engine.prototype.beginTransformFeedback = function (usePoints) {
  12447. if (usePoints === void 0) { usePoints = true; }
  12448. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  12449. };
  12450. Engine.prototype.endTransformFeedback = function () {
  12451. this._gl.endTransformFeedback();
  12452. };
  12453. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  12454. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  12455. };
  12456. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  12457. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  12458. };
  12459. // Statics
  12460. Engine.isSupported = function () {
  12461. try {
  12462. var tempcanvas = document.createElement("canvas");
  12463. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  12464. return gl != null && !!window.WebGLRenderingContext;
  12465. }
  12466. catch (e) {
  12467. return false;
  12468. }
  12469. };
  12470. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  12471. Engine.WebGL2UniformBuffersExceptionList = ["Chrome/63"];
  12472. Engine.Instances = new Array();
  12473. // Const statics
  12474. Engine._ALPHA_DISABLE = 0;
  12475. Engine._ALPHA_ADD = 1;
  12476. Engine._ALPHA_COMBINE = 2;
  12477. Engine._ALPHA_SUBTRACT = 3;
  12478. Engine._ALPHA_MULTIPLY = 4;
  12479. Engine._ALPHA_MAXIMIZED = 5;
  12480. Engine._ALPHA_ONEONE = 6;
  12481. Engine._ALPHA_PREMULTIPLIED = 7;
  12482. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  12483. Engine._ALPHA_INTERPOLATE = 9;
  12484. Engine._ALPHA_SCREENMODE = 10;
  12485. Engine._DELAYLOADSTATE_NONE = 0;
  12486. Engine._DELAYLOADSTATE_LOADED = 1;
  12487. Engine._DELAYLOADSTATE_LOADING = 2;
  12488. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  12489. Engine._TEXTUREFORMAT_ALPHA = 0;
  12490. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  12491. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  12492. Engine._TEXTUREFORMAT_RGB = 4;
  12493. Engine._TEXTUREFORMAT_RGBA = 5;
  12494. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  12495. Engine._TEXTURETYPE_FLOAT = 1;
  12496. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  12497. // Depht or Stencil test Constants.
  12498. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  12499. 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.
  12500. 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.
  12501. 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.
  12502. 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.
  12503. 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.
  12504. 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.
  12505. 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.
  12506. // Stencil Actions Constants.
  12507. Engine._KEEP = 0x1E00;
  12508. Engine._REPLACE = 0x1E01;
  12509. Engine._INCR = 0x1E02;
  12510. Engine._DECR = 0x1E03;
  12511. Engine._INVERT = 0x150A;
  12512. Engine._INCR_WRAP = 0x8507;
  12513. Engine._DECR_WRAP = 0x8508;
  12514. // Texture rescaling mode
  12515. Engine._SCALEMODE_FLOOR = 1;
  12516. Engine._SCALEMODE_NEAREST = 2;
  12517. Engine._SCALEMODE_CEILING = 3;
  12518. // Updatable statics so stick with vars here
  12519. Engine.CollisionsEpsilon = 0.001;
  12520. Engine.CodeRepository = "src/";
  12521. Engine.ShadersRepository = "src/Shaders/";
  12522. return Engine;
  12523. }());
  12524. BABYLON.Engine = Engine;
  12525. })(BABYLON || (BABYLON = {}));
  12526. //# sourceMappingURL=babylon.engine.js.map
  12527. var BABYLON;
  12528. (function (BABYLON) {
  12529. /**
  12530. * Node is the basic class for all scene objects (Mesh, Light Camera).
  12531. */
  12532. var Node = /** @class */ (function () {
  12533. /**
  12534. * @constructor
  12535. * @param {string} name - the name and id to be given to this node
  12536. * @param {BABYLON.Scene} the scene this node will be added to
  12537. */
  12538. function Node(name, scene) {
  12539. if (scene === void 0) { scene = null; }
  12540. this.state = "";
  12541. this.metadata = null;
  12542. this.doNotSerialize = false;
  12543. this.animations = new Array();
  12544. this._ranges = {};
  12545. this._isEnabled = true;
  12546. this._isReady = true;
  12547. this._currentRenderId = -1;
  12548. this._parentRenderId = -1;
  12549. /**
  12550. * An event triggered when the mesh is disposed.
  12551. * @type {BABYLON.Observable}
  12552. */
  12553. this.onDisposeObservable = new BABYLON.Observable();
  12554. // Behaviors
  12555. this._behaviors = new Array();
  12556. this.name = name;
  12557. this.id = name;
  12558. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  12559. this.uniqueId = this._scene.getUniqueId();
  12560. this._initCache();
  12561. }
  12562. Object.defineProperty(Node.prototype, "parent", {
  12563. get: function () {
  12564. return this._parentNode;
  12565. },
  12566. set: function (parent) {
  12567. if (this._parentNode === parent) {
  12568. return;
  12569. }
  12570. if (this._parentNode) {
  12571. var index = this._parentNode._children.indexOf(this);
  12572. if (index !== -1) {
  12573. this._parentNode._children.splice(index, 1);
  12574. }
  12575. }
  12576. this._parentNode = parent;
  12577. if (this._parentNode) {
  12578. if (!this._parentNode._children) {
  12579. this._parentNode._children = new Array();
  12580. }
  12581. this._parentNode._children.push(this);
  12582. }
  12583. },
  12584. enumerable: true,
  12585. configurable: true
  12586. });
  12587. Node.prototype.getClassName = function () {
  12588. return "Node";
  12589. };
  12590. Object.defineProperty(Node.prototype, "onDispose", {
  12591. set: function (callback) {
  12592. if (this._onDisposeObserver) {
  12593. this.onDisposeObservable.remove(this._onDisposeObserver);
  12594. }
  12595. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  12596. },
  12597. enumerable: true,
  12598. configurable: true
  12599. });
  12600. Node.prototype.getScene = function () {
  12601. return this._scene;
  12602. };
  12603. Node.prototype.getEngine = function () {
  12604. return this._scene.getEngine();
  12605. };
  12606. Node.prototype.addBehavior = function (behavior) {
  12607. var _this = this;
  12608. var index = this._behaviors.indexOf(behavior);
  12609. if (index !== -1) {
  12610. return this;
  12611. }
  12612. behavior.init();
  12613. if (this._scene.isLoading) {
  12614. // We defer the attach when the scene will be loaded
  12615. var observer = this._scene.onDataLoadedObservable.add(function () {
  12616. behavior.attach(_this);
  12617. setTimeout(function () {
  12618. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  12619. _this._scene.onDataLoadedObservable.remove(observer);
  12620. }, 0);
  12621. });
  12622. }
  12623. else {
  12624. behavior.attach(this);
  12625. }
  12626. this._behaviors.push(behavior);
  12627. return this;
  12628. };
  12629. Node.prototype.removeBehavior = function (behavior) {
  12630. var index = this._behaviors.indexOf(behavior);
  12631. if (index === -1) {
  12632. return this;
  12633. }
  12634. this._behaviors[index].detach();
  12635. this._behaviors.splice(index, 1);
  12636. return this;
  12637. };
  12638. Object.defineProperty(Node.prototype, "behaviors", {
  12639. get: function () {
  12640. return this._behaviors;
  12641. },
  12642. enumerable: true,
  12643. configurable: true
  12644. });
  12645. Node.prototype.getBehaviorByName = function (name) {
  12646. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12647. var behavior = _a[_i];
  12648. if (behavior.name === name) {
  12649. return behavior;
  12650. }
  12651. }
  12652. return null;
  12653. };
  12654. // override it in derived class
  12655. Node.prototype.getWorldMatrix = function () {
  12656. return BABYLON.Matrix.Identity();
  12657. };
  12658. // override it in derived class if you add new variables to the cache
  12659. // and call the parent class method
  12660. Node.prototype._initCache = function () {
  12661. this._cache = {};
  12662. this._cache.parent = undefined;
  12663. };
  12664. Node.prototype.updateCache = function (force) {
  12665. if (!force && this.isSynchronized())
  12666. return;
  12667. this._cache.parent = this.parent;
  12668. this._updateCache();
  12669. };
  12670. // override it in derived class if you add new variables to the cache
  12671. // and call the parent class method if !ignoreParentClass
  12672. Node.prototype._updateCache = function (ignoreParentClass) {
  12673. };
  12674. // override it in derived class if you add new variables to the cache
  12675. Node.prototype._isSynchronized = function () {
  12676. return true;
  12677. };
  12678. Node.prototype._markSyncedWithParent = function () {
  12679. if (this.parent) {
  12680. this._parentRenderId = this.parent._currentRenderId;
  12681. }
  12682. };
  12683. Node.prototype.isSynchronizedWithParent = function () {
  12684. if (!this.parent) {
  12685. return true;
  12686. }
  12687. if (this._parentRenderId !== this.parent._currentRenderId) {
  12688. return false;
  12689. }
  12690. return this.parent.isSynchronized();
  12691. };
  12692. Node.prototype.isSynchronized = function (updateCache) {
  12693. var check = this.hasNewParent();
  12694. check = check || !this.isSynchronizedWithParent();
  12695. check = check || !this._isSynchronized();
  12696. if (updateCache)
  12697. this.updateCache(true);
  12698. return !check;
  12699. };
  12700. Node.prototype.hasNewParent = function (update) {
  12701. if (this._cache.parent === this.parent)
  12702. return false;
  12703. if (update)
  12704. this._cache.parent = this.parent;
  12705. return true;
  12706. };
  12707. /**
  12708. * Is this node ready to be used/rendered
  12709. * @return {boolean} is it ready
  12710. */
  12711. Node.prototype.isReady = function () {
  12712. return this._isReady;
  12713. };
  12714. /**
  12715. * Is this node enabled.
  12716. * If the node has a parent and is enabled, the parent will be inspected as well.
  12717. * @return {boolean} whether this node (and its parent) is enabled.
  12718. * @see setEnabled
  12719. */
  12720. Node.prototype.isEnabled = function () {
  12721. if (!this._isEnabled) {
  12722. return false;
  12723. }
  12724. if (this.parent) {
  12725. return this.parent.isEnabled();
  12726. }
  12727. return true;
  12728. };
  12729. /**
  12730. * Set the enabled state of this node.
  12731. * @param {boolean} value - the new enabled state
  12732. * @see isEnabled
  12733. */
  12734. Node.prototype.setEnabled = function (value) {
  12735. this._isEnabled = value;
  12736. };
  12737. /**
  12738. * Is this node a descendant of the given node.
  12739. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  12740. * @param {BABYLON.Node} ancestor - The parent node to inspect
  12741. * @see parent
  12742. */
  12743. Node.prototype.isDescendantOf = function (ancestor) {
  12744. if (this.parent) {
  12745. if (this.parent === ancestor) {
  12746. return true;
  12747. }
  12748. return this.parent.isDescendantOf(ancestor);
  12749. }
  12750. return false;
  12751. };
  12752. /**
  12753. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  12754. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  12755. * @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.
  12756. * @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.
  12757. */
  12758. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  12759. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  12760. if (!this._children) {
  12761. return;
  12762. }
  12763. for (var index = 0; index < this._children.length; index++) {
  12764. var item = this._children[index];
  12765. if (!predicate || predicate(item)) {
  12766. results.push(item);
  12767. }
  12768. if (!directDescendantsOnly) {
  12769. item._getDescendants(results, false, predicate);
  12770. }
  12771. }
  12772. };
  12773. /**
  12774. * Will return all nodes that have this node as ascendant.
  12775. * @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.
  12776. * @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.
  12777. * @return {BABYLON.Node[]} all children nodes of all types.
  12778. */
  12779. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  12780. var results = new Array();
  12781. this._getDescendants(results, directDescendantsOnly, predicate);
  12782. return results;
  12783. };
  12784. /**
  12785. * Get all child-meshes of this node.
  12786. */
  12787. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  12788. var results = [];
  12789. this._getDescendants(results, directDescendantsOnly, function (node) {
  12790. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  12791. });
  12792. return results;
  12793. };
  12794. /**
  12795. * Get all child-transformNodes of this node.
  12796. */
  12797. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  12798. var results = [];
  12799. this._getDescendants(results, directDescendantsOnly, function (node) {
  12800. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  12801. });
  12802. return results;
  12803. };
  12804. /**
  12805. * Get all direct children of this node.
  12806. */
  12807. Node.prototype.getChildren = function (predicate) {
  12808. return this.getDescendants(true, predicate);
  12809. };
  12810. Node.prototype._setReady = function (state) {
  12811. if (state === this._isReady) {
  12812. return;
  12813. }
  12814. if (!state) {
  12815. this._isReady = false;
  12816. return;
  12817. }
  12818. this._isReady = true;
  12819. if (this.onReady) {
  12820. this.onReady(this);
  12821. }
  12822. };
  12823. Node.prototype.getAnimationByName = function (name) {
  12824. for (var i = 0; i < this.animations.length; i++) {
  12825. var animation = this.animations[i];
  12826. if (animation.name === name) {
  12827. return animation;
  12828. }
  12829. }
  12830. return null;
  12831. };
  12832. Node.prototype.createAnimationRange = function (name, from, to) {
  12833. // check name not already in use
  12834. if (!this._ranges[name]) {
  12835. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  12836. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12837. if (this.animations[i]) {
  12838. this.animations[i].createRange(name, from, to);
  12839. }
  12840. }
  12841. }
  12842. };
  12843. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  12844. if (deleteFrames === void 0) { deleteFrames = true; }
  12845. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12846. if (this.animations[i]) {
  12847. this.animations[i].deleteRange(name, deleteFrames);
  12848. }
  12849. }
  12850. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  12851. };
  12852. Node.prototype.getAnimationRange = function (name) {
  12853. return this._ranges[name];
  12854. };
  12855. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  12856. var range = this.getAnimationRange(name);
  12857. if (!range) {
  12858. return;
  12859. }
  12860. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  12861. };
  12862. Node.prototype.serializeAnimationRanges = function () {
  12863. var serializationRanges = [];
  12864. for (var name in this._ranges) {
  12865. var localRange = this._ranges[name];
  12866. if (!localRange) {
  12867. continue;
  12868. }
  12869. var range = {};
  12870. range.name = name;
  12871. range.from = localRange.from;
  12872. range.to = localRange.to;
  12873. serializationRanges.push(range);
  12874. }
  12875. return serializationRanges;
  12876. };
  12877. // override it in derived class
  12878. Node.prototype.computeWorldMatrix = function (force) {
  12879. return BABYLON.Matrix.Identity();
  12880. };
  12881. Node.prototype.dispose = function () {
  12882. this.parent = null;
  12883. // Callback
  12884. this.onDisposeObservable.notifyObservers(this);
  12885. this.onDisposeObservable.clear();
  12886. // Behaviors
  12887. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12888. var behavior = _a[_i];
  12889. behavior.detach();
  12890. }
  12891. this._behaviors = [];
  12892. };
  12893. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  12894. if (parsedNode.ranges) {
  12895. for (var index = 0; index < parsedNode.ranges.length; index++) {
  12896. var data = parsedNode.ranges[index];
  12897. node.createAnimationRange(data.name, data.from, data.to);
  12898. }
  12899. }
  12900. };
  12901. __decorate([
  12902. BABYLON.serialize()
  12903. ], Node.prototype, "name", void 0);
  12904. __decorate([
  12905. BABYLON.serialize()
  12906. ], Node.prototype, "id", void 0);
  12907. __decorate([
  12908. BABYLON.serialize()
  12909. ], Node.prototype, "uniqueId", void 0);
  12910. __decorate([
  12911. BABYLON.serialize()
  12912. ], Node.prototype, "state", void 0);
  12913. __decorate([
  12914. BABYLON.serialize()
  12915. ], Node.prototype, "metadata", void 0);
  12916. return Node;
  12917. }());
  12918. BABYLON.Node = Node;
  12919. })(BABYLON || (BABYLON = {}));
  12920. //# sourceMappingURL=babylon.node.js.map
  12921. var BABYLON;
  12922. (function (BABYLON) {
  12923. var BoundingSphere = /** @class */ (function () {
  12924. function BoundingSphere(minimum, maximum) {
  12925. this.minimum = minimum;
  12926. this.maximum = maximum;
  12927. this._tempRadiusVector = BABYLON.Vector3.Zero();
  12928. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  12929. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  12930. this.radius = distance * 0.5;
  12931. this.centerWorld = BABYLON.Vector3.Zero();
  12932. this._update(BABYLON.Matrix.Identity());
  12933. }
  12934. // Methods
  12935. BoundingSphere.prototype._update = function (world) {
  12936. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  12937. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  12938. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  12939. };
  12940. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  12941. for (var i = 0; i < 6; i++) {
  12942. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  12943. return false;
  12944. }
  12945. return true;
  12946. };
  12947. BoundingSphere.prototype.intersectsPoint = function (point) {
  12948. var x = this.centerWorld.x - point.x;
  12949. var y = this.centerWorld.y - point.y;
  12950. var z = this.centerWorld.z - point.z;
  12951. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12952. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  12953. return false;
  12954. return true;
  12955. };
  12956. // Statics
  12957. BoundingSphere.Intersects = function (sphere0, sphere1) {
  12958. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  12959. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  12960. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  12961. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12962. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  12963. return false;
  12964. return true;
  12965. };
  12966. return BoundingSphere;
  12967. }());
  12968. BABYLON.BoundingSphere = BoundingSphere;
  12969. })(BABYLON || (BABYLON = {}));
  12970. //# sourceMappingURL=babylon.boundingSphere.js.map
  12971. var BABYLON;
  12972. (function (BABYLON) {
  12973. var BoundingBox = /** @class */ (function () {
  12974. function BoundingBox(minimum, maximum) {
  12975. this.minimum = minimum;
  12976. this.maximum = maximum;
  12977. this.vectors = new Array();
  12978. this.vectorsWorld = new Array();
  12979. // Bounding vectors
  12980. this.vectors.push(this.minimum.clone());
  12981. this.vectors.push(this.maximum.clone());
  12982. this.vectors.push(this.minimum.clone());
  12983. this.vectors[2].x = this.maximum.x;
  12984. this.vectors.push(this.minimum.clone());
  12985. this.vectors[3].y = this.maximum.y;
  12986. this.vectors.push(this.minimum.clone());
  12987. this.vectors[4].z = this.maximum.z;
  12988. this.vectors.push(this.maximum.clone());
  12989. this.vectors[5].z = this.minimum.z;
  12990. this.vectors.push(this.maximum.clone());
  12991. this.vectors[6].x = this.minimum.x;
  12992. this.vectors.push(this.maximum.clone());
  12993. this.vectors[7].y = this.minimum.y;
  12994. // OBB
  12995. this.center = this.maximum.add(this.minimum).scale(0.5);
  12996. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  12997. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  12998. // World
  12999. for (var index = 0; index < this.vectors.length; index++) {
  13000. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  13001. }
  13002. this.minimumWorld = BABYLON.Vector3.Zero();
  13003. this.maximumWorld = BABYLON.Vector3.Zero();
  13004. this.centerWorld = BABYLON.Vector3.Zero();
  13005. this.extendSizeWorld = BABYLON.Vector3.Zero();
  13006. this._update(BABYLON.Matrix.Identity());
  13007. }
  13008. // Methods
  13009. BoundingBox.prototype.getWorldMatrix = function () {
  13010. return this._worldMatrix;
  13011. };
  13012. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  13013. this._worldMatrix.copyFrom(matrix);
  13014. return this;
  13015. };
  13016. BoundingBox.prototype._update = function (world) {
  13017. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  13018. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  13019. for (var index = 0; index < this.vectors.length; index++) {
  13020. var v = this.vectorsWorld[index];
  13021. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  13022. if (v.x < this.minimumWorld.x)
  13023. this.minimumWorld.x = v.x;
  13024. if (v.y < this.minimumWorld.y)
  13025. this.minimumWorld.y = v.y;
  13026. if (v.z < this.minimumWorld.z)
  13027. this.minimumWorld.z = v.z;
  13028. if (v.x > this.maximumWorld.x)
  13029. this.maximumWorld.x = v.x;
  13030. if (v.y > this.maximumWorld.y)
  13031. this.maximumWorld.y = v.y;
  13032. if (v.z > this.maximumWorld.z)
  13033. this.maximumWorld.z = v.z;
  13034. }
  13035. // Extend
  13036. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  13037. this.extendSizeWorld.scaleInPlace(0.5);
  13038. // OBB
  13039. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  13040. this.centerWorld.scaleInPlace(0.5);
  13041. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  13042. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  13043. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  13044. this._worldMatrix = world;
  13045. };
  13046. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  13047. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  13048. };
  13049. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13050. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  13051. };
  13052. BoundingBox.prototype.intersectsPoint = function (point) {
  13053. var delta = -BABYLON.Epsilon;
  13054. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  13055. return false;
  13056. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  13057. return false;
  13058. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  13059. return false;
  13060. return true;
  13061. };
  13062. BoundingBox.prototype.intersectsSphere = function (sphere) {
  13063. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  13064. };
  13065. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  13066. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  13067. return false;
  13068. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  13069. return false;
  13070. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  13071. return false;
  13072. return true;
  13073. };
  13074. // Statics
  13075. BoundingBox.Intersects = function (box0, box1) {
  13076. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  13077. return false;
  13078. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  13079. return false;
  13080. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  13081. return false;
  13082. return true;
  13083. };
  13084. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  13085. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  13086. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  13087. return (num <= (sphereRadius * sphereRadius));
  13088. };
  13089. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  13090. for (var p = 0; p < 6; p++) {
  13091. for (var i = 0; i < 8; i++) {
  13092. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  13093. return false;
  13094. }
  13095. }
  13096. }
  13097. return true;
  13098. };
  13099. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  13100. for (var p = 0; p < 6; p++) {
  13101. var inCount = 8;
  13102. for (var i = 0; i < 8; i++) {
  13103. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  13104. --inCount;
  13105. }
  13106. else {
  13107. break;
  13108. }
  13109. }
  13110. if (inCount === 0)
  13111. return false;
  13112. }
  13113. return true;
  13114. };
  13115. return BoundingBox;
  13116. }());
  13117. BABYLON.BoundingBox = BoundingBox;
  13118. })(BABYLON || (BABYLON = {}));
  13119. //# sourceMappingURL=babylon.boundingBox.js.map
  13120. var BABYLON;
  13121. (function (BABYLON) {
  13122. var computeBoxExtents = function (axis, box) {
  13123. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  13124. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  13125. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  13126. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  13127. var r = r0 + r1 + r2;
  13128. return {
  13129. min: p - r,
  13130. max: p + r
  13131. };
  13132. };
  13133. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  13134. var axisOverlap = function (axis, box0, box1) {
  13135. var result0 = computeBoxExtents(axis, box0);
  13136. var result1 = computeBoxExtents(axis, box1);
  13137. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  13138. };
  13139. var BoundingInfo = /** @class */ (function () {
  13140. function BoundingInfo(minimum, maximum) {
  13141. this.minimum = minimum;
  13142. this.maximum = maximum;
  13143. this._isLocked = false;
  13144. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  13145. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  13146. }
  13147. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  13148. get: function () {
  13149. return this._isLocked;
  13150. },
  13151. set: function (value) {
  13152. this._isLocked = value;
  13153. },
  13154. enumerable: true,
  13155. configurable: true
  13156. });
  13157. // Methods
  13158. BoundingInfo.prototype.update = function (world) {
  13159. if (this._isLocked) {
  13160. return;
  13161. }
  13162. this.boundingBox._update(world);
  13163. this.boundingSphere._update(world);
  13164. };
  13165. /**
  13166. * Recreate the bounding info to be centered around a specific point given a specific extend.
  13167. * @param center New center of the bounding info
  13168. * @param extend New extend of the bounding info
  13169. */
  13170. BoundingInfo.prototype.centerOn = function (center, extend) {
  13171. this.minimum = center.subtract(extend);
  13172. this.maximum = center.add(extend);
  13173. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  13174. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  13175. return this;
  13176. };
  13177. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  13178. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  13179. return false;
  13180. return this.boundingBox.isInFrustum(frustumPlanes);
  13181. };
  13182. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  13183. /**
  13184. * Gets the world distance between the min and max points of the bounding box
  13185. */
  13186. get: function () {
  13187. var boundingBox = this.boundingBox;
  13188. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  13189. return size.length();
  13190. },
  13191. enumerable: true,
  13192. configurable: true
  13193. });
  13194. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13195. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  13196. };
  13197. BoundingInfo.prototype._checkCollision = function (collider) {
  13198. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  13199. };
  13200. BoundingInfo.prototype.intersectsPoint = function (point) {
  13201. if (!this.boundingSphere.centerWorld) {
  13202. return false;
  13203. }
  13204. if (!this.boundingSphere.intersectsPoint(point)) {
  13205. return false;
  13206. }
  13207. if (!this.boundingBox.intersectsPoint(point)) {
  13208. return false;
  13209. }
  13210. return true;
  13211. };
  13212. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  13213. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  13214. return false;
  13215. }
  13216. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  13217. return false;
  13218. }
  13219. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  13220. return false;
  13221. }
  13222. if (!precise) {
  13223. return true;
  13224. }
  13225. var box0 = this.boundingBox;
  13226. var box1 = boundingInfo.boundingBox;
  13227. if (!axisOverlap(box0.directions[0], box0, box1))
  13228. return false;
  13229. if (!axisOverlap(box0.directions[1], box0, box1))
  13230. return false;
  13231. if (!axisOverlap(box0.directions[2], box0, box1))
  13232. return false;
  13233. if (!axisOverlap(box1.directions[0], box0, box1))
  13234. return false;
  13235. if (!axisOverlap(box1.directions[1], box0, box1))
  13236. return false;
  13237. if (!axisOverlap(box1.directions[2], box0, box1))
  13238. return false;
  13239. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  13240. return false;
  13241. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  13242. return false;
  13243. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  13244. return false;
  13245. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  13246. return false;
  13247. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  13248. return false;
  13249. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  13250. return false;
  13251. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  13252. return false;
  13253. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  13254. return false;
  13255. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  13256. return false;
  13257. return true;
  13258. };
  13259. return BoundingInfo;
  13260. }());
  13261. BABYLON.BoundingInfo = BoundingInfo;
  13262. })(BABYLON || (BABYLON = {}));
  13263. //# sourceMappingURL=babylon.boundingInfo.js.map
  13264. var BABYLON;
  13265. (function (BABYLON) {
  13266. var TransformNode = /** @class */ (function (_super) {
  13267. __extends(TransformNode, _super);
  13268. function TransformNode(name, scene, isPure) {
  13269. if (scene === void 0) { scene = null; }
  13270. if (isPure === void 0) { isPure = true; }
  13271. var _this = _super.call(this, name, scene) || this;
  13272. // Properties
  13273. _this._rotation = BABYLON.Vector3.Zero();
  13274. _this._scaling = BABYLON.Vector3.One();
  13275. _this._isDirty = false;
  13276. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  13277. _this.scalingDeterminant = 1;
  13278. _this.infiniteDistance = false;
  13279. _this.position = BABYLON.Vector3.Zero();
  13280. _this._localWorld = BABYLON.Matrix.Zero();
  13281. _this._worldMatrix = BABYLON.Matrix.Zero();
  13282. _this._worldMatrixDeterminant = 0;
  13283. _this._absolutePosition = BABYLON.Vector3.Zero();
  13284. _this._pivotMatrix = BABYLON.Matrix.Identity();
  13285. _this._postMultiplyPivotMatrix = false;
  13286. _this._isWorldMatrixFrozen = false;
  13287. /**
  13288. * An event triggered after the world matrix is updated
  13289. * @type {BABYLON.Observable}
  13290. */
  13291. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  13292. _this._nonUniformScaling = false;
  13293. if (isPure) {
  13294. _this.getScene().addTransformNode(_this);
  13295. }
  13296. return _this;
  13297. }
  13298. Object.defineProperty(TransformNode.prototype, "rotation", {
  13299. /**
  13300. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  13301. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  13302. * Default : (0.0, 0.0, 0.0)
  13303. */
  13304. get: function () {
  13305. return this._rotation;
  13306. },
  13307. set: function (newRotation) {
  13308. this._rotation = newRotation;
  13309. },
  13310. enumerable: true,
  13311. configurable: true
  13312. });
  13313. Object.defineProperty(TransformNode.prototype, "scaling", {
  13314. /**
  13315. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  13316. * Default : (1.0, 1.0, 1.0)
  13317. */
  13318. get: function () {
  13319. return this._scaling;
  13320. },
  13321. /**
  13322. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  13323. * Default : (1.0, 1.0, 1.0)
  13324. */
  13325. set: function (newScaling) {
  13326. this._scaling = newScaling;
  13327. },
  13328. enumerable: true,
  13329. configurable: true
  13330. });
  13331. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  13332. /**
  13333. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  13334. * It's null by default.
  13335. * 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)
  13336. */
  13337. get: function () {
  13338. return this._rotationQuaternion;
  13339. },
  13340. set: function (quaternion) {
  13341. this._rotationQuaternion = quaternion;
  13342. //reset the rotation vector.
  13343. if (quaternion && this.rotation.length()) {
  13344. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  13345. }
  13346. },
  13347. enumerable: true,
  13348. configurable: true
  13349. });
  13350. /**
  13351. * Returns the latest update of the World matrix
  13352. * Returns a Matrix.
  13353. */
  13354. TransformNode.prototype.getWorldMatrix = function () {
  13355. if (this._currentRenderId !== this.getScene().getRenderId()) {
  13356. this.computeWorldMatrix();
  13357. }
  13358. return this._worldMatrix;
  13359. };
  13360. /**
  13361. * Returns the latest update of the World matrix determinant.
  13362. */
  13363. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  13364. if (this._currentRenderId !== this.getScene().getRenderId()) {
  13365. this._worldMatrixDeterminant = this.computeWorldMatrix().determinant();
  13366. }
  13367. return this._worldMatrixDeterminant;
  13368. };
  13369. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  13370. /**
  13371. * Returns directly the latest state of the mesh World matrix.
  13372. * A Matrix is returned.
  13373. */
  13374. get: function () {
  13375. return this._worldMatrix;
  13376. },
  13377. enumerable: true,
  13378. configurable: true
  13379. });
  13380. /**
  13381. * Copies the paramater passed Matrix into the mesh Pose matrix.
  13382. * Returns the AbstractMesh.
  13383. */
  13384. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  13385. this._poseMatrix.copyFrom(matrix);
  13386. return this;
  13387. };
  13388. /**
  13389. * Returns the mesh Pose matrix.
  13390. * Returned object : Matrix
  13391. */
  13392. TransformNode.prototype.getPoseMatrix = function () {
  13393. return this._poseMatrix;
  13394. };
  13395. TransformNode.prototype._isSynchronized = function () {
  13396. if (this._isDirty) {
  13397. return false;
  13398. }
  13399. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  13400. return false;
  13401. if (this._cache.pivotMatrixUpdated) {
  13402. return false;
  13403. }
  13404. if (this.infiniteDistance) {
  13405. return false;
  13406. }
  13407. if (!this._cache.position.equals(this.position))
  13408. return false;
  13409. if (this.rotationQuaternion) {
  13410. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  13411. return false;
  13412. }
  13413. if (!this._cache.rotation.equals(this.rotation))
  13414. return false;
  13415. if (!this._cache.scaling.equals(this.scaling))
  13416. return false;
  13417. return true;
  13418. };
  13419. TransformNode.prototype._initCache = function () {
  13420. _super.prototype._initCache.call(this);
  13421. this._cache.localMatrixUpdated = false;
  13422. this._cache.position = BABYLON.Vector3.Zero();
  13423. this._cache.scaling = BABYLON.Vector3.Zero();
  13424. this._cache.rotation = BABYLON.Vector3.Zero();
  13425. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  13426. this._cache.billboardMode = -1;
  13427. };
  13428. TransformNode.prototype.markAsDirty = function (property) {
  13429. if (property === "rotation") {
  13430. this.rotationQuaternion = null;
  13431. }
  13432. this._currentRenderId = Number.MAX_VALUE;
  13433. this._isDirty = true;
  13434. return this;
  13435. };
  13436. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  13437. /**
  13438. * Returns the current mesh absolute position.
  13439. * Retuns a Vector3.
  13440. */
  13441. get: function () {
  13442. return this._absolutePosition;
  13443. },
  13444. enumerable: true,
  13445. configurable: true
  13446. });
  13447. /**
  13448. * Sets a new pivot matrix to the mesh.
  13449. * Returns the AbstractMesh.
  13450. */
  13451. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  13452. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  13453. this._pivotMatrix = matrix.clone();
  13454. this._cache.pivotMatrixUpdated = true;
  13455. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  13456. if (this._postMultiplyPivotMatrix) {
  13457. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  13458. }
  13459. return this;
  13460. };
  13461. /**
  13462. * Returns the mesh pivot matrix.
  13463. * Default : Identity.
  13464. * A Matrix is returned.
  13465. */
  13466. TransformNode.prototype.getPivotMatrix = function () {
  13467. return this._pivotMatrix;
  13468. };
  13469. /**
  13470. * Prevents the World matrix to be computed any longer.
  13471. * Returns the AbstractMesh.
  13472. */
  13473. TransformNode.prototype.freezeWorldMatrix = function () {
  13474. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  13475. this.computeWorldMatrix(true);
  13476. this._isWorldMatrixFrozen = true;
  13477. return this;
  13478. };
  13479. /**
  13480. * Allows back the World matrix computation.
  13481. * Returns the AbstractMesh.
  13482. */
  13483. TransformNode.prototype.unfreezeWorldMatrix = function () {
  13484. this._isWorldMatrixFrozen = false;
  13485. this.computeWorldMatrix(true);
  13486. return this;
  13487. };
  13488. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  13489. /**
  13490. * True if the World matrix has been frozen.
  13491. * Returns a boolean.
  13492. */
  13493. get: function () {
  13494. return this._isWorldMatrixFrozen;
  13495. },
  13496. enumerable: true,
  13497. configurable: true
  13498. });
  13499. /**
  13500. * Retuns the mesh absolute position in the World.
  13501. * Returns a Vector3.
  13502. */
  13503. TransformNode.prototype.getAbsolutePosition = function () {
  13504. this.computeWorldMatrix();
  13505. return this._absolutePosition;
  13506. };
  13507. /**
  13508. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  13509. * Returns the AbstractMesh.
  13510. */
  13511. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  13512. if (!absolutePosition) {
  13513. return this;
  13514. }
  13515. var absolutePositionX;
  13516. var absolutePositionY;
  13517. var absolutePositionZ;
  13518. if (absolutePosition.x === undefined) {
  13519. if (arguments.length < 3) {
  13520. return this;
  13521. }
  13522. absolutePositionX = arguments[0];
  13523. absolutePositionY = arguments[1];
  13524. absolutePositionZ = arguments[2];
  13525. }
  13526. else {
  13527. absolutePositionX = absolutePosition.x;
  13528. absolutePositionY = absolutePosition.y;
  13529. absolutePositionZ = absolutePosition.z;
  13530. }
  13531. if (this.parent) {
  13532. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13533. invertParentWorldMatrix.invert();
  13534. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  13535. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  13536. }
  13537. else {
  13538. this.position.x = absolutePositionX;
  13539. this.position.y = absolutePositionY;
  13540. this.position.z = absolutePositionZ;
  13541. }
  13542. return this;
  13543. };
  13544. /**
  13545. * Sets the mesh position in its local space.
  13546. * Returns the AbstractMesh.
  13547. */
  13548. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  13549. this.computeWorldMatrix();
  13550. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  13551. return this;
  13552. };
  13553. /**
  13554. * Returns the mesh position in the local space from the current World matrix values.
  13555. * Returns a new Vector3.
  13556. */
  13557. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  13558. this.computeWorldMatrix();
  13559. var invLocalWorldMatrix = this._localWorld.clone();
  13560. invLocalWorldMatrix.invert();
  13561. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  13562. };
  13563. /**
  13564. * Translates the mesh along the passed Vector3 in its local space.
  13565. * Returns the AbstractMesh.
  13566. */
  13567. TransformNode.prototype.locallyTranslate = function (vector3) {
  13568. this.computeWorldMatrix(true);
  13569. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  13570. return this;
  13571. };
  13572. /**
  13573. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  13574. * @param targetPoint the position (must be in same space as current mesh) to look at
  13575. * @param yawCor optional yaw (y-axis) correction in radians
  13576. * @param pitchCor optional pitch (x-axis) correction in radians
  13577. * @param rollCor optional roll (z-axis) correction in radians
  13578. * @param space the choosen space of the target
  13579. * @returns the TransformNode.
  13580. */
  13581. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  13582. if (yawCor === void 0) { yawCor = 0; }
  13583. if (pitchCor === void 0) { pitchCor = 0; }
  13584. if (rollCor === void 0) { rollCor = 0; }
  13585. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13586. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  13587. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  13588. targetPoint.subtractToRef(pos, dv);
  13589. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  13590. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  13591. var pitch = Math.atan2(dv.y, len);
  13592. if (this.rotationQuaternion) {
  13593. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  13594. }
  13595. else {
  13596. this.rotation.x = pitch + pitchCor;
  13597. this.rotation.y = yaw + yawCor;
  13598. this.rotation.z = rollCor;
  13599. }
  13600. return this;
  13601. };
  13602. /**
  13603. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13604. * This Vector3 is expressed in the World space.
  13605. */
  13606. TransformNode.prototype.getDirection = function (localAxis) {
  13607. var result = BABYLON.Vector3.Zero();
  13608. this.getDirectionToRef(localAxis, result);
  13609. return result;
  13610. };
  13611. /**
  13612. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13613. * localAxis is expressed in the mesh local space.
  13614. * result is computed in the Wordl space from the mesh World matrix.
  13615. * Returns the AbstractMesh.
  13616. */
  13617. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  13618. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13619. return this;
  13620. };
  13621. TransformNode.prototype.setPivotPoint = function (point, space) {
  13622. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13623. if (this.getScene().getRenderId() == 0) {
  13624. this.computeWorldMatrix(true);
  13625. }
  13626. var wm = this.getWorldMatrix();
  13627. if (space == BABYLON.Space.WORLD) {
  13628. var tmat = BABYLON.Tmp.Matrix[0];
  13629. wm.invertToRef(tmat);
  13630. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13631. }
  13632. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13633. this._pivotMatrix.m[12] = -point.x;
  13634. this._pivotMatrix.m[13] = -point.y;
  13635. this._pivotMatrix.m[14] = -point.z;
  13636. this._cache.pivotMatrixUpdated = true;
  13637. return this;
  13638. };
  13639. /**
  13640. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13641. */
  13642. TransformNode.prototype.getPivotPoint = function () {
  13643. var point = BABYLON.Vector3.Zero();
  13644. this.getPivotPointToRef(point);
  13645. return point;
  13646. };
  13647. /**
  13648. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13649. * Returns the AbstractMesh.
  13650. */
  13651. TransformNode.prototype.getPivotPointToRef = function (result) {
  13652. result.x = -this._pivotMatrix.m[12];
  13653. result.y = -this._pivotMatrix.m[13];
  13654. result.z = -this._pivotMatrix.m[14];
  13655. return this;
  13656. };
  13657. /**
  13658. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13659. */
  13660. TransformNode.prototype.getAbsolutePivotPoint = function () {
  13661. var point = BABYLON.Vector3.Zero();
  13662. this.getAbsolutePivotPointToRef(point);
  13663. return point;
  13664. };
  13665. /**
  13666. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13667. * Returns the AbstractMesh.
  13668. */
  13669. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  13670. result.x = this._pivotMatrix.m[12];
  13671. result.y = this._pivotMatrix.m[13];
  13672. result.z = this._pivotMatrix.m[14];
  13673. this.getPivotPointToRef(result);
  13674. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13675. return this;
  13676. };
  13677. /**
  13678. * Defines the passed node as the parent of the current node.
  13679. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  13680. * Returns the TransformNode.
  13681. */
  13682. TransformNode.prototype.setParent = function (node) {
  13683. if (node == null) {
  13684. var rotation = BABYLON.Tmp.Quaternion[0];
  13685. var position = BABYLON.Tmp.Vector3[0];
  13686. var scale = BABYLON.Tmp.Vector3[1];
  13687. if (this.parent && this.parent.computeWorldMatrix) {
  13688. this.parent.computeWorldMatrix(true);
  13689. }
  13690. this.computeWorldMatrix(true);
  13691. this.getWorldMatrix().decompose(scale, rotation, position);
  13692. if (this.rotationQuaternion) {
  13693. this.rotationQuaternion.copyFrom(rotation);
  13694. }
  13695. else {
  13696. rotation.toEulerAnglesToRef(this.rotation);
  13697. }
  13698. this.scaling.x = scale.x;
  13699. this.scaling.y = scale.y;
  13700. this.scaling.z = scale.z;
  13701. this.position.x = position.x;
  13702. this.position.y = position.y;
  13703. this.position.z = position.z;
  13704. }
  13705. else {
  13706. var rotation = BABYLON.Tmp.Quaternion[0];
  13707. var position = BABYLON.Tmp.Vector3[0];
  13708. var scale = BABYLON.Tmp.Vector3[1];
  13709. var diffMatrix = BABYLON.Tmp.Matrix[0];
  13710. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  13711. this.computeWorldMatrix(true);
  13712. node.computeWorldMatrix(true);
  13713. node.getWorldMatrix().invertToRef(invParentMatrix);
  13714. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  13715. diffMatrix.decompose(scale, rotation, position);
  13716. if (this.rotationQuaternion) {
  13717. this.rotationQuaternion.copyFrom(rotation);
  13718. }
  13719. else {
  13720. rotation.toEulerAnglesToRef(this.rotation);
  13721. }
  13722. this.position.x = position.x;
  13723. this.position.y = position.y;
  13724. this.position.z = position.z;
  13725. this.scaling.x = scale.x;
  13726. this.scaling.y = scale.y;
  13727. this.scaling.z = scale.z;
  13728. }
  13729. this.parent = node;
  13730. return this;
  13731. };
  13732. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  13733. get: function () {
  13734. return this._nonUniformScaling;
  13735. },
  13736. enumerable: true,
  13737. configurable: true
  13738. });
  13739. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  13740. if (this._nonUniformScaling === value) {
  13741. return false;
  13742. }
  13743. this._nonUniformScaling = true;
  13744. return true;
  13745. };
  13746. /**
  13747. * Attach the current TransformNode to another TransformNode associated with a bone
  13748. * @param bone Bone affecting the TransformNode
  13749. * @param affectedTransformNode TransformNode associated with the bone
  13750. */
  13751. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  13752. this._transformToBoneReferal = affectedTransformNode;
  13753. this.parent = bone;
  13754. if (bone.getWorldMatrix().determinant() < 0) {
  13755. this.scalingDeterminant *= -1;
  13756. }
  13757. return this;
  13758. };
  13759. TransformNode.prototype.detachFromBone = function () {
  13760. if (!this.parent) {
  13761. return this;
  13762. }
  13763. if (this.parent.getWorldMatrix().determinant() < 0) {
  13764. this.scalingDeterminant *= -1;
  13765. }
  13766. this._transformToBoneReferal = null;
  13767. this.parent = null;
  13768. return this;
  13769. };
  13770. /**
  13771. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  13772. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13773. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13774. * The passed axis is also normalized.
  13775. * Returns the AbstractMesh.
  13776. */
  13777. TransformNode.prototype.rotate = function (axis, amount, space) {
  13778. axis.normalize();
  13779. if (!this.rotationQuaternion) {
  13780. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13781. this.rotation = BABYLON.Vector3.Zero();
  13782. }
  13783. var rotationQuaternion;
  13784. if (!space || space === BABYLON.Space.LOCAL) {
  13785. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  13786. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  13787. }
  13788. else {
  13789. if (this.parent) {
  13790. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13791. invertParentWorldMatrix.invert();
  13792. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  13793. }
  13794. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  13795. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13796. }
  13797. return this;
  13798. };
  13799. /**
  13800. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  13801. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13802. * The passed axis is also normalized.
  13803. * Returns the AbstractMesh.
  13804. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  13805. */
  13806. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  13807. axis.normalize();
  13808. if (!this.rotationQuaternion) {
  13809. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13810. this.rotation.copyFromFloats(0, 0, 0);
  13811. }
  13812. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  13813. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  13814. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  13815. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  13816. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  13817. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  13818. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  13819. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  13820. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13821. return this;
  13822. };
  13823. /**
  13824. * Translates the mesh along the axis vector for the passed distance in the given space.
  13825. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13826. * Returns the AbstractMesh.
  13827. */
  13828. TransformNode.prototype.translate = function (axis, distance, space) {
  13829. var displacementVector = axis.scale(distance);
  13830. if (!space || space === BABYLON.Space.LOCAL) {
  13831. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  13832. this.setPositionWithLocalVector(tempV3);
  13833. }
  13834. else {
  13835. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  13836. }
  13837. return this;
  13838. };
  13839. /**
  13840. * Adds a rotation step to the mesh current rotation.
  13841. * x, y, z are Euler angles expressed in radians.
  13842. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  13843. * This means this rotation is made in the mesh local space only.
  13844. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  13845. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  13846. * ```javascript
  13847. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  13848. * ```
  13849. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  13850. * 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.
  13851. * Returns the AbstractMesh.
  13852. */
  13853. TransformNode.prototype.addRotation = function (x, y, z) {
  13854. var rotationQuaternion;
  13855. if (this.rotationQuaternion) {
  13856. rotationQuaternion = this.rotationQuaternion;
  13857. }
  13858. else {
  13859. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  13860. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  13861. }
  13862. var accumulation = BABYLON.Tmp.Quaternion[0];
  13863. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  13864. rotationQuaternion.multiplyInPlace(accumulation);
  13865. if (!this.rotationQuaternion) {
  13866. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  13867. }
  13868. return this;
  13869. };
  13870. /**
  13871. * Computes the mesh World matrix and returns it.
  13872. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  13873. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  13874. * If the parameter `force`is set to `true`, the actual computation is done.
  13875. * Returns the mesh World Matrix.
  13876. */
  13877. TransformNode.prototype.computeWorldMatrix = function (force) {
  13878. if (this._isWorldMatrixFrozen) {
  13879. return this._worldMatrix;
  13880. }
  13881. if (!force && this.isSynchronized(true)) {
  13882. return this._worldMatrix;
  13883. }
  13884. this._cache.position.copyFrom(this.position);
  13885. this._cache.scaling.copyFrom(this.scaling);
  13886. this._cache.pivotMatrixUpdated = false;
  13887. this._cache.billboardMode = this.billboardMode;
  13888. this._currentRenderId = this.getScene().getRenderId();
  13889. this._isDirty = false;
  13890. // Scaling
  13891. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  13892. // Rotation
  13893. //rotate, if quaternion is set and rotation was used
  13894. if (this.rotationQuaternion) {
  13895. var len = this.rotation.length();
  13896. if (len) {
  13897. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  13898. this.rotation.copyFromFloats(0, 0, 0);
  13899. }
  13900. }
  13901. if (this.rotationQuaternion) {
  13902. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  13903. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13904. }
  13905. else {
  13906. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  13907. this._cache.rotation.copyFrom(this.rotation);
  13908. }
  13909. // Translation
  13910. var camera = this.getScene().activeCamera;
  13911. if (this.infiniteDistance && !this.parent && camera) {
  13912. var cameraWorldMatrix = camera.getWorldMatrix();
  13913. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  13914. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  13915. }
  13916. else {
  13917. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  13918. }
  13919. // Composing transformations
  13920. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  13921. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13922. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  13923. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  13924. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  13925. // Need to decompose each rotation here
  13926. var currentPosition = BABYLON.Tmp.Vector3[3];
  13927. if (this.parent && this.parent.getWorldMatrix) {
  13928. if (this._transformToBoneReferal) {
  13929. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13930. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  13931. }
  13932. else {
  13933. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  13934. }
  13935. }
  13936. else {
  13937. currentPosition.copyFrom(this.position);
  13938. }
  13939. currentPosition.subtractInPlace(camera.globalPosition);
  13940. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  13941. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  13942. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  13943. }
  13944. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  13945. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  13946. }
  13947. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  13948. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  13949. }
  13950. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  13951. }
  13952. else {
  13953. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  13954. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  13955. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  13956. }
  13957. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  13958. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13959. }
  13960. // Local world
  13961. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  13962. // Parent
  13963. if (this.parent && this.parent.getWorldMatrix) {
  13964. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  13965. if (this._transformToBoneReferal) {
  13966. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13967. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  13968. }
  13969. else {
  13970. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  13971. }
  13972. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  13973. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  13974. this._worldMatrix.copyFrom(this._localWorld);
  13975. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  13976. }
  13977. else {
  13978. if (this._transformToBoneReferal) {
  13979. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13980. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  13981. }
  13982. else {
  13983. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  13984. }
  13985. }
  13986. this._markSyncedWithParent();
  13987. }
  13988. else {
  13989. this._worldMatrix.copyFrom(this._localWorld);
  13990. }
  13991. // Post multiply inverse of pivotMatrix
  13992. if (this._postMultiplyPivotMatrix) {
  13993. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  13994. }
  13995. // Normal matrix
  13996. if (this.scaling.isNonUniform) {
  13997. this._updateNonUniformScalingState(true);
  13998. }
  13999. else if (this.parent && this.parent._nonUniformScaling) {
  14000. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  14001. }
  14002. else {
  14003. this._updateNonUniformScalingState(false);
  14004. }
  14005. this._afterComputeWorldMatrix();
  14006. // Absolute position
  14007. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  14008. // Callbacks
  14009. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  14010. if (!this._poseMatrix) {
  14011. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  14012. }
  14013. return this._worldMatrix;
  14014. };
  14015. TransformNode.prototype._afterComputeWorldMatrix = function () {
  14016. };
  14017. /**
  14018. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  14019. * @param func: callback function to add
  14020. *
  14021. * Returns the TransformNode.
  14022. */
  14023. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  14024. this.onAfterWorldMatrixUpdateObservable.add(func);
  14025. return this;
  14026. };
  14027. /**
  14028. * Removes a registered callback function.
  14029. * Returns the TransformNode.
  14030. */
  14031. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  14032. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  14033. return this;
  14034. };
  14035. /**
  14036. * Clone the current transform node
  14037. * Returns the new transform node
  14038. * @param name Name of the new clone
  14039. * @param newParent New parent for the clone
  14040. * @param doNotCloneChildren Do not clone children hierarchy
  14041. */
  14042. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14043. var _this = this;
  14044. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  14045. result.name = name;
  14046. result.id = name;
  14047. if (newParent) {
  14048. result.parent = newParent;
  14049. }
  14050. if (!doNotCloneChildren) {
  14051. // Children
  14052. var directDescendants = this.getDescendants(true);
  14053. for (var index = 0; index < directDescendants.length; index++) {
  14054. var child = directDescendants[index];
  14055. if (child.clone) {
  14056. child.clone(name + "." + child.name, result);
  14057. }
  14058. }
  14059. }
  14060. return result;
  14061. };
  14062. TransformNode.prototype.serialize = function (currentSerializationObject) {
  14063. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  14064. serializationObject.type = this.getClassName();
  14065. // Parent
  14066. if (this.parent) {
  14067. serializationObject.parentId = this.parent.id;
  14068. }
  14069. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  14070. serializationObject.tags = BABYLON.Tags.GetTags(this);
  14071. }
  14072. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  14073. serializationObject.isEnabled = this.isEnabled();
  14074. // Parent
  14075. if (this.parent) {
  14076. serializationObject.parentId = this.parent.id;
  14077. }
  14078. return serializationObject;
  14079. };
  14080. // Statics
  14081. /**
  14082. * Returns a new TransformNode object parsed from the source provided.
  14083. * The parameter `parsedMesh` is the source.
  14084. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  14085. */
  14086. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  14087. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  14088. if (BABYLON.Tags) {
  14089. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  14090. }
  14091. if (parsedTransformNode.localMatrix) {
  14092. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  14093. }
  14094. else if (parsedTransformNode.pivotMatrix) {
  14095. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  14096. }
  14097. transformNode.setEnabled(parsedTransformNode.isEnabled);
  14098. // Parent
  14099. if (parsedTransformNode.parentId) {
  14100. transformNode._waitingParentId = parsedTransformNode.parentId;
  14101. }
  14102. return transformNode;
  14103. };
  14104. /**
  14105. * Disposes the TransformNode.
  14106. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  14107. * Returns nothing.
  14108. */
  14109. TransformNode.prototype.dispose = function (doNotRecurse) {
  14110. // Animations
  14111. this.getScene().stopAnimation(this);
  14112. // Remove from scene
  14113. this.getScene().removeTransformNode(this);
  14114. this._cache = {};
  14115. if (!doNotRecurse) {
  14116. // Children
  14117. var objects = this.getDescendants(true);
  14118. for (var index = 0; index < objects.length; index++) {
  14119. objects[index].dispose();
  14120. }
  14121. }
  14122. else {
  14123. var childMeshes = this.getChildMeshes(true);
  14124. for (index = 0; index < childMeshes.length; index++) {
  14125. var child = childMeshes[index];
  14126. child.parent = null;
  14127. child.computeWorldMatrix(true);
  14128. }
  14129. }
  14130. this.onAfterWorldMatrixUpdateObservable.clear();
  14131. _super.prototype.dispose.call(this);
  14132. };
  14133. // Statics
  14134. TransformNode.BILLBOARDMODE_NONE = 0;
  14135. TransformNode.BILLBOARDMODE_X = 1;
  14136. TransformNode.BILLBOARDMODE_Y = 2;
  14137. TransformNode.BILLBOARDMODE_Z = 4;
  14138. TransformNode.BILLBOARDMODE_ALL = 7;
  14139. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  14140. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  14141. __decorate([
  14142. BABYLON.serializeAsVector3()
  14143. ], TransformNode.prototype, "_rotation", void 0);
  14144. __decorate([
  14145. BABYLON.serializeAsQuaternion()
  14146. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  14147. __decorate([
  14148. BABYLON.serializeAsVector3()
  14149. ], TransformNode.prototype, "_scaling", void 0);
  14150. __decorate([
  14151. BABYLON.serialize()
  14152. ], TransformNode.prototype, "billboardMode", void 0);
  14153. __decorate([
  14154. BABYLON.serialize()
  14155. ], TransformNode.prototype, "scalingDeterminant", void 0);
  14156. __decorate([
  14157. BABYLON.serialize()
  14158. ], TransformNode.prototype, "infiniteDistance", void 0);
  14159. __decorate([
  14160. BABYLON.serializeAsVector3()
  14161. ], TransformNode.prototype, "position", void 0);
  14162. return TransformNode;
  14163. }(BABYLON.Node));
  14164. BABYLON.TransformNode = TransformNode;
  14165. })(BABYLON || (BABYLON = {}));
  14166. //# sourceMappingURL=babylon.transformNode.js.map
  14167. var BABYLON;
  14168. (function (BABYLON) {
  14169. var AbstractMesh = /** @class */ (function (_super) {
  14170. __extends(AbstractMesh, _super);
  14171. // Constructor
  14172. function AbstractMesh(name, scene) {
  14173. if (scene === void 0) { scene = null; }
  14174. var _this = _super.call(this, name, scene, false) || this;
  14175. _this._facetNb = 0; // facet number
  14176. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  14177. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  14178. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  14179. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  14180. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  14181. _this._subDiv = {
  14182. max: 1,
  14183. X: 1,
  14184. Y: 1,
  14185. Z: 1
  14186. };
  14187. _this._facetDepthSort = false; // is the facet depth sort to be computed
  14188. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  14189. // Events
  14190. /**
  14191. * An event triggered when this mesh collides with another one
  14192. * @type {BABYLON.Observable}
  14193. */
  14194. _this.onCollideObservable = new BABYLON.Observable();
  14195. /**
  14196. * An event triggered when the collision's position changes
  14197. * @type {BABYLON.Observable}
  14198. */
  14199. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  14200. /**
  14201. * An event triggered when material is changed
  14202. * @type {BABYLON.Observable}
  14203. */
  14204. _this.onMaterialChangedObservable = new BABYLON.Observable();
  14205. // Properties
  14206. _this.definedFacingForward = true; // orientation for POV movement & rotation
  14207. /**
  14208. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  14209. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  14210. * or
  14211. * 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.
  14212. * for more info check WebGl documentations
  14213. */
  14214. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  14215. /**
  14216. * 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:
  14217. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  14218. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  14219. * 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.
  14220. */
  14221. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  14222. /**
  14223. * 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.
  14224. * The default value is -1 which means don't break the query and wait till the result.
  14225. */
  14226. _this.occlusionRetryCount = -1;
  14227. _this._occlusionInternalRetryCounter = 0;
  14228. _this._isOccluded = false;
  14229. _this._isOcclusionQueryInProgress = false;
  14230. _this.visibility = 1.0;
  14231. _this.alphaIndex = Number.MAX_VALUE;
  14232. _this.isVisible = true;
  14233. _this.isPickable = true;
  14234. _this.showBoundingBox = false;
  14235. _this.showSubMeshesBoundingBox = false;
  14236. _this.isBlocker = false;
  14237. _this.enablePointerMoveEvents = false;
  14238. _this.renderingGroupId = 0;
  14239. _this._receiveShadows = false;
  14240. _this.renderOutline = false;
  14241. _this.outlineColor = BABYLON.Color3.Red();
  14242. _this.outlineWidth = 0.02;
  14243. _this.renderOverlay = false;
  14244. _this.overlayColor = BABYLON.Color3.Red();
  14245. _this.overlayAlpha = 0.5;
  14246. _this._hasVertexAlpha = false;
  14247. _this._useVertexColors = true;
  14248. _this._computeBonesUsingShaders = true;
  14249. _this._numBoneInfluencers = 4;
  14250. _this._applyFog = true;
  14251. _this.useOctreeForRenderingSelection = true;
  14252. _this.useOctreeForPicking = true;
  14253. _this.useOctreeForCollisions = true;
  14254. _this._layerMask = 0x0FFFFFFF;
  14255. /**
  14256. * True if the mesh must be rendered in any case.
  14257. */
  14258. _this.alwaysSelectAsActiveMesh = false;
  14259. /**
  14260. * This scene's action manager
  14261. * @type {BABYLON.ActionManager}
  14262. */
  14263. _this.actionManager = null;
  14264. // Physics
  14265. _this.physicsImpostor = null;
  14266. // Collisions
  14267. _this._checkCollisions = false;
  14268. _this._collisionMask = -1;
  14269. _this._collisionGroup = -1;
  14270. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  14271. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  14272. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  14273. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  14274. // Edges
  14275. _this.edgesWidth = 1;
  14276. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  14277. // Cache
  14278. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  14279. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  14280. _this._isDisposed = false;
  14281. _this._renderId = 0;
  14282. _this._intersectionsInProgress = new Array();
  14283. _this._unIndexed = false;
  14284. _this._lightSources = new Array();
  14285. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  14286. if (collidedMesh === void 0) { collidedMesh = null; }
  14287. //TODO move this to the collision coordinator!
  14288. if (_this.getScene().workerCollisions)
  14289. newPosition.multiplyInPlace(_this._collider._radius);
  14290. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  14291. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  14292. _this.position.addInPlace(_this._diffPositionForCollisions);
  14293. }
  14294. if (collidedMesh) {
  14295. _this.onCollideObservable.notifyObservers(collidedMesh);
  14296. }
  14297. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  14298. };
  14299. _this.getScene().addMesh(_this);
  14300. _this._resyncLightSources();
  14301. return _this;
  14302. }
  14303. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  14304. get: function () {
  14305. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  14306. },
  14307. enumerable: true,
  14308. configurable: true
  14309. });
  14310. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  14311. get: function () {
  14312. return BABYLON.TransformNode.BILLBOARDMODE_X;
  14313. },
  14314. enumerable: true,
  14315. configurable: true
  14316. });
  14317. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  14318. get: function () {
  14319. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  14320. },
  14321. enumerable: true,
  14322. configurable: true
  14323. });
  14324. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  14325. get: function () {
  14326. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  14327. },
  14328. enumerable: true,
  14329. configurable: true
  14330. });
  14331. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  14332. get: function () {
  14333. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  14334. },
  14335. enumerable: true,
  14336. configurable: true
  14337. });
  14338. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  14339. /**
  14340. * Read-only : the number of facets in the mesh
  14341. */
  14342. get: function () {
  14343. return this._facetNb;
  14344. },
  14345. enumerable: true,
  14346. configurable: true
  14347. });
  14348. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  14349. /**
  14350. * The number (integer) of subdivisions per axis in the partioning space
  14351. */
  14352. get: function () {
  14353. return this._partitioningSubdivisions;
  14354. },
  14355. set: function (nb) {
  14356. this._partitioningSubdivisions = nb;
  14357. },
  14358. enumerable: true,
  14359. configurable: true
  14360. });
  14361. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  14362. /**
  14363. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  14364. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  14365. */
  14366. get: function () {
  14367. return this._partitioningBBoxRatio;
  14368. },
  14369. set: function (ratio) {
  14370. this._partitioningBBoxRatio = ratio;
  14371. },
  14372. enumerable: true,
  14373. configurable: true
  14374. });
  14375. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  14376. /**
  14377. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  14378. * Works only for updatable meshes.
  14379. * Doesn't work with multi-materials.
  14380. */
  14381. get: function () {
  14382. return this._facetDepthSort;
  14383. },
  14384. set: function (sort) {
  14385. this._facetDepthSort = sort;
  14386. },
  14387. enumerable: true,
  14388. configurable: true
  14389. });
  14390. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  14391. /**
  14392. * The location (Vector3) where the facet depth sort must be computed from.
  14393. * By default, the active camera position.
  14394. * Used only when facet depth sort is enabled.
  14395. */
  14396. get: function () {
  14397. return this._facetDepthSortFrom;
  14398. },
  14399. set: function (location) {
  14400. this._facetDepthSortFrom = location;
  14401. },
  14402. enumerable: true,
  14403. configurable: true
  14404. });
  14405. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  14406. /**
  14407. * Read-only boolean : is the feature facetData enabled ?
  14408. */
  14409. get: function () {
  14410. return this._facetDataEnabled;
  14411. },
  14412. enumerable: true,
  14413. configurable: true
  14414. });
  14415. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  14416. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  14417. return false;
  14418. }
  14419. this._markSubMeshesAsMiscDirty();
  14420. return true;
  14421. };
  14422. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  14423. set: function (callback) {
  14424. if (this._onCollideObserver) {
  14425. this.onCollideObservable.remove(this._onCollideObserver);
  14426. }
  14427. this._onCollideObserver = this.onCollideObservable.add(callback);
  14428. },
  14429. enumerable: true,
  14430. configurable: true
  14431. });
  14432. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  14433. set: function (callback) {
  14434. if (this._onCollisionPositionChangeObserver) {
  14435. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  14436. }
  14437. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  14438. },
  14439. enumerable: true,
  14440. configurable: true
  14441. });
  14442. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  14443. /**
  14444. * 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.
  14445. */
  14446. get: function () {
  14447. return this._isOccluded;
  14448. },
  14449. set: function (value) {
  14450. this._isOccluded = value;
  14451. },
  14452. enumerable: true,
  14453. configurable: true
  14454. });
  14455. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  14456. /**
  14457. * Flag to check the progress status of the query
  14458. */
  14459. get: function () {
  14460. return this._isOcclusionQueryInProgress;
  14461. },
  14462. enumerable: true,
  14463. configurable: true
  14464. });
  14465. Object.defineProperty(AbstractMesh.prototype, "material", {
  14466. get: function () {
  14467. return this._material;
  14468. },
  14469. set: function (value) {
  14470. if (this._material === value) {
  14471. return;
  14472. }
  14473. this._material = value;
  14474. if (this.onMaterialChangedObservable.hasObservers) {
  14475. this.onMaterialChangedObservable.notifyObservers(this);
  14476. }
  14477. if (!this.subMeshes) {
  14478. return;
  14479. }
  14480. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14481. var subMesh = _a[_i];
  14482. subMesh.setEffect(null);
  14483. }
  14484. },
  14485. enumerable: true,
  14486. configurable: true
  14487. });
  14488. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  14489. get: function () {
  14490. return this._receiveShadows;
  14491. },
  14492. set: function (value) {
  14493. if (this._receiveShadows === value) {
  14494. return;
  14495. }
  14496. this._receiveShadows = value;
  14497. this._markSubMeshesAsLightDirty();
  14498. },
  14499. enumerable: true,
  14500. configurable: true
  14501. });
  14502. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  14503. get: function () {
  14504. return this._hasVertexAlpha;
  14505. },
  14506. set: function (value) {
  14507. if (this._hasVertexAlpha === value) {
  14508. return;
  14509. }
  14510. this._hasVertexAlpha = value;
  14511. this._markSubMeshesAsAttributesDirty();
  14512. },
  14513. enumerable: true,
  14514. configurable: true
  14515. });
  14516. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  14517. get: function () {
  14518. return this._useVertexColors;
  14519. },
  14520. set: function (value) {
  14521. if (this._useVertexColors === value) {
  14522. return;
  14523. }
  14524. this._useVertexColors = value;
  14525. this._markSubMeshesAsAttributesDirty();
  14526. },
  14527. enumerable: true,
  14528. configurable: true
  14529. });
  14530. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  14531. get: function () {
  14532. return this._computeBonesUsingShaders;
  14533. },
  14534. set: function (value) {
  14535. if (this._computeBonesUsingShaders === value) {
  14536. return;
  14537. }
  14538. this._computeBonesUsingShaders = value;
  14539. this._markSubMeshesAsAttributesDirty();
  14540. },
  14541. enumerable: true,
  14542. configurable: true
  14543. });
  14544. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  14545. get: function () {
  14546. return this._numBoneInfluencers;
  14547. },
  14548. set: function (value) {
  14549. if (this._numBoneInfluencers === value) {
  14550. return;
  14551. }
  14552. this._numBoneInfluencers = value;
  14553. this._markSubMeshesAsAttributesDirty();
  14554. },
  14555. enumerable: true,
  14556. configurable: true
  14557. });
  14558. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  14559. get: function () {
  14560. return this._applyFog;
  14561. },
  14562. set: function (value) {
  14563. if (this._applyFog === value) {
  14564. return;
  14565. }
  14566. this._applyFog = value;
  14567. this._markSubMeshesAsMiscDirty();
  14568. },
  14569. enumerable: true,
  14570. configurable: true
  14571. });
  14572. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  14573. get: function () {
  14574. return this._layerMask;
  14575. },
  14576. set: function (value) {
  14577. if (value === this._layerMask) {
  14578. return;
  14579. }
  14580. this._layerMask = value;
  14581. this._resyncLightSources();
  14582. },
  14583. enumerable: true,
  14584. configurable: true
  14585. });
  14586. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  14587. get: function () {
  14588. return this._collisionMask;
  14589. },
  14590. set: function (mask) {
  14591. this._collisionMask = !isNaN(mask) ? mask : -1;
  14592. },
  14593. enumerable: true,
  14594. configurable: true
  14595. });
  14596. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  14597. get: function () {
  14598. return this._collisionGroup;
  14599. },
  14600. set: function (mask) {
  14601. this._collisionGroup = !isNaN(mask) ? mask : -1;
  14602. },
  14603. enumerable: true,
  14604. configurable: true
  14605. });
  14606. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  14607. get: function () {
  14608. return null;
  14609. },
  14610. enumerable: true,
  14611. configurable: true
  14612. });
  14613. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  14614. get: function () {
  14615. return this._skeleton;
  14616. },
  14617. set: function (value) {
  14618. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  14619. this._skeleton._unregisterMeshWithPoseMatrix(this);
  14620. }
  14621. if (value && value.needInitialSkinMatrix) {
  14622. value._registerMeshWithPoseMatrix(this);
  14623. }
  14624. this._skeleton = value;
  14625. if (!this._skeleton) {
  14626. this._bonesTransformMatrices = null;
  14627. }
  14628. this._markSubMeshesAsAttributesDirty();
  14629. },
  14630. enumerable: true,
  14631. configurable: true
  14632. });
  14633. /**
  14634. * Boolean : true if the mesh has been disposed.
  14635. */
  14636. AbstractMesh.prototype.isDisposed = function () {
  14637. return this._isDisposed;
  14638. };
  14639. /**
  14640. * Returns the string "AbstractMesh"
  14641. */
  14642. AbstractMesh.prototype.getClassName = function () {
  14643. return "AbstractMesh";
  14644. };
  14645. /**
  14646. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14647. */
  14648. AbstractMesh.prototype.toString = function (fullDetails) {
  14649. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  14650. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  14651. if (this._skeleton) {
  14652. ret += ", skeleton: " + this._skeleton.name;
  14653. }
  14654. if (fullDetails) {
  14655. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  14656. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  14657. }
  14658. return ret;
  14659. };
  14660. AbstractMesh.prototype._rebuild = function () {
  14661. if (this._occlusionQuery) {
  14662. this._occlusionQuery = null;
  14663. }
  14664. if (this._edgesRenderer) {
  14665. this._edgesRenderer._rebuild();
  14666. }
  14667. if (!this.subMeshes) {
  14668. return;
  14669. }
  14670. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14671. var subMesh = _a[_i];
  14672. subMesh._rebuild();
  14673. }
  14674. };
  14675. AbstractMesh.prototype._resyncLightSources = function () {
  14676. this._lightSources.length = 0;
  14677. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  14678. var light = _a[_i];
  14679. if (!light.isEnabled()) {
  14680. continue;
  14681. }
  14682. if (light.canAffectMesh(this)) {
  14683. this._lightSources.push(light);
  14684. }
  14685. }
  14686. this._markSubMeshesAsLightDirty();
  14687. };
  14688. AbstractMesh.prototype._resyncLighSource = function (light) {
  14689. var isIn = light.isEnabled() && light.canAffectMesh(this);
  14690. var index = this._lightSources.indexOf(light);
  14691. if (index === -1) {
  14692. if (!isIn) {
  14693. return;
  14694. }
  14695. this._lightSources.push(light);
  14696. }
  14697. else {
  14698. if (isIn) {
  14699. return;
  14700. }
  14701. this._lightSources.splice(index, 1);
  14702. }
  14703. this._markSubMeshesAsLightDirty();
  14704. };
  14705. AbstractMesh.prototype._removeLightSource = function (light) {
  14706. var index = this._lightSources.indexOf(light);
  14707. if (index === -1) {
  14708. return;
  14709. }
  14710. this._lightSources.splice(index, 1);
  14711. };
  14712. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  14713. if (!this.subMeshes) {
  14714. return;
  14715. }
  14716. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14717. var subMesh = _a[_i];
  14718. if (subMesh._materialDefines) {
  14719. func(subMesh._materialDefines);
  14720. }
  14721. }
  14722. };
  14723. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  14724. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  14725. };
  14726. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  14727. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  14728. };
  14729. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  14730. if (!this.subMeshes) {
  14731. return;
  14732. }
  14733. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14734. var subMesh = _a[_i];
  14735. var material = subMesh.getMaterial();
  14736. if (material) {
  14737. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  14738. }
  14739. }
  14740. };
  14741. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  14742. /**
  14743. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14744. * Default : (1.0, 1.0, 1.0)
  14745. */
  14746. get: function () {
  14747. return this._scaling;
  14748. },
  14749. /**
  14750. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14751. * Default : (1.0, 1.0, 1.0)
  14752. */
  14753. set: function (newScaling) {
  14754. this._scaling = newScaling;
  14755. if (this.physicsImpostor) {
  14756. this.physicsImpostor.forceUpdate();
  14757. }
  14758. },
  14759. enumerable: true,
  14760. configurable: true
  14761. });
  14762. // Methods
  14763. /**
  14764. * Disables the mesh edger rendering mode.
  14765. * Returns the AbstractMesh.
  14766. */
  14767. AbstractMesh.prototype.disableEdgesRendering = function () {
  14768. if (this._edgesRenderer) {
  14769. this._edgesRenderer.dispose();
  14770. this._edgesRenderer = null;
  14771. }
  14772. return this;
  14773. };
  14774. /**
  14775. * Enables the edge rendering mode on the mesh.
  14776. * This mode makes the mesh edges visible.
  14777. * Returns the AbstractMesh.
  14778. */
  14779. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  14780. if (epsilon === void 0) { epsilon = 0.95; }
  14781. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  14782. this.disableEdgesRendering();
  14783. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  14784. return this;
  14785. };
  14786. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  14787. /**
  14788. * Returns true if the mesh is blocked. Used by the class Mesh.
  14789. * Returns the boolean `false` by default.
  14790. */
  14791. get: function () {
  14792. return false;
  14793. },
  14794. enumerable: true,
  14795. configurable: true
  14796. });
  14797. /**
  14798. * Returns the mesh itself by default, used by the class Mesh.
  14799. * Returned type : AbstractMesh
  14800. */
  14801. AbstractMesh.prototype.getLOD = function (camera) {
  14802. return this;
  14803. };
  14804. /**
  14805. * Returns 0 by default, used by the class Mesh.
  14806. * Returns an integer.
  14807. */
  14808. AbstractMesh.prototype.getTotalVertices = function () {
  14809. return 0;
  14810. };
  14811. /**
  14812. * Returns null by default, used by the class Mesh.
  14813. * Returned type : integer array
  14814. */
  14815. AbstractMesh.prototype.getIndices = function () {
  14816. return null;
  14817. };
  14818. /**
  14819. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  14820. * Returned type : float array or Float32Array
  14821. */
  14822. AbstractMesh.prototype.getVerticesData = function (kind) {
  14823. return null;
  14824. };
  14825. /**
  14826. * Sets the vertex data of the mesh geometry for the requested `kind`.
  14827. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  14828. * The `data` are either a numeric array either a Float32Array.
  14829. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  14830. * 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).
  14831. * Note that a new underlying VertexBuffer object is created each call.
  14832. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  14833. *
  14834. * Possible `kind` values :
  14835. * - BABYLON.VertexBuffer.PositionKind
  14836. * - BABYLON.VertexBuffer.UVKind
  14837. * - BABYLON.VertexBuffer.UV2Kind
  14838. * - BABYLON.VertexBuffer.UV3Kind
  14839. * - BABYLON.VertexBuffer.UV4Kind
  14840. * - BABYLON.VertexBuffer.UV5Kind
  14841. * - BABYLON.VertexBuffer.UV6Kind
  14842. * - BABYLON.VertexBuffer.ColorKind
  14843. * - BABYLON.VertexBuffer.MatricesIndicesKind
  14844. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  14845. * - BABYLON.VertexBuffer.MatricesWeightsKind
  14846. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  14847. *
  14848. * Returns the Mesh.
  14849. */
  14850. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14851. return this;
  14852. };
  14853. /**
  14854. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  14855. * If the mesh has no geometry, it is simply returned as it is.
  14856. * The `data` are either a numeric array either a Float32Array.
  14857. * No new underlying VertexBuffer object is created.
  14858. * 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.
  14859. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  14860. *
  14861. * Possible `kind` values :
  14862. * - BABYLON.VertexBuffer.PositionKind
  14863. * - BABYLON.VertexBuffer.UVKind
  14864. * - BABYLON.VertexBuffer.UV2Kind
  14865. * - BABYLON.VertexBuffer.UV3Kind
  14866. * - BABYLON.VertexBuffer.UV4Kind
  14867. * - BABYLON.VertexBuffer.UV5Kind
  14868. * - BABYLON.VertexBuffer.UV6Kind
  14869. * - BABYLON.VertexBuffer.ColorKind
  14870. * - BABYLON.VertexBuffer.MatricesIndicesKind
  14871. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  14872. * - BABYLON.VertexBuffer.MatricesWeightsKind
  14873. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  14874. *
  14875. * Returns the Mesh.
  14876. */
  14877. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14878. return this;
  14879. };
  14880. /**
  14881. * Sets the mesh indices.
  14882. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  14883. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  14884. * This method creates a new index buffer each call.
  14885. * Returns the Mesh.
  14886. */
  14887. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  14888. return this;
  14889. };
  14890. /** Returns false by default, used by the class Mesh.
  14891. * Returns a boolean
  14892. */
  14893. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  14894. return false;
  14895. };
  14896. /**
  14897. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  14898. * Returns a BoundingInfo
  14899. */
  14900. AbstractMesh.prototype.getBoundingInfo = function () {
  14901. if (this._masterMesh) {
  14902. return this._masterMesh.getBoundingInfo();
  14903. }
  14904. if (!this._boundingInfo) {
  14905. // this._boundingInfo is being created here
  14906. this._updateBoundingInfo();
  14907. }
  14908. // cannot be null.
  14909. return this._boundingInfo;
  14910. };
  14911. /**
  14912. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  14913. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  14914. */
  14915. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  14916. if (includeDescendants === void 0) { includeDescendants = true; }
  14917. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  14918. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  14919. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  14920. if (maxDimension === 0) {
  14921. return this;
  14922. }
  14923. var scale = 1 / maxDimension;
  14924. this.scaling.scaleInPlace(scale);
  14925. return this;
  14926. };
  14927. /**
  14928. * Sets a mesh new object BoundingInfo.
  14929. * Returns the AbstractMesh.
  14930. */
  14931. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  14932. this._boundingInfo = boundingInfo;
  14933. return this;
  14934. };
  14935. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  14936. get: function () {
  14937. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  14938. },
  14939. enumerable: true,
  14940. configurable: true
  14941. });
  14942. AbstractMesh.prototype._preActivate = function () {
  14943. };
  14944. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  14945. };
  14946. AbstractMesh.prototype._activate = function (renderId) {
  14947. this._renderId = renderId;
  14948. };
  14949. /**
  14950. * Returns the latest update of the World matrix
  14951. * Returns a Matrix.
  14952. */
  14953. AbstractMesh.prototype.getWorldMatrix = function () {
  14954. if (this._masterMesh) {
  14955. return this._masterMesh.getWorldMatrix();
  14956. }
  14957. return _super.prototype.getWorldMatrix.call(this);
  14958. };
  14959. /**
  14960. * Returns the latest update of the World matrix determinant.
  14961. */
  14962. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  14963. if (this._masterMesh) {
  14964. return this._masterMesh._getWorldMatrixDeterminant();
  14965. }
  14966. return _super.prototype._getWorldMatrixDeterminant.call(this);
  14967. };
  14968. // ================================== Point of View Movement =================================
  14969. /**
  14970. * Perform relative position change from the point of view of behind the front of the mesh.
  14971. * This is performed taking into account the meshes current rotation, so you do not have to care.
  14972. * Supports definition of mesh facing forward or backward.
  14973. * @param {number} amountRight
  14974. * @param {number} amountUp
  14975. * @param {number} amountForward
  14976. *
  14977. * Returns the AbstractMesh.
  14978. */
  14979. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  14980. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  14981. return this;
  14982. };
  14983. /**
  14984. * Calculate relative position change from the point of view of behind the front of the mesh.
  14985. * This is performed taking into account the meshes current rotation, so you do not have to care.
  14986. * Supports definition of mesh facing forward or backward.
  14987. * @param {number} amountRight
  14988. * @param {number} amountUp
  14989. * @param {number} amountForward
  14990. *
  14991. * Returns a new Vector3.
  14992. */
  14993. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  14994. var rotMatrix = new BABYLON.Matrix();
  14995. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  14996. rotQuaternion.toRotationMatrix(rotMatrix);
  14997. var translationDelta = BABYLON.Vector3.Zero();
  14998. var defForwardMult = this.definedFacingForward ? -1 : 1;
  14999. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  15000. return translationDelta;
  15001. };
  15002. // ================================== Point of View Rotation =================================
  15003. /**
  15004. * Perform relative rotation change from the point of view of behind the front of the mesh.
  15005. * Supports definition of mesh facing forward or backward.
  15006. * @param {number} flipBack
  15007. * @param {number} twirlClockwise
  15008. * @param {number} tiltRight
  15009. *
  15010. * Returns the AbstractMesh.
  15011. */
  15012. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  15013. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  15014. return this;
  15015. };
  15016. /**
  15017. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  15018. * Supports definition of mesh facing forward or backward.
  15019. * @param {number} flipBack
  15020. * @param {number} twirlClockwise
  15021. * @param {number} tiltRight
  15022. *
  15023. * Returns a new Vector3.
  15024. */
  15025. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  15026. var defForwardMult = this.definedFacingForward ? 1 : -1;
  15027. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  15028. };
  15029. /**
  15030. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  15031. * @param includeDescendants Include bounding info from descendants as well (true by default).
  15032. */
  15033. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  15034. if (includeDescendants === void 0) { includeDescendants = true; }
  15035. this.computeWorldMatrix(true);
  15036. var min;
  15037. var max;
  15038. var boundingInfo = this.getBoundingInfo();
  15039. if (!this.subMeshes) {
  15040. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15041. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  15042. }
  15043. else {
  15044. min = boundingInfo.boundingBox.minimumWorld;
  15045. max = boundingInfo.boundingBox.maximumWorld;
  15046. }
  15047. if (includeDescendants) {
  15048. var descendants = this.getDescendants(false);
  15049. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  15050. var descendant = descendants_1[_i];
  15051. var childMesh = descendant;
  15052. childMesh.computeWorldMatrix(true);
  15053. //make sure we have the needed params to get mix and max
  15054. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  15055. continue;
  15056. }
  15057. var childBoundingInfo = childMesh.getBoundingInfo();
  15058. var boundingBox = childBoundingInfo.boundingBox;
  15059. var minBox = boundingBox.minimumWorld;
  15060. var maxBox = boundingBox.maximumWorld;
  15061. BABYLON.Tools.CheckExtends(minBox, min, max);
  15062. BABYLON.Tools.CheckExtends(maxBox, min, max);
  15063. }
  15064. }
  15065. return {
  15066. min: min,
  15067. max: max
  15068. };
  15069. };
  15070. /**
  15071. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  15072. * Returns the AbstractMesh.
  15073. */
  15074. AbstractMesh.prototype._updateBoundingInfo = function () {
  15075. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  15076. this._boundingInfo.update(this.worldMatrixFromCache);
  15077. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  15078. return this;
  15079. };
  15080. /**
  15081. * Update a mesh's children BoundingInfo objects only.
  15082. * Returns the AbstractMesh.
  15083. */
  15084. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  15085. if (!this.subMeshes) {
  15086. return this;
  15087. }
  15088. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  15089. var subMesh = this.subMeshes[subIndex];
  15090. if (!subMesh.IsGlobal) {
  15091. subMesh.updateBoundingInfo(matrix);
  15092. }
  15093. }
  15094. return this;
  15095. };
  15096. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  15097. // Bounding info
  15098. this._updateBoundingInfo();
  15099. };
  15100. /**
  15101. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  15102. * A mesh is in the frustum if its bounding box intersects the frustum.
  15103. * Boolean returned.
  15104. */
  15105. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  15106. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  15107. };
  15108. /**
  15109. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  15110. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  15111. * Boolean returned.
  15112. */
  15113. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15114. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  15115. ;
  15116. };
  15117. /**
  15118. * True if the mesh intersects another mesh or a SolidParticle object.
  15119. * 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)
  15120. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  15121. * Returns a boolean.
  15122. */
  15123. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  15124. if (precise === void 0) { precise = false; }
  15125. if (!this._boundingInfo || !mesh._boundingInfo) {
  15126. return false;
  15127. }
  15128. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  15129. return true;
  15130. }
  15131. if (includeDescendants) {
  15132. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  15133. var child = _a[_i];
  15134. if (child.intersectsMesh(mesh, precise, true)) {
  15135. return true;
  15136. }
  15137. }
  15138. }
  15139. return false;
  15140. };
  15141. /**
  15142. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  15143. * Returns a boolean.
  15144. */
  15145. AbstractMesh.prototype.intersectsPoint = function (point) {
  15146. if (!this._boundingInfo) {
  15147. return false;
  15148. }
  15149. return this._boundingInfo.intersectsPoint(point);
  15150. };
  15151. AbstractMesh.prototype.getPhysicsImpostor = function () {
  15152. return this.physicsImpostor;
  15153. };
  15154. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  15155. if (camera === void 0) { camera = null; }
  15156. if (!camera) {
  15157. camera = this.getScene().activeCamera;
  15158. }
  15159. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  15160. };
  15161. /**
  15162. * Returns the distance from the mesh to the active camera.
  15163. * Returns a float.
  15164. */
  15165. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  15166. if (camera === void 0) { camera = null; }
  15167. if (!camera) {
  15168. camera = this.getScene().activeCamera;
  15169. }
  15170. return this.absolutePosition.subtract(camera.position).length();
  15171. };
  15172. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  15173. if (!this.physicsImpostor) {
  15174. return this;
  15175. }
  15176. this.physicsImpostor.applyImpulse(force, contactPoint);
  15177. return this;
  15178. };
  15179. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  15180. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  15181. return this;
  15182. }
  15183. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  15184. mainPivot: pivot1,
  15185. connectedPivot: pivot2,
  15186. nativeParams: options
  15187. });
  15188. return this;
  15189. };
  15190. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  15191. // Collisions
  15192. /**
  15193. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  15194. * Default `false`.
  15195. */
  15196. get: function () {
  15197. return this._checkCollisions;
  15198. },
  15199. set: function (collisionEnabled) {
  15200. this._checkCollisions = collisionEnabled;
  15201. if (this.getScene().workerCollisions) {
  15202. this.getScene().collisionCoordinator.onMeshUpdated(this);
  15203. }
  15204. },
  15205. enumerable: true,
  15206. configurable: true
  15207. });
  15208. Object.defineProperty(AbstractMesh.prototype, "collider", {
  15209. /**
  15210. * Gets Collider object used to compute collisions (not physics)
  15211. */
  15212. get: function () {
  15213. return this._collider;
  15214. },
  15215. enumerable: true,
  15216. configurable: true
  15217. });
  15218. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  15219. var globalPosition = this.getAbsolutePosition();
  15220. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  15221. if (!this._collider) {
  15222. this._collider = new BABYLON.Collider();
  15223. }
  15224. this._collider._radius = this.ellipsoid;
  15225. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  15226. return this;
  15227. };
  15228. // Submeshes octree
  15229. /**
  15230. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  15231. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  15232. * Returns an Octree of submeshes.
  15233. */
  15234. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  15235. if (maxCapacity === void 0) { maxCapacity = 64; }
  15236. if (maxDepth === void 0) { maxDepth = 2; }
  15237. if (!this._submeshesOctree) {
  15238. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  15239. }
  15240. this.computeWorldMatrix(true);
  15241. var boundingInfo = this.getBoundingInfo();
  15242. // Update octree
  15243. var bbox = boundingInfo.boundingBox;
  15244. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  15245. return this._submeshesOctree;
  15246. };
  15247. // Collisions
  15248. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  15249. this._generatePointsArray();
  15250. if (!this._positions) {
  15251. return this;
  15252. }
  15253. // Transformation
  15254. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  15255. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  15256. subMesh._lastColliderWorldVertices = [];
  15257. subMesh._trianglePlanes = [];
  15258. var start = subMesh.verticesStart;
  15259. var end = (subMesh.verticesStart + subMesh.verticesCount);
  15260. for (var i = start; i < end; i++) {
  15261. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  15262. }
  15263. }
  15264. // Collide
  15265. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  15266. if (collider.collisionFound) {
  15267. collider.collidedMesh = this;
  15268. }
  15269. return this;
  15270. };
  15271. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  15272. var subMeshes;
  15273. var len;
  15274. // Octrees
  15275. if (this._submeshesOctree && this.useOctreeForCollisions) {
  15276. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  15277. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  15278. len = intersections.length;
  15279. subMeshes = intersections.data;
  15280. }
  15281. else {
  15282. subMeshes = this.subMeshes;
  15283. len = subMeshes.length;
  15284. }
  15285. for (var index = 0; index < len; index++) {
  15286. var subMesh = subMeshes[index];
  15287. // Bounding test
  15288. if (len > 1 && !subMesh._checkCollision(collider))
  15289. continue;
  15290. this._collideForSubMesh(subMesh, transformMatrix, collider);
  15291. }
  15292. return this;
  15293. };
  15294. AbstractMesh.prototype._checkCollision = function (collider) {
  15295. // Bounding box test
  15296. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  15297. return this;
  15298. // Transformation matrix
  15299. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  15300. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  15301. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  15302. return this;
  15303. };
  15304. // Picking
  15305. AbstractMesh.prototype._generatePointsArray = function () {
  15306. return false;
  15307. };
  15308. /**
  15309. * Checks if the passed Ray intersects with the mesh.
  15310. * Returns an object PickingInfo.
  15311. */
  15312. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  15313. var pickingInfo = new BABYLON.PickingInfo();
  15314. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  15315. return pickingInfo;
  15316. }
  15317. if (!this._generatePointsArray()) {
  15318. return pickingInfo;
  15319. }
  15320. var intersectInfo = null;
  15321. // Octrees
  15322. var subMeshes;
  15323. var len;
  15324. if (this._submeshesOctree && this.useOctreeForPicking) {
  15325. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  15326. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  15327. len = intersections.length;
  15328. subMeshes = intersections.data;
  15329. }
  15330. else {
  15331. subMeshes = this.subMeshes;
  15332. len = subMeshes.length;
  15333. }
  15334. for (var index = 0; index < len; index++) {
  15335. var subMesh = subMeshes[index];
  15336. // Bounding test
  15337. if (len > 1 && !subMesh.canIntersects(ray))
  15338. continue;
  15339. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  15340. if (currentIntersectInfo) {
  15341. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  15342. intersectInfo = currentIntersectInfo;
  15343. intersectInfo.subMeshId = index;
  15344. if (fastCheck) {
  15345. break;
  15346. }
  15347. }
  15348. }
  15349. }
  15350. if (intersectInfo) {
  15351. // Get picked point
  15352. var world = this.getWorldMatrix();
  15353. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  15354. var direction = ray.direction.clone();
  15355. direction = direction.scale(intersectInfo.distance);
  15356. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  15357. var pickedPoint = worldOrigin.add(worldDirection);
  15358. // Return result
  15359. pickingInfo.hit = true;
  15360. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  15361. pickingInfo.pickedPoint = pickedPoint;
  15362. pickingInfo.pickedMesh = this;
  15363. pickingInfo.bu = intersectInfo.bu || 0;
  15364. pickingInfo.bv = intersectInfo.bv || 0;
  15365. pickingInfo.faceId = intersectInfo.faceId;
  15366. pickingInfo.subMeshId = intersectInfo.subMeshId;
  15367. return pickingInfo;
  15368. }
  15369. return pickingInfo;
  15370. };
  15371. /**
  15372. * Clones the mesh, used by the class Mesh.
  15373. * Just returns `null` for an AbstractMesh.
  15374. */
  15375. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15376. return null;
  15377. };
  15378. /**
  15379. * Disposes all the mesh submeshes.
  15380. * Returns the AbstractMesh.
  15381. */
  15382. AbstractMesh.prototype.releaseSubMeshes = function () {
  15383. if (this.subMeshes) {
  15384. while (this.subMeshes.length) {
  15385. this.subMeshes[0].dispose();
  15386. }
  15387. }
  15388. else {
  15389. this.subMeshes = new Array();
  15390. }
  15391. return this;
  15392. };
  15393. /**
  15394. * Disposes the AbstractMesh.
  15395. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  15396. * Returns nothing.
  15397. */
  15398. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  15399. var _this = this;
  15400. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  15401. var index;
  15402. // Action manager
  15403. if (this.actionManager) {
  15404. this.actionManager.dispose();
  15405. this.actionManager = null;
  15406. }
  15407. // Skeleton
  15408. this.skeleton = null;
  15409. // Physics
  15410. if (this.physicsImpostor) {
  15411. this.physicsImpostor.dispose();
  15412. }
  15413. // Intersections in progress
  15414. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  15415. var other = this._intersectionsInProgress[index];
  15416. var pos = other._intersectionsInProgress.indexOf(this);
  15417. other._intersectionsInProgress.splice(pos, 1);
  15418. }
  15419. this._intersectionsInProgress = [];
  15420. // Lights
  15421. var lights = this.getScene().lights;
  15422. lights.forEach(function (light) {
  15423. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  15424. if (meshIndex !== -1) {
  15425. light.includedOnlyMeshes.splice(meshIndex, 1);
  15426. }
  15427. meshIndex = light.excludedMeshes.indexOf(_this);
  15428. if (meshIndex !== -1) {
  15429. light.excludedMeshes.splice(meshIndex, 1);
  15430. }
  15431. // Shadow generators
  15432. var generator = light.getShadowGenerator();
  15433. if (generator) {
  15434. var shadowMap = generator.getShadowMap();
  15435. if (shadowMap && shadowMap.renderList) {
  15436. meshIndex = shadowMap.renderList.indexOf(_this);
  15437. if (meshIndex !== -1) {
  15438. shadowMap.renderList.splice(meshIndex, 1);
  15439. }
  15440. }
  15441. }
  15442. });
  15443. // Edges
  15444. if (this._edgesRenderer) {
  15445. this._edgesRenderer.dispose();
  15446. this._edgesRenderer = null;
  15447. }
  15448. // SubMeshes
  15449. if (this.getClassName() !== "InstancedMesh") {
  15450. this.releaseSubMeshes();
  15451. }
  15452. // Octree
  15453. var sceneOctree = this.getScene().selectionOctree;
  15454. if (sceneOctree) {
  15455. var index = sceneOctree.dynamicContent.indexOf(this);
  15456. if (index !== -1) {
  15457. sceneOctree.dynamicContent.splice(index, 1);
  15458. }
  15459. }
  15460. // Query
  15461. var engine = this.getScene().getEngine();
  15462. if (this._occlusionQuery) {
  15463. this._isOcclusionQueryInProgress = false;
  15464. engine.deleteQuery(this._occlusionQuery);
  15465. this._occlusionQuery = null;
  15466. }
  15467. // Engine
  15468. engine.wipeCaches();
  15469. // Remove from scene
  15470. this.getScene().removeMesh(this);
  15471. if (disposeMaterialAndTextures) {
  15472. if (this.material) {
  15473. this.material.dispose(false, true);
  15474. }
  15475. }
  15476. if (!doNotRecurse) {
  15477. // Particles
  15478. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  15479. if (this.getScene().particleSystems[index].emitter === this) {
  15480. this.getScene().particleSystems[index].dispose();
  15481. index--;
  15482. }
  15483. }
  15484. }
  15485. // facet data
  15486. if (this._facetDataEnabled) {
  15487. this.disableFacetData();
  15488. }
  15489. this.onAfterWorldMatrixUpdateObservable.clear();
  15490. this.onCollideObservable.clear();
  15491. this.onCollisionPositionChangeObservable.clear();
  15492. this._isDisposed = true;
  15493. _super.prototype.dispose.call(this, doNotRecurse);
  15494. };
  15495. /**
  15496. * Adds the passed mesh as a child to the current mesh.
  15497. * Returns the AbstractMesh.
  15498. */
  15499. AbstractMesh.prototype.addChild = function (mesh) {
  15500. mesh.setParent(this);
  15501. return this;
  15502. };
  15503. /**
  15504. * Removes the passed mesh from the current mesh children list.
  15505. * Returns the AbstractMesh.
  15506. */
  15507. AbstractMesh.prototype.removeChild = function (mesh) {
  15508. mesh.setParent(null);
  15509. return this;
  15510. };
  15511. // Facet data
  15512. /**
  15513. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  15514. * Returns the AbstractMesh.
  15515. */
  15516. AbstractMesh.prototype._initFacetData = function () {
  15517. if (!this._facetNormals) {
  15518. this._facetNormals = new Array();
  15519. }
  15520. if (!this._facetPositions) {
  15521. this._facetPositions = new Array();
  15522. }
  15523. if (!this._facetPartitioning) {
  15524. this._facetPartitioning = new Array();
  15525. }
  15526. this._facetNb = (this.getIndices().length / 3) | 0;
  15527. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  15528. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  15529. for (var f = 0; f < this._facetNb; f++) {
  15530. this._facetNormals[f] = BABYLON.Vector3.Zero();
  15531. this._facetPositions[f] = BABYLON.Vector3.Zero();
  15532. }
  15533. this._facetDataEnabled = true;
  15534. return this;
  15535. };
  15536. /**
  15537. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  15538. * This method can be called within the render loop.
  15539. * 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.
  15540. * Returns the AbstractMesh.
  15541. */
  15542. AbstractMesh.prototype.updateFacetData = function () {
  15543. if (!this._facetDataEnabled) {
  15544. this._initFacetData();
  15545. }
  15546. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15547. var indices = this.getIndices();
  15548. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15549. var bInfo = this.getBoundingInfo();
  15550. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  15551. // init arrays, matrix and sort function on first call
  15552. this._facetDepthSortEnabled = true;
  15553. if (indices instanceof Uint16Array) {
  15554. this._depthSortedIndices = new Uint16Array(indices);
  15555. }
  15556. else if (indices instanceof Uint32Array) {
  15557. this._depthSortedIndices = new Uint32Array(indices);
  15558. }
  15559. else {
  15560. var needs32bits = false;
  15561. for (var i = 0; i < indices.length; i++) {
  15562. if (indices[i] > 65535) {
  15563. needs32bits = true;
  15564. break;
  15565. }
  15566. }
  15567. if (needs32bits) {
  15568. this._depthSortedIndices = new Uint32Array(indices);
  15569. }
  15570. else {
  15571. this._depthSortedIndices = new Uint16Array(indices);
  15572. }
  15573. }
  15574. this._facetDepthSortFunction = function (f1, f2) {
  15575. return (f2.sqDistance - f1.sqDistance);
  15576. };
  15577. if (!this._facetDepthSortFrom) {
  15578. var camera = this.getScene().activeCamera;
  15579. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  15580. }
  15581. this._depthSortedFacets = [];
  15582. for (var f = 0; f < this._facetNb; f++) {
  15583. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  15584. this._depthSortedFacets.push(depthSortedFacet);
  15585. }
  15586. this._invertedMatrix = BABYLON.Matrix.Identity();
  15587. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  15588. }
  15589. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  15590. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  15591. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  15592. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  15593. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  15594. this._subDiv.max = this._partitioningSubdivisions;
  15595. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  15596. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  15597. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  15598. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  15599. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  15600. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  15601. // set the parameters for ComputeNormals()
  15602. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  15603. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  15604. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  15605. this._facetParameters.bInfo = bInfo;
  15606. this._facetParameters.bbSize = this._bbSize;
  15607. this._facetParameters.subDiv = this._subDiv;
  15608. this._facetParameters.ratio = this.partitioningBBoxRatio;
  15609. this._facetParameters.depthSort = this._facetDepthSort;
  15610. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  15611. this.computeWorldMatrix(true);
  15612. this._worldMatrix.invertToRef(this._invertedMatrix);
  15613. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  15614. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  15615. }
  15616. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  15617. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  15618. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  15619. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  15620. var l = (this._depthSortedIndices.length / 3) | 0;
  15621. for (var f = 0; f < l; f++) {
  15622. var sind = this._depthSortedFacets[f].ind;
  15623. this._depthSortedIndices[f * 3] = indices[sind];
  15624. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  15625. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  15626. }
  15627. this.updateIndices(this._depthSortedIndices);
  15628. }
  15629. return this;
  15630. };
  15631. /**
  15632. * Returns the facetLocalNormals array.
  15633. * The normals are expressed in the mesh local space.
  15634. */
  15635. AbstractMesh.prototype.getFacetLocalNormals = function () {
  15636. if (!this._facetNormals) {
  15637. this.updateFacetData();
  15638. }
  15639. return this._facetNormals;
  15640. };
  15641. /**
  15642. * Returns the facetLocalPositions array.
  15643. * The facet positions are expressed in the mesh local space.
  15644. */
  15645. AbstractMesh.prototype.getFacetLocalPositions = function () {
  15646. if (!this._facetPositions) {
  15647. this.updateFacetData();
  15648. }
  15649. return this._facetPositions;
  15650. };
  15651. /**
  15652. * Returns the facetLocalPartioning array.
  15653. */
  15654. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  15655. if (!this._facetPartitioning) {
  15656. this.updateFacetData();
  15657. }
  15658. return this._facetPartitioning;
  15659. };
  15660. /**
  15661. * Returns the i-th facet position in the world system.
  15662. * This method allocates a new Vector3 per call.
  15663. */
  15664. AbstractMesh.prototype.getFacetPosition = function (i) {
  15665. var pos = BABYLON.Vector3.Zero();
  15666. this.getFacetPositionToRef(i, pos);
  15667. return pos;
  15668. };
  15669. /**
  15670. * Sets the reference Vector3 with the i-th facet position in the world system.
  15671. * Returns the AbstractMesh.
  15672. */
  15673. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  15674. var localPos = (this.getFacetLocalPositions())[i];
  15675. var world = this.getWorldMatrix();
  15676. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  15677. return this;
  15678. };
  15679. /**
  15680. * Returns the i-th facet normal in the world system.
  15681. * This method allocates a new Vector3 per call.
  15682. */
  15683. AbstractMesh.prototype.getFacetNormal = function (i) {
  15684. var norm = BABYLON.Vector3.Zero();
  15685. this.getFacetNormalToRef(i, norm);
  15686. return norm;
  15687. };
  15688. /**
  15689. * Sets the reference Vector3 with the i-th facet normal in the world system.
  15690. * Returns the AbstractMesh.
  15691. */
  15692. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  15693. var localNorm = (this.getFacetLocalNormals())[i];
  15694. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  15695. return this;
  15696. };
  15697. /**
  15698. * 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).
  15699. */
  15700. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  15701. var bInfo = this.getBoundingInfo();
  15702. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  15703. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  15704. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  15705. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  15706. return null;
  15707. }
  15708. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  15709. };
  15710. /**
  15711. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  15712. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  15713. * 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.
  15714. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  15715. * 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.
  15716. */
  15717. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  15718. if (checkFace === void 0) { checkFace = false; }
  15719. if (facing === void 0) { facing = true; }
  15720. var world = this.getWorldMatrix();
  15721. var invMat = BABYLON.Tmp.Matrix[5];
  15722. world.invertToRef(invMat);
  15723. var invVect = BABYLON.Tmp.Vector3[8];
  15724. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  15725. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  15726. if (projected) {
  15727. // tranform the local computed projected vector to world coordinates
  15728. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  15729. }
  15730. return closest;
  15731. };
  15732. /**
  15733. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  15734. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  15735. * 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.
  15736. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  15737. * 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.
  15738. */
  15739. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  15740. if (checkFace === void 0) { checkFace = false; }
  15741. if (facing === void 0) { facing = true; }
  15742. var closest = null;
  15743. var tmpx = 0.0;
  15744. var tmpy = 0.0;
  15745. var tmpz = 0.0;
  15746. var d = 0.0; // tmp dot facet normal * facet position
  15747. var t0 = 0.0;
  15748. var projx = 0.0;
  15749. var projy = 0.0;
  15750. var projz = 0.0;
  15751. // Get all the facets in the same partitioning block than (x, y, z)
  15752. var facetPositions = this.getFacetLocalPositions();
  15753. var facetNormals = this.getFacetLocalNormals();
  15754. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  15755. if (!facetsInBlock) {
  15756. return null;
  15757. }
  15758. // Get the closest facet to (x, y, z)
  15759. var shortest = Number.MAX_VALUE; // init distance vars
  15760. var tmpDistance = shortest;
  15761. var fib; // current facet in the block
  15762. var norm; // current facet normal
  15763. var p0; // current facet barycenter position
  15764. // loop on all the facets in the current partitioning block
  15765. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  15766. fib = facetsInBlock[idx];
  15767. norm = facetNormals[fib];
  15768. p0 = facetPositions[fib];
  15769. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  15770. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  15771. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  15772. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  15773. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  15774. projx = x + norm.x * t0;
  15775. projy = y + norm.y * t0;
  15776. projz = z + norm.z * t0;
  15777. tmpx = projx - x;
  15778. tmpy = projy - y;
  15779. tmpz = projz - z;
  15780. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  15781. if (tmpDistance < shortest) {
  15782. shortest = tmpDistance;
  15783. closest = fib;
  15784. if (projected) {
  15785. projected.x = projx;
  15786. projected.y = projy;
  15787. projected.z = projz;
  15788. }
  15789. }
  15790. }
  15791. }
  15792. return closest;
  15793. };
  15794. /**
  15795. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  15796. */
  15797. AbstractMesh.prototype.getFacetDataParameters = function () {
  15798. return this._facetParameters;
  15799. };
  15800. /**
  15801. * Disables the feature FacetData and frees the related memory.
  15802. * Returns the AbstractMesh.
  15803. */
  15804. AbstractMesh.prototype.disableFacetData = function () {
  15805. if (this._facetDataEnabled) {
  15806. this._facetDataEnabled = false;
  15807. this._facetPositions = new Array();
  15808. this._facetNormals = new Array();
  15809. this._facetPartitioning = new Array();
  15810. this._facetParameters = null;
  15811. this._depthSortedIndices = new Uint32Array(0);
  15812. }
  15813. return this;
  15814. };
  15815. /**
  15816. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  15817. * Returns the mesh.
  15818. */
  15819. AbstractMesh.prototype.updateIndices = function (indices) {
  15820. return this;
  15821. };
  15822. /**
  15823. * The mesh Geometry. Actually used by the Mesh object.
  15824. * Returns a blank geometry object.
  15825. */
  15826. /**
  15827. * Creates new normals data for the mesh.
  15828. * @param updatable.
  15829. */
  15830. AbstractMesh.prototype.createNormals = function (updatable) {
  15831. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15832. var indices = this.getIndices();
  15833. var normals;
  15834. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15835. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15836. }
  15837. else {
  15838. normals = [];
  15839. }
  15840. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  15841. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  15842. };
  15843. /**
  15844. * Align the mesh with a normal.
  15845. * Returns the mesh.
  15846. */
  15847. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  15848. if (!upDirection) {
  15849. upDirection = BABYLON.Axis.Y;
  15850. }
  15851. var axisX = BABYLON.Tmp.Vector3[0];
  15852. var axisZ = BABYLON.Tmp.Vector3[1];
  15853. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  15854. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  15855. if (this.rotationQuaternion) {
  15856. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  15857. }
  15858. else {
  15859. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  15860. }
  15861. return this;
  15862. };
  15863. AbstractMesh.prototype.checkOcclusionQuery = function () {
  15864. var engine = this.getEngine();
  15865. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  15866. this._isOccluded = false;
  15867. return;
  15868. }
  15869. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  15870. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  15871. if (isOcclusionQueryAvailable) {
  15872. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  15873. this._isOcclusionQueryInProgress = false;
  15874. this._occlusionInternalRetryCounter = 0;
  15875. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  15876. }
  15877. else {
  15878. this._occlusionInternalRetryCounter++;
  15879. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  15880. this._isOcclusionQueryInProgress = false;
  15881. this._occlusionInternalRetryCounter = 0;
  15882. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  15883. // if strict continue the last state of the object.
  15884. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  15885. }
  15886. else {
  15887. return;
  15888. }
  15889. }
  15890. }
  15891. var scene = this.getScene();
  15892. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  15893. if (!this._occlusionQuery) {
  15894. this._occlusionQuery = engine.createQuery();
  15895. }
  15896. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  15897. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  15898. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  15899. this._isOcclusionQueryInProgress = true;
  15900. };
  15901. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  15902. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  15903. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  15904. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  15905. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  15906. return AbstractMesh;
  15907. }(BABYLON.TransformNode));
  15908. BABYLON.AbstractMesh = AbstractMesh;
  15909. })(BABYLON || (BABYLON = {}));
  15910. //# sourceMappingURL=babylon.abstractMesh.js.map
  15911. var BABYLON;
  15912. (function (BABYLON) {
  15913. var Light = /** @class */ (function (_super) {
  15914. __extends(Light, _super);
  15915. /**
  15916. * Creates a Light object in the scene.
  15917. * Documentation : http://doc.babylonjs.com/tutorials/lights
  15918. */
  15919. function Light(name, scene) {
  15920. var _this = _super.call(this, name, scene) || this;
  15921. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  15922. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  15923. _this.intensity = 1.0;
  15924. _this.range = Number.MAX_VALUE;
  15925. /**
  15926. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  15927. * of light.
  15928. */
  15929. _this._photometricScale = 1.0;
  15930. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  15931. _this._radius = 0.00001;
  15932. _this.renderPriority = 0;
  15933. /**
  15934. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  15935. * the current shadow generator.
  15936. */
  15937. _this.shadowEnabled = true;
  15938. _this._excludeWithLayerMask = 0;
  15939. _this._includeOnlyWithLayerMask = 0;
  15940. _this._lightmapMode = 0;
  15941. _this._excludedMeshesIds = new Array();
  15942. _this._includedOnlyMeshesIds = new Array();
  15943. _this.getScene().addLight(_this);
  15944. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  15945. _this._buildUniformLayout();
  15946. _this.includedOnlyMeshes = new Array();
  15947. _this.excludedMeshes = new Array();
  15948. _this._resyncMeshes();
  15949. return _this;
  15950. }
  15951. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  15952. /**
  15953. * If every light affecting the material is in this lightmapMode,
  15954. * material.lightmapTexture adds or multiplies
  15955. * (depends on material.useLightmapAsShadowmap)
  15956. * after every other light calculations.
  15957. */
  15958. get: function () {
  15959. return Light._LIGHTMAP_DEFAULT;
  15960. },
  15961. enumerable: true,
  15962. configurable: true
  15963. });
  15964. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  15965. /**
  15966. * material.lightmapTexture as only diffuse lighting from this light
  15967. * adds pnly specular lighting from this light
  15968. * adds dynamic shadows
  15969. */
  15970. get: function () {
  15971. return Light._LIGHTMAP_SPECULAR;
  15972. },
  15973. enumerable: true,
  15974. configurable: true
  15975. });
  15976. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  15977. /**
  15978. * material.lightmapTexture as only lighting
  15979. * no light calculation from this light
  15980. * only adds dynamic shadows from this light
  15981. */
  15982. get: function () {
  15983. return Light._LIGHTMAP_SHADOWSONLY;
  15984. },
  15985. enumerable: true,
  15986. configurable: true
  15987. });
  15988. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  15989. /**
  15990. * Each light type uses the default quantity according to its type:
  15991. * point/spot lights use luminous intensity
  15992. * directional lights use illuminance
  15993. */
  15994. get: function () {
  15995. return Light._INTENSITYMODE_AUTOMATIC;
  15996. },
  15997. enumerable: true,
  15998. configurable: true
  15999. });
  16000. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  16001. /**
  16002. * lumen (lm)
  16003. */
  16004. get: function () {
  16005. return Light._INTENSITYMODE_LUMINOUSPOWER;
  16006. },
  16007. enumerable: true,
  16008. configurable: true
  16009. });
  16010. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  16011. /**
  16012. * candela (lm/sr)
  16013. */
  16014. get: function () {
  16015. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  16016. },
  16017. enumerable: true,
  16018. configurable: true
  16019. });
  16020. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  16021. /**
  16022. * lux (lm/m^2)
  16023. */
  16024. get: function () {
  16025. return Light._INTENSITYMODE_ILLUMINANCE;
  16026. },
  16027. enumerable: true,
  16028. configurable: true
  16029. });
  16030. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  16031. /**
  16032. * nit (cd/m^2)
  16033. */
  16034. get: function () {
  16035. return Light._INTENSITYMODE_LUMINANCE;
  16036. },
  16037. enumerable: true,
  16038. configurable: true
  16039. });
  16040. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  16041. /**
  16042. * Light type const id of the point light.
  16043. */
  16044. get: function () {
  16045. return Light._LIGHTTYPEID_POINTLIGHT;
  16046. },
  16047. enumerable: true,
  16048. configurable: true
  16049. });
  16050. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  16051. /**
  16052. * Light type const id of the directional light.
  16053. */
  16054. get: function () {
  16055. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  16056. },
  16057. enumerable: true,
  16058. configurable: true
  16059. });
  16060. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  16061. /**
  16062. * Light type const id of the spot light.
  16063. */
  16064. get: function () {
  16065. return Light._LIGHTTYPEID_SPOTLIGHT;
  16066. },
  16067. enumerable: true,
  16068. configurable: true
  16069. });
  16070. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  16071. /**
  16072. * Light type const id of the hemispheric light.
  16073. */
  16074. get: function () {
  16075. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  16076. },
  16077. enumerable: true,
  16078. configurable: true
  16079. });
  16080. Object.defineProperty(Light.prototype, "intensityMode", {
  16081. /**
  16082. * Gets the photometric scale used to interpret the intensity.
  16083. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  16084. */
  16085. get: function () {
  16086. return this._intensityMode;
  16087. },
  16088. /**
  16089. * Sets the photometric scale used to interpret the intensity.
  16090. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  16091. */
  16092. set: function (value) {
  16093. this._intensityMode = value;
  16094. this._computePhotometricScale();
  16095. },
  16096. enumerable: true,
  16097. configurable: true
  16098. });
  16099. ;
  16100. ;
  16101. Object.defineProperty(Light.prototype, "radius", {
  16102. /**
  16103. * Gets the light radius used by PBR Materials to simulate soft area lights.
  16104. */
  16105. get: function () {
  16106. return this._radius;
  16107. },
  16108. /**
  16109. * sets the light radius used by PBR Materials to simulate soft area lights.
  16110. */
  16111. set: function (value) {
  16112. this._radius = value;
  16113. this._computePhotometricScale();
  16114. },
  16115. enumerable: true,
  16116. configurable: true
  16117. });
  16118. ;
  16119. ;
  16120. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  16121. get: function () {
  16122. return this._includedOnlyMeshes;
  16123. },
  16124. set: function (value) {
  16125. this._includedOnlyMeshes = value;
  16126. this._hookArrayForIncludedOnly(value);
  16127. },
  16128. enumerable: true,
  16129. configurable: true
  16130. });
  16131. Object.defineProperty(Light.prototype, "excludedMeshes", {
  16132. get: function () {
  16133. return this._excludedMeshes;
  16134. },
  16135. set: function (value) {
  16136. this._excludedMeshes = value;
  16137. this._hookArrayForExcluded(value);
  16138. },
  16139. enumerable: true,
  16140. configurable: true
  16141. });
  16142. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  16143. get: function () {
  16144. return this._excludeWithLayerMask;
  16145. },
  16146. set: function (value) {
  16147. this._excludeWithLayerMask = value;
  16148. this._resyncMeshes();
  16149. },
  16150. enumerable: true,
  16151. configurable: true
  16152. });
  16153. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  16154. get: function () {
  16155. return this._includeOnlyWithLayerMask;
  16156. },
  16157. set: function (value) {
  16158. this._includeOnlyWithLayerMask = value;
  16159. this._resyncMeshes();
  16160. },
  16161. enumerable: true,
  16162. configurable: true
  16163. });
  16164. Object.defineProperty(Light.prototype, "lightmapMode", {
  16165. get: function () {
  16166. return this._lightmapMode;
  16167. },
  16168. set: function (value) {
  16169. if (this._lightmapMode === value) {
  16170. return;
  16171. }
  16172. this._lightmapMode = value;
  16173. this._markMeshesAsLightDirty();
  16174. },
  16175. enumerable: true,
  16176. configurable: true
  16177. });
  16178. Light.prototype._buildUniformLayout = function () {
  16179. // Overridden
  16180. };
  16181. /**
  16182. * Returns the string "Light".
  16183. */
  16184. Light.prototype.getClassName = function () {
  16185. return "Light";
  16186. };
  16187. /**
  16188. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16189. */
  16190. Light.prototype.toString = function (fullDetails) {
  16191. var ret = "Name: " + this.name;
  16192. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  16193. if (this.animations) {
  16194. for (var i = 0; i < this.animations.length; i++) {
  16195. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  16196. }
  16197. }
  16198. if (fullDetails) {
  16199. }
  16200. return ret;
  16201. };
  16202. /**
  16203. * Set the enabled state of this node.
  16204. * @param {boolean} value - the new enabled state
  16205. * @see isEnabled
  16206. */
  16207. Light.prototype.setEnabled = function (value) {
  16208. _super.prototype.setEnabled.call(this, value);
  16209. this._resyncMeshes();
  16210. };
  16211. /**
  16212. * Returns the Light associated shadow generator.
  16213. */
  16214. Light.prototype.getShadowGenerator = function () {
  16215. return this._shadowGenerator;
  16216. };
  16217. /**
  16218. * Returns a Vector3, the absolute light position in the World.
  16219. */
  16220. Light.prototype.getAbsolutePosition = function () {
  16221. return BABYLON.Vector3.Zero();
  16222. };
  16223. Light.prototype.transferToEffect = function (effect, lightIndex) {
  16224. };
  16225. Light.prototype._getWorldMatrix = function () {
  16226. return BABYLON.Matrix.Identity();
  16227. };
  16228. /**
  16229. * Boolean : True if the light will affect the passed mesh.
  16230. */
  16231. Light.prototype.canAffectMesh = function (mesh) {
  16232. if (!mesh) {
  16233. return true;
  16234. }
  16235. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  16236. return false;
  16237. }
  16238. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  16239. return false;
  16240. }
  16241. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  16242. return false;
  16243. }
  16244. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  16245. return false;
  16246. }
  16247. return true;
  16248. };
  16249. /**
  16250. * Returns the light World matrix.
  16251. */
  16252. Light.prototype.getWorldMatrix = function () {
  16253. this._currentRenderId = this.getScene().getRenderId();
  16254. var worldMatrix = this._getWorldMatrix();
  16255. if (this.parent && this.parent.getWorldMatrix) {
  16256. if (!this._parentedWorldMatrix) {
  16257. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  16258. }
  16259. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  16260. this._markSyncedWithParent();
  16261. return this._parentedWorldMatrix;
  16262. }
  16263. return worldMatrix;
  16264. };
  16265. /**
  16266. * Sort function to order lights for rendering.
  16267. * @param a First Light object to compare to second.
  16268. * @param b Second Light object to compare first.
  16269. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  16270. */
  16271. Light.compareLightsPriority = function (a, b) {
  16272. //shadow-casting lights have priority over non-shadow-casting lights
  16273. //the renderPrioirty is a secondary sort criterion
  16274. if (a.shadowEnabled !== b.shadowEnabled) {
  16275. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  16276. }
  16277. return b.renderPriority - a.renderPriority;
  16278. };
  16279. /**
  16280. * Disposes the light.
  16281. */
  16282. Light.prototype.dispose = function () {
  16283. if (this._shadowGenerator) {
  16284. this._shadowGenerator.dispose();
  16285. this._shadowGenerator = null;
  16286. }
  16287. // Animations
  16288. this.getScene().stopAnimation(this);
  16289. // Remove from meshes
  16290. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  16291. var mesh = _a[_i];
  16292. mesh._removeLightSource(this);
  16293. }
  16294. this._uniformBuffer.dispose();
  16295. // Remove from scene
  16296. this.getScene().removeLight(this);
  16297. _super.prototype.dispose.call(this);
  16298. };
  16299. /**
  16300. * Returns the light type ID (integer).
  16301. */
  16302. Light.prototype.getTypeID = function () {
  16303. return 0;
  16304. };
  16305. /**
  16306. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  16307. */
  16308. Light.prototype.getScaledIntensity = function () {
  16309. return this._photometricScale * this.intensity;
  16310. };
  16311. /**
  16312. * Returns a new Light object, named "name", from the current one.
  16313. */
  16314. Light.prototype.clone = function (name) {
  16315. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  16316. if (!constructor) {
  16317. return null;
  16318. }
  16319. return BABYLON.SerializationHelper.Clone(constructor, this);
  16320. };
  16321. /**
  16322. * Serializes the current light into a Serialization object.
  16323. * Returns the serialized object.
  16324. */
  16325. Light.prototype.serialize = function () {
  16326. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  16327. // Type
  16328. serializationObject.type = this.getTypeID();
  16329. // Parent
  16330. if (this.parent) {
  16331. serializationObject.parentId = this.parent.id;
  16332. }
  16333. // Inclusion / exclusions
  16334. if (this.excludedMeshes.length > 0) {
  16335. serializationObject.excludedMeshesIds = [];
  16336. this.excludedMeshes.forEach(function (mesh) {
  16337. serializationObject.excludedMeshesIds.push(mesh.id);
  16338. });
  16339. }
  16340. if (this.includedOnlyMeshes.length > 0) {
  16341. serializationObject.includedOnlyMeshesIds = [];
  16342. this.includedOnlyMeshes.forEach(function (mesh) {
  16343. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  16344. });
  16345. }
  16346. // Animations
  16347. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  16348. serializationObject.ranges = this.serializeAnimationRanges();
  16349. return serializationObject;
  16350. };
  16351. /**
  16352. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  16353. * This new light is named "name" and added to the passed scene.
  16354. */
  16355. Light.GetConstructorFromName = function (type, name, scene) {
  16356. switch (type) {
  16357. case 0:
  16358. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  16359. case 1:
  16360. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  16361. case 2:
  16362. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  16363. case 3:
  16364. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  16365. }
  16366. return null;
  16367. };
  16368. /**
  16369. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  16370. */
  16371. Light.Parse = function (parsedLight, scene) {
  16372. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  16373. if (!constructor) {
  16374. return null;
  16375. }
  16376. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  16377. // Inclusion / exclusions
  16378. if (parsedLight.excludedMeshesIds) {
  16379. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  16380. }
  16381. if (parsedLight.includedOnlyMeshesIds) {
  16382. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  16383. }
  16384. // Parent
  16385. if (parsedLight.parentId) {
  16386. light._waitingParentId = parsedLight.parentId;
  16387. }
  16388. // Animations
  16389. if (parsedLight.animations) {
  16390. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  16391. var parsedAnimation = parsedLight.animations[animationIndex];
  16392. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16393. }
  16394. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  16395. }
  16396. if (parsedLight.autoAnimate) {
  16397. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  16398. }
  16399. return light;
  16400. };
  16401. Light.prototype._hookArrayForExcluded = function (array) {
  16402. var _this = this;
  16403. var oldPush = array.push;
  16404. array.push = function () {
  16405. var items = [];
  16406. for (var _i = 0; _i < arguments.length; _i++) {
  16407. items[_i] = arguments[_i];
  16408. }
  16409. var result = oldPush.apply(array, items);
  16410. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  16411. var item = items_1[_a];
  16412. item._resyncLighSource(_this);
  16413. }
  16414. return result;
  16415. };
  16416. var oldSplice = array.splice;
  16417. array.splice = function (index, deleteCount) {
  16418. var deleted = oldSplice.apply(array, [index, deleteCount]);
  16419. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  16420. var item = deleted_1[_i];
  16421. item._resyncLighSource(_this);
  16422. }
  16423. return deleted;
  16424. };
  16425. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  16426. var item = array_1[_i];
  16427. item._resyncLighSource(this);
  16428. }
  16429. };
  16430. Light.prototype._hookArrayForIncludedOnly = function (array) {
  16431. var _this = this;
  16432. var oldPush = array.push;
  16433. array.push = function () {
  16434. var items = [];
  16435. for (var _i = 0; _i < arguments.length; _i++) {
  16436. items[_i] = arguments[_i];
  16437. }
  16438. var result = oldPush.apply(array, items);
  16439. _this._resyncMeshes();
  16440. return result;
  16441. };
  16442. var oldSplice = array.splice;
  16443. array.splice = function (index, deleteCount) {
  16444. var deleted = oldSplice.apply(array, [index, deleteCount]);
  16445. _this._resyncMeshes();
  16446. return deleted;
  16447. };
  16448. this._resyncMeshes();
  16449. };
  16450. Light.prototype._resyncMeshes = function () {
  16451. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  16452. var mesh = _a[_i];
  16453. mesh._resyncLighSource(this);
  16454. }
  16455. };
  16456. Light.prototype._markMeshesAsLightDirty = function () {
  16457. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  16458. var mesh = _a[_i];
  16459. if (mesh._lightSources.indexOf(this) !== -1) {
  16460. mesh._markSubMeshesAsLightDirty();
  16461. }
  16462. }
  16463. };
  16464. /**
  16465. * Recomputes the cached photometric scale if needed.
  16466. */
  16467. Light.prototype._computePhotometricScale = function () {
  16468. this._photometricScale = this._getPhotometricScale();
  16469. this.getScene().resetCachedMaterial();
  16470. };
  16471. /**
  16472. * Returns the Photometric Scale according to the light type and intensity mode.
  16473. */
  16474. Light.prototype._getPhotometricScale = function () {
  16475. var photometricScale = 0.0;
  16476. var lightTypeID = this.getTypeID();
  16477. //get photometric mode
  16478. var photometricMode = this.intensityMode;
  16479. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  16480. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  16481. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  16482. }
  16483. else {
  16484. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  16485. }
  16486. }
  16487. //compute photometric scale
  16488. switch (lightTypeID) {
  16489. case Light.LIGHTTYPEID_POINTLIGHT:
  16490. case Light.LIGHTTYPEID_SPOTLIGHT:
  16491. switch (photometricMode) {
  16492. case Light.INTENSITYMODE_LUMINOUSPOWER:
  16493. photometricScale = 1.0 / (4.0 * Math.PI);
  16494. break;
  16495. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  16496. photometricScale = 1.0;
  16497. break;
  16498. case Light.INTENSITYMODE_LUMINANCE:
  16499. photometricScale = this.radius * this.radius;
  16500. break;
  16501. }
  16502. break;
  16503. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  16504. switch (photometricMode) {
  16505. case Light.INTENSITYMODE_ILLUMINANCE:
  16506. photometricScale = 1.0;
  16507. break;
  16508. case Light.INTENSITYMODE_LUMINANCE:
  16509. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  16510. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  16511. var apexAngleRadians = this.radius;
  16512. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  16513. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  16514. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  16515. photometricScale = solidAngle;
  16516. break;
  16517. }
  16518. break;
  16519. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  16520. // No fall off in hemisperic light.
  16521. photometricScale = 1.0;
  16522. break;
  16523. }
  16524. return photometricScale;
  16525. };
  16526. Light.prototype._reorderLightsInScene = function () {
  16527. var scene = this.getScene();
  16528. if (this._renderPriority != 0) {
  16529. scene.requireLightSorting = true;
  16530. }
  16531. this.getScene().sortLightsByPriority();
  16532. };
  16533. //lightmapMode Consts
  16534. Light._LIGHTMAP_DEFAULT = 0;
  16535. Light._LIGHTMAP_SPECULAR = 1;
  16536. Light._LIGHTMAP_SHADOWSONLY = 2;
  16537. // Intensity Mode Consts
  16538. Light._INTENSITYMODE_AUTOMATIC = 0;
  16539. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  16540. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  16541. Light._INTENSITYMODE_ILLUMINANCE = 3;
  16542. Light._INTENSITYMODE_LUMINANCE = 4;
  16543. // Light types ids const.
  16544. Light._LIGHTTYPEID_POINTLIGHT = 0;
  16545. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  16546. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  16547. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  16548. __decorate([
  16549. BABYLON.serializeAsColor3()
  16550. ], Light.prototype, "diffuse", void 0);
  16551. __decorate([
  16552. BABYLON.serializeAsColor3()
  16553. ], Light.prototype, "specular", void 0);
  16554. __decorate([
  16555. BABYLON.serialize()
  16556. ], Light.prototype, "intensity", void 0);
  16557. __decorate([
  16558. BABYLON.serialize()
  16559. ], Light.prototype, "range", void 0);
  16560. __decorate([
  16561. BABYLON.serialize()
  16562. ], Light.prototype, "intensityMode", null);
  16563. __decorate([
  16564. BABYLON.serialize()
  16565. ], Light.prototype, "radius", null);
  16566. __decorate([
  16567. BABYLON.serialize()
  16568. ], Light.prototype, "_renderPriority", void 0);
  16569. __decorate([
  16570. BABYLON.expandToProperty("_reorderLightsInScene")
  16571. ], Light.prototype, "renderPriority", void 0);
  16572. __decorate([
  16573. BABYLON.serialize()
  16574. ], Light.prototype, "shadowEnabled", void 0);
  16575. __decorate([
  16576. BABYLON.serialize("excludeWithLayerMask")
  16577. ], Light.prototype, "_excludeWithLayerMask", void 0);
  16578. __decorate([
  16579. BABYLON.serialize("includeOnlyWithLayerMask")
  16580. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  16581. __decorate([
  16582. BABYLON.serialize("lightmapMode")
  16583. ], Light.prototype, "_lightmapMode", void 0);
  16584. return Light;
  16585. }(BABYLON.Node));
  16586. BABYLON.Light = Light;
  16587. })(BABYLON || (BABYLON = {}));
  16588. //# sourceMappingURL=babylon.light.js.map
  16589. var BABYLON;
  16590. (function (BABYLON) {
  16591. var Camera = /** @class */ (function (_super) {
  16592. __extends(Camera, _super);
  16593. function Camera(name, position, scene) {
  16594. var _this = _super.call(this, name, scene) || this;
  16595. _this.upVector = BABYLON.Vector3.Up();
  16596. _this.orthoLeft = null;
  16597. _this.orthoRight = null;
  16598. _this.orthoBottom = null;
  16599. _this.orthoTop = null;
  16600. _this.fov = 0.8;
  16601. _this.minZ = 1;
  16602. _this.maxZ = 10000.0;
  16603. _this.inertia = 0.9;
  16604. _this.mode = Camera.PERSPECTIVE_CAMERA;
  16605. _this.isIntermediate = false;
  16606. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  16607. _this.layerMask = 0x0FFFFFFF;
  16608. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  16609. // Camera rig members
  16610. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  16611. _this._rigCameras = new Array();
  16612. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  16613. _this._skipRendering = false;
  16614. _this.customRenderTargets = new Array();
  16615. // Observables
  16616. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  16617. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  16618. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  16619. _this.onRestoreStateObservable = new BABYLON.Observable();
  16620. // Cache
  16621. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  16622. _this._projectionMatrix = new BABYLON.Matrix();
  16623. _this._doNotComputeProjectionMatrix = false;
  16624. _this._postProcesses = new Array();
  16625. _this._transformMatrix = BABYLON.Matrix.Zero();
  16626. _this._activeMeshes = new BABYLON.SmartArray(256);
  16627. _this._globalPosition = BABYLON.Vector3.Zero();
  16628. _this._refreshFrustumPlanes = true;
  16629. _this.getScene().addCamera(_this);
  16630. if (!_this.getScene().activeCamera) {
  16631. _this.getScene().activeCamera = _this;
  16632. }
  16633. _this.position = position;
  16634. return _this;
  16635. }
  16636. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  16637. get: function () {
  16638. return Camera._PERSPECTIVE_CAMERA;
  16639. },
  16640. enumerable: true,
  16641. configurable: true
  16642. });
  16643. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  16644. get: function () {
  16645. return Camera._ORTHOGRAPHIC_CAMERA;
  16646. },
  16647. enumerable: true,
  16648. configurable: true
  16649. });
  16650. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  16651. get: function () {
  16652. return Camera._FOVMODE_VERTICAL_FIXED;
  16653. },
  16654. enumerable: true,
  16655. configurable: true
  16656. });
  16657. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  16658. get: function () {
  16659. return Camera._FOVMODE_HORIZONTAL_FIXED;
  16660. },
  16661. enumerable: true,
  16662. configurable: true
  16663. });
  16664. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  16665. get: function () {
  16666. return Camera._RIG_MODE_NONE;
  16667. },
  16668. enumerable: true,
  16669. configurable: true
  16670. });
  16671. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  16672. get: function () {
  16673. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  16674. },
  16675. enumerable: true,
  16676. configurable: true
  16677. });
  16678. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  16679. get: function () {
  16680. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  16681. },
  16682. enumerable: true,
  16683. configurable: true
  16684. });
  16685. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  16686. get: function () {
  16687. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16688. },
  16689. enumerable: true,
  16690. configurable: true
  16691. });
  16692. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  16693. get: function () {
  16694. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  16695. },
  16696. enumerable: true,
  16697. configurable: true
  16698. });
  16699. Object.defineProperty(Camera, "RIG_MODE_VR", {
  16700. get: function () {
  16701. return Camera._RIG_MODE_VR;
  16702. },
  16703. enumerable: true,
  16704. configurable: true
  16705. });
  16706. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  16707. get: function () {
  16708. return Camera._RIG_MODE_WEBVR;
  16709. },
  16710. enumerable: true,
  16711. configurable: true
  16712. });
  16713. /**
  16714. * Store current camera state (fov, position, etc..)
  16715. */
  16716. Camera.prototype.storeState = function () {
  16717. this._stateStored = true;
  16718. this._storedFov = this.fov;
  16719. return this;
  16720. };
  16721. /**
  16722. * Restores the camera state values if it has been stored. You must call storeState() first
  16723. */
  16724. Camera.prototype._restoreStateValues = function () {
  16725. if (!this._stateStored) {
  16726. return false;
  16727. }
  16728. this.fov = this._storedFov;
  16729. return true;
  16730. };
  16731. /**
  16732. * Restored camera state. You must call storeState() first
  16733. */
  16734. Camera.prototype.restoreState = function () {
  16735. if (this._restoreStateValues()) {
  16736. this.onRestoreStateObservable.notifyObservers(this);
  16737. return true;
  16738. }
  16739. return false;
  16740. };
  16741. Camera.prototype.getClassName = function () {
  16742. return "Camera";
  16743. };
  16744. /**
  16745. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16746. */
  16747. Camera.prototype.toString = function (fullDetails) {
  16748. var ret = "Name: " + this.name;
  16749. ret += ", type: " + this.getClassName();
  16750. if (this.animations) {
  16751. for (var i = 0; i < this.animations.length; i++) {
  16752. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  16753. }
  16754. }
  16755. if (fullDetails) {
  16756. }
  16757. return ret;
  16758. };
  16759. Object.defineProperty(Camera.prototype, "globalPosition", {
  16760. get: function () {
  16761. return this._globalPosition;
  16762. },
  16763. enumerable: true,
  16764. configurable: true
  16765. });
  16766. Camera.prototype.getActiveMeshes = function () {
  16767. return this._activeMeshes;
  16768. };
  16769. Camera.prototype.isActiveMesh = function (mesh) {
  16770. return (this._activeMeshes.indexOf(mesh) !== -1);
  16771. };
  16772. //Cache
  16773. Camera.prototype._initCache = function () {
  16774. _super.prototype._initCache.call(this);
  16775. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16776. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16777. this._cache.mode = undefined;
  16778. this._cache.minZ = undefined;
  16779. this._cache.maxZ = undefined;
  16780. this._cache.fov = undefined;
  16781. this._cache.fovMode = undefined;
  16782. this._cache.aspectRatio = undefined;
  16783. this._cache.orthoLeft = undefined;
  16784. this._cache.orthoRight = undefined;
  16785. this._cache.orthoBottom = undefined;
  16786. this._cache.orthoTop = undefined;
  16787. this._cache.renderWidth = undefined;
  16788. this._cache.renderHeight = undefined;
  16789. };
  16790. Camera.prototype._updateCache = function (ignoreParentClass) {
  16791. if (!ignoreParentClass) {
  16792. _super.prototype._updateCache.call(this);
  16793. }
  16794. this._cache.position.copyFrom(this.position);
  16795. this._cache.upVector.copyFrom(this.upVector);
  16796. };
  16797. // Synchronized
  16798. Camera.prototype._isSynchronized = function () {
  16799. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  16800. };
  16801. Camera.prototype._isSynchronizedViewMatrix = function () {
  16802. if (!_super.prototype._isSynchronized.call(this))
  16803. return false;
  16804. return this._cache.position.equals(this.position)
  16805. && this._cache.upVector.equals(this.upVector)
  16806. && this.isSynchronizedWithParent();
  16807. };
  16808. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  16809. var check = this._cache.mode === this.mode
  16810. && this._cache.minZ === this.minZ
  16811. && this._cache.maxZ === this.maxZ;
  16812. if (!check) {
  16813. return false;
  16814. }
  16815. var engine = this.getEngine();
  16816. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16817. check = this._cache.fov === this.fov
  16818. && this._cache.fovMode === this.fovMode
  16819. && this._cache.aspectRatio === engine.getAspectRatio(this);
  16820. }
  16821. else {
  16822. check = this._cache.orthoLeft === this.orthoLeft
  16823. && this._cache.orthoRight === this.orthoRight
  16824. && this._cache.orthoBottom === this.orthoBottom
  16825. && this._cache.orthoTop === this.orthoTop
  16826. && this._cache.renderWidth === engine.getRenderWidth()
  16827. && this._cache.renderHeight === engine.getRenderHeight();
  16828. }
  16829. return check;
  16830. };
  16831. // Controls
  16832. Camera.prototype.attachControl = function (element, noPreventDefault) {
  16833. };
  16834. Camera.prototype.detachControl = function (element) {
  16835. };
  16836. Camera.prototype.update = function () {
  16837. this._checkInputs();
  16838. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16839. this._updateRigCameras();
  16840. }
  16841. };
  16842. Camera.prototype._checkInputs = function () {
  16843. this.onAfterCheckInputsObservable.notifyObservers(this);
  16844. };
  16845. Object.defineProperty(Camera.prototype, "rigCameras", {
  16846. get: function () {
  16847. return this._rigCameras;
  16848. },
  16849. enumerable: true,
  16850. configurable: true
  16851. });
  16852. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  16853. get: function () {
  16854. return this._rigPostProcess;
  16855. },
  16856. enumerable: true,
  16857. configurable: true
  16858. });
  16859. Camera.prototype._cascadePostProcessesToRigCams = function () {
  16860. // invalidate framebuffer
  16861. if (this._postProcesses.length > 0) {
  16862. this._postProcesses[0].markTextureDirty();
  16863. }
  16864. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  16865. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  16866. var cam = this._rigCameras[i];
  16867. var rigPostProcess = cam._rigPostProcess;
  16868. // for VR rig, there does not have to be a post process
  16869. if (rigPostProcess) {
  16870. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  16871. if (isPass) {
  16872. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  16873. cam.isIntermediate = this._postProcesses.length === 0;
  16874. }
  16875. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  16876. rigPostProcess.markTextureDirty();
  16877. }
  16878. else {
  16879. cam._postProcesses = this._postProcesses.slice(0);
  16880. }
  16881. }
  16882. };
  16883. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  16884. if (insertAt === void 0) { insertAt = null; }
  16885. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  16886. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  16887. return 0;
  16888. }
  16889. if (insertAt == null || insertAt < 0) {
  16890. this._postProcesses.push(postProcess);
  16891. }
  16892. else {
  16893. this._postProcesses.splice(insertAt, 0, postProcess);
  16894. }
  16895. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16896. return this._postProcesses.indexOf(postProcess);
  16897. };
  16898. Camera.prototype.detachPostProcess = function (postProcess) {
  16899. var idx = this._postProcesses.indexOf(postProcess);
  16900. if (idx !== -1) {
  16901. this._postProcesses.splice(idx, 1);
  16902. }
  16903. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16904. };
  16905. Camera.prototype.getWorldMatrix = function () {
  16906. if (!this._worldMatrix) {
  16907. this._worldMatrix = BABYLON.Matrix.Identity();
  16908. }
  16909. var viewMatrix = this.getViewMatrix();
  16910. viewMatrix.invertToRef(this._worldMatrix);
  16911. return this._worldMatrix;
  16912. };
  16913. Camera.prototype._getViewMatrix = function () {
  16914. return BABYLON.Matrix.Identity();
  16915. };
  16916. Camera.prototype.getViewMatrix = function (force) {
  16917. if (!force && this._isSynchronizedViewMatrix()) {
  16918. return this._computedViewMatrix;
  16919. }
  16920. this.updateCache();
  16921. this._computedViewMatrix = this._getViewMatrix();
  16922. this._currentRenderId = this.getScene().getRenderId();
  16923. this._refreshFrustumPlanes = true;
  16924. if (!this.parent || !this.parent.getWorldMatrix) {
  16925. this._globalPosition.copyFrom(this.position);
  16926. }
  16927. else {
  16928. if (!this._worldMatrix) {
  16929. this._worldMatrix = BABYLON.Matrix.Identity();
  16930. }
  16931. this._computedViewMatrix.invertToRef(this._worldMatrix);
  16932. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  16933. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  16934. this._computedViewMatrix.invert();
  16935. this._markSyncedWithParent();
  16936. }
  16937. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  16938. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  16939. }
  16940. this.onViewMatrixChangedObservable.notifyObservers(this);
  16941. return this._computedViewMatrix;
  16942. };
  16943. Camera.prototype.freezeProjectionMatrix = function (projection) {
  16944. this._doNotComputeProjectionMatrix = true;
  16945. if (projection !== undefined) {
  16946. this._projectionMatrix = projection;
  16947. }
  16948. };
  16949. ;
  16950. Camera.prototype.unfreezeProjectionMatrix = function () {
  16951. this._doNotComputeProjectionMatrix = false;
  16952. };
  16953. ;
  16954. Camera.prototype.getProjectionMatrix = function (force) {
  16955. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  16956. return this._projectionMatrix;
  16957. }
  16958. // Cache
  16959. this._cache.mode = this.mode;
  16960. this._cache.minZ = this.minZ;
  16961. this._cache.maxZ = this.maxZ;
  16962. // Matrix
  16963. this._refreshFrustumPlanes = true;
  16964. var engine = this.getEngine();
  16965. var scene = this.getScene();
  16966. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16967. this._cache.fov = this.fov;
  16968. this._cache.fovMode = this.fovMode;
  16969. this._cache.aspectRatio = engine.getAspectRatio(this);
  16970. if (this.minZ <= 0) {
  16971. this.minZ = 0.1;
  16972. }
  16973. if (scene.useRightHandedSystem) {
  16974. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16975. }
  16976. else {
  16977. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16978. }
  16979. }
  16980. else {
  16981. var halfWidth = engine.getRenderWidth() / 2.0;
  16982. var halfHeight = engine.getRenderHeight() / 2.0;
  16983. if (scene.useRightHandedSystem) {
  16984. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16985. }
  16986. else {
  16987. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16988. }
  16989. this._cache.orthoLeft = this.orthoLeft;
  16990. this._cache.orthoRight = this.orthoRight;
  16991. this._cache.orthoBottom = this.orthoBottom;
  16992. this._cache.orthoTop = this.orthoTop;
  16993. this._cache.renderWidth = engine.getRenderWidth();
  16994. this._cache.renderHeight = engine.getRenderHeight();
  16995. }
  16996. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  16997. return this._projectionMatrix;
  16998. };
  16999. Camera.prototype.getTranformationMatrix = function () {
  17000. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  17001. return this._transformMatrix;
  17002. };
  17003. Camera.prototype.updateFrustumPlanes = function () {
  17004. if (!this._refreshFrustumPlanes) {
  17005. return;
  17006. }
  17007. this.getTranformationMatrix();
  17008. if (!this._frustumPlanes) {
  17009. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  17010. }
  17011. else {
  17012. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  17013. }
  17014. this._refreshFrustumPlanes = false;
  17015. };
  17016. Camera.prototype.isInFrustum = function (target) {
  17017. this.updateFrustumPlanes();
  17018. return target.isInFrustum(this._frustumPlanes);
  17019. };
  17020. Camera.prototype.isCompletelyInFrustum = function (target) {
  17021. this.updateFrustumPlanes();
  17022. return target.isCompletelyInFrustum(this._frustumPlanes);
  17023. };
  17024. Camera.prototype.getForwardRay = function (length, transform, origin) {
  17025. if (length === void 0) { length = 100; }
  17026. if (!transform) {
  17027. transform = this.getWorldMatrix();
  17028. }
  17029. if (!origin) {
  17030. origin = this.position;
  17031. }
  17032. var forward = new BABYLON.Vector3(0, 0, 1);
  17033. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  17034. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  17035. return new BABYLON.Ray(origin, direction, length);
  17036. };
  17037. Camera.prototype.dispose = function () {
  17038. // Observables
  17039. this.onViewMatrixChangedObservable.clear();
  17040. this.onProjectionMatrixChangedObservable.clear();
  17041. this.onAfterCheckInputsObservable.clear();
  17042. this.onRestoreStateObservable.clear();
  17043. // Inputs
  17044. if (this.inputs) {
  17045. this.inputs.clear();
  17046. }
  17047. // Animations
  17048. this.getScene().stopAnimation(this);
  17049. // Remove from scene
  17050. this.getScene().removeCamera(this);
  17051. while (this._rigCameras.length > 0) {
  17052. var camera = this._rigCameras.pop();
  17053. if (camera) {
  17054. camera.dispose();
  17055. }
  17056. }
  17057. // Postprocesses
  17058. if (this._rigPostProcess) {
  17059. this._rigPostProcess.dispose(this);
  17060. this._rigPostProcess = null;
  17061. this._postProcesses = [];
  17062. }
  17063. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  17064. this._rigPostProcess = null;
  17065. this._postProcesses = [];
  17066. }
  17067. else {
  17068. var i = this._postProcesses.length;
  17069. while (--i >= 0) {
  17070. this._postProcesses[i].dispose(this);
  17071. }
  17072. }
  17073. // Render targets
  17074. var i = this.customRenderTargets.length;
  17075. while (--i >= 0) {
  17076. this.customRenderTargets[i].dispose();
  17077. }
  17078. this.customRenderTargets = [];
  17079. // Active Meshes
  17080. this._activeMeshes.dispose();
  17081. _super.prototype.dispose.call(this);
  17082. };
  17083. Object.defineProperty(Camera.prototype, "leftCamera", {
  17084. // ---- Camera rigs section ----
  17085. get: function () {
  17086. if (this._rigCameras.length < 1) {
  17087. return null;
  17088. }
  17089. return this._rigCameras[0];
  17090. },
  17091. enumerable: true,
  17092. configurable: true
  17093. });
  17094. Object.defineProperty(Camera.prototype, "rightCamera", {
  17095. get: function () {
  17096. if (this._rigCameras.length < 2) {
  17097. return null;
  17098. }
  17099. return this._rigCameras[1];
  17100. },
  17101. enumerable: true,
  17102. configurable: true
  17103. });
  17104. Camera.prototype.getLeftTarget = function () {
  17105. if (this._rigCameras.length < 1) {
  17106. return null;
  17107. }
  17108. return this._rigCameras[0].getTarget();
  17109. };
  17110. Camera.prototype.getRightTarget = function () {
  17111. if (this._rigCameras.length < 2) {
  17112. return null;
  17113. }
  17114. return this._rigCameras[1].getTarget();
  17115. };
  17116. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  17117. if (this.cameraRigMode === mode) {
  17118. return;
  17119. }
  17120. while (this._rigCameras.length > 0) {
  17121. var camera = this._rigCameras.pop();
  17122. if (camera) {
  17123. camera.dispose();
  17124. }
  17125. }
  17126. this.cameraRigMode = mode;
  17127. this._cameraRigParams = {};
  17128. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  17129. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  17130. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  17131. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  17132. // create the rig cameras, unless none
  17133. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  17134. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  17135. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  17136. if (leftCamera && rightCamera) {
  17137. this._rigCameras.push(leftCamera);
  17138. this._rigCameras.push(rightCamera);
  17139. }
  17140. }
  17141. switch (this.cameraRigMode) {
  17142. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  17143. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  17144. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  17145. break;
  17146. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  17147. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  17148. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  17149. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  17150. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  17151. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  17152. break;
  17153. case Camera.RIG_MODE_VR:
  17154. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  17155. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  17156. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  17157. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  17158. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  17159. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  17160. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  17161. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  17162. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  17163. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  17164. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  17165. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  17166. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  17167. if (metrics.compensateDistortion) {
  17168. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  17169. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  17170. }
  17171. break;
  17172. case Camera.RIG_MODE_WEBVR:
  17173. if (rigParams.vrDisplay) {
  17174. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  17175. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  17176. //Left eye
  17177. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  17178. this._rigCameras[0].setCameraRigParameter("left", true);
  17179. //leaving this for future reference
  17180. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  17181. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  17182. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  17183. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  17184. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  17185. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  17186. this._rigCameras[0].parent = this;
  17187. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  17188. //Right eye
  17189. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  17190. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  17191. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  17192. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  17193. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  17194. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  17195. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  17196. this._rigCameras[1].parent = this;
  17197. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  17198. if (Camera.UseAlternateWebVRRendering) {
  17199. this._rigCameras[1]._skipRendering = true;
  17200. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  17201. }
  17202. }
  17203. break;
  17204. }
  17205. this._cascadePostProcessesToRigCams();
  17206. this.update();
  17207. };
  17208. Camera.prototype._getVRProjectionMatrix = function () {
  17209. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  17210. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  17211. return this._projectionMatrix;
  17212. };
  17213. Camera.prototype._updateCameraRotationMatrix = function () {
  17214. //Here for WebVR
  17215. };
  17216. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  17217. //Here for WebVR
  17218. };
  17219. /**
  17220. * This function MUST be overwritten by the different WebVR cameras available.
  17221. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  17222. */
  17223. Camera.prototype._getWebVRProjectionMatrix = function () {
  17224. return BABYLON.Matrix.Identity();
  17225. };
  17226. /**
  17227. * This function MUST be overwritten by the different WebVR cameras available.
  17228. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  17229. */
  17230. Camera.prototype._getWebVRViewMatrix = function () {
  17231. return BABYLON.Matrix.Identity();
  17232. };
  17233. Camera.prototype.setCameraRigParameter = function (name, value) {
  17234. if (!this._cameraRigParams) {
  17235. this._cameraRigParams = {};
  17236. }
  17237. this._cameraRigParams[name] = value;
  17238. //provisionnally:
  17239. if (name === "interaxialDistance") {
  17240. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  17241. }
  17242. };
  17243. /**
  17244. * needs to be overridden by children so sub has required properties to be copied
  17245. */
  17246. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  17247. return null;
  17248. };
  17249. /**
  17250. * May need to be overridden by children
  17251. */
  17252. Camera.prototype._updateRigCameras = function () {
  17253. for (var i = 0; i < this._rigCameras.length; i++) {
  17254. this._rigCameras[i].minZ = this.minZ;
  17255. this._rigCameras[i].maxZ = this.maxZ;
  17256. this._rigCameras[i].fov = this.fov;
  17257. }
  17258. // only update viewport when ANAGLYPH
  17259. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  17260. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  17261. }
  17262. };
  17263. Camera.prototype._setupInputs = function () {
  17264. };
  17265. Camera.prototype.serialize = function () {
  17266. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  17267. // Type
  17268. serializationObject.type = this.getClassName();
  17269. // Parent
  17270. if (this.parent) {
  17271. serializationObject.parentId = this.parent.id;
  17272. }
  17273. if (this.inputs) {
  17274. this.inputs.serialize(serializationObject);
  17275. }
  17276. // Animations
  17277. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17278. serializationObject.ranges = this.serializeAnimationRanges();
  17279. return serializationObject;
  17280. };
  17281. Camera.prototype.clone = function (name) {
  17282. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  17283. };
  17284. Camera.prototype.getDirection = function (localAxis) {
  17285. var result = BABYLON.Vector3.Zero();
  17286. this.getDirectionToRef(localAxis, result);
  17287. return result;
  17288. };
  17289. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  17290. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  17291. };
  17292. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  17293. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  17294. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  17295. switch (type) {
  17296. case "ArcRotateCamera":
  17297. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  17298. case "DeviceOrientationCamera":
  17299. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  17300. case "FollowCamera":
  17301. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  17302. case "ArcFollowCamera":
  17303. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  17304. case "GamepadCamera":
  17305. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  17306. case "TouchCamera":
  17307. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  17308. case "VirtualJoysticksCamera":
  17309. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  17310. case "WebVRFreeCamera":
  17311. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  17312. case "WebVRGamepadCamera":
  17313. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  17314. case "VRDeviceOrientationFreeCamera":
  17315. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  17316. case "VRDeviceOrientationGamepadCamera":
  17317. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  17318. case "AnaglyphArcRotateCamera":
  17319. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  17320. case "AnaglyphFreeCamera":
  17321. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  17322. case "AnaglyphGamepadCamera":
  17323. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  17324. case "AnaglyphUniversalCamera":
  17325. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  17326. case "StereoscopicArcRotateCamera":
  17327. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  17328. case "StereoscopicFreeCamera":
  17329. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  17330. case "StereoscopicGamepadCamera":
  17331. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  17332. case "StereoscopicUniversalCamera":
  17333. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  17334. case "FreeCamera":// Forcing Universal here
  17335. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  17336. default:// Universal Camera is the default value
  17337. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  17338. }
  17339. };
  17340. Camera.prototype.computeWorldMatrix = function () {
  17341. return this.getWorldMatrix();
  17342. };
  17343. Camera.Parse = function (parsedCamera, scene) {
  17344. var type = parsedCamera.type;
  17345. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  17346. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  17347. // Parent
  17348. if (parsedCamera.parentId) {
  17349. camera._waitingParentId = parsedCamera.parentId;
  17350. }
  17351. //If camera has an input manager, let it parse inputs settings
  17352. if (camera.inputs) {
  17353. camera.inputs.parse(parsedCamera);
  17354. camera._setupInputs();
  17355. }
  17356. if (camera.setPosition) {
  17357. camera.position.copyFromFloats(0, 0, 0);
  17358. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  17359. }
  17360. // Target
  17361. if (parsedCamera.target) {
  17362. if (camera.setTarget) {
  17363. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  17364. }
  17365. }
  17366. // Apply 3d rig, when found
  17367. if (parsedCamera.cameraRigMode) {
  17368. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  17369. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  17370. }
  17371. // Animations
  17372. if (parsedCamera.animations) {
  17373. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  17374. var parsedAnimation = parsedCamera.animations[animationIndex];
  17375. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17376. }
  17377. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  17378. }
  17379. if (parsedCamera.autoAnimate) {
  17380. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  17381. }
  17382. return camera;
  17383. };
  17384. // Statics
  17385. Camera._PERSPECTIVE_CAMERA = 0;
  17386. Camera._ORTHOGRAPHIC_CAMERA = 1;
  17387. Camera._FOVMODE_VERTICAL_FIXED = 0;
  17388. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  17389. Camera._RIG_MODE_NONE = 0;
  17390. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  17391. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  17392. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  17393. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  17394. Camera._RIG_MODE_VR = 20;
  17395. Camera._RIG_MODE_WEBVR = 21;
  17396. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  17397. Camera.UseAlternateWebVRRendering = false;
  17398. __decorate([
  17399. BABYLON.serializeAsVector3()
  17400. ], Camera.prototype, "position", void 0);
  17401. __decorate([
  17402. BABYLON.serializeAsVector3()
  17403. ], Camera.prototype, "upVector", void 0);
  17404. __decorate([
  17405. BABYLON.serialize()
  17406. ], Camera.prototype, "orthoLeft", void 0);
  17407. __decorate([
  17408. BABYLON.serialize()
  17409. ], Camera.prototype, "orthoRight", void 0);
  17410. __decorate([
  17411. BABYLON.serialize()
  17412. ], Camera.prototype, "orthoBottom", void 0);
  17413. __decorate([
  17414. BABYLON.serialize()
  17415. ], Camera.prototype, "orthoTop", void 0);
  17416. __decorate([
  17417. BABYLON.serialize()
  17418. ], Camera.prototype, "fov", void 0);
  17419. __decorate([
  17420. BABYLON.serialize()
  17421. ], Camera.prototype, "minZ", void 0);
  17422. __decorate([
  17423. BABYLON.serialize()
  17424. ], Camera.prototype, "maxZ", void 0);
  17425. __decorate([
  17426. BABYLON.serialize()
  17427. ], Camera.prototype, "inertia", void 0);
  17428. __decorate([
  17429. BABYLON.serialize()
  17430. ], Camera.prototype, "mode", void 0);
  17431. __decorate([
  17432. BABYLON.serialize()
  17433. ], Camera.prototype, "layerMask", void 0);
  17434. __decorate([
  17435. BABYLON.serialize()
  17436. ], Camera.prototype, "fovMode", void 0);
  17437. __decorate([
  17438. BABYLON.serialize()
  17439. ], Camera.prototype, "cameraRigMode", void 0);
  17440. __decorate([
  17441. BABYLON.serialize()
  17442. ], Camera.prototype, "interaxialDistance", void 0);
  17443. __decorate([
  17444. BABYLON.serialize()
  17445. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  17446. return Camera;
  17447. }(BABYLON.Node));
  17448. BABYLON.Camera = Camera;
  17449. })(BABYLON || (BABYLON = {}));
  17450. //# sourceMappingURL=babylon.camera.js.map
  17451. var BABYLON;
  17452. (function (BABYLON) {
  17453. var RenderingManager = /** @class */ (function () {
  17454. function RenderingManager(scene) {
  17455. this._renderingGroups = new Array();
  17456. this._autoClearDepthStencil = {};
  17457. this._customOpaqueSortCompareFn = {};
  17458. this._customAlphaTestSortCompareFn = {};
  17459. this._customTransparentSortCompareFn = {};
  17460. this._renderinGroupInfo = null;
  17461. this._scene = scene;
  17462. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  17463. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  17464. }
  17465. }
  17466. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  17467. if (depth === void 0) { depth = true; }
  17468. if (stencil === void 0) { stencil = true; }
  17469. if (this._depthStencilBufferAlreadyCleaned) {
  17470. return;
  17471. }
  17472. this._scene.getEngine().clear(null, false, depth, stencil);
  17473. this._depthStencilBufferAlreadyCleaned = true;
  17474. };
  17475. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  17476. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  17477. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  17478. var info = null;
  17479. if (observable) {
  17480. if (!this._renderinGroupInfo) {
  17481. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  17482. }
  17483. info = this._renderinGroupInfo;
  17484. info.scene = this._scene;
  17485. info.camera = this._scene.activeCamera;
  17486. }
  17487. // Dispatch sprites
  17488. if (renderSprites) {
  17489. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  17490. var manager = this._scene.spriteManagers[index];
  17491. this.dispatchSprites(manager);
  17492. }
  17493. }
  17494. // Render
  17495. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  17496. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  17497. var renderingGroup = this._renderingGroups[index];
  17498. if (!renderingGroup && !observable)
  17499. continue;
  17500. var renderingGroupMask = 0;
  17501. // Fire PRECLEAR stage
  17502. if (observable && info) {
  17503. renderingGroupMask = Math.pow(2, index);
  17504. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  17505. info.renderingGroupId = index;
  17506. observable.notifyObservers(info, renderingGroupMask);
  17507. }
  17508. // Clear depth/stencil if needed
  17509. if (RenderingManager.AUTOCLEAR) {
  17510. var autoClear = this._autoClearDepthStencil[index];
  17511. if (autoClear && autoClear.autoClear) {
  17512. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  17513. }
  17514. }
  17515. if (observable && info) {
  17516. // Fire PREOPAQUE stage
  17517. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  17518. observable.notifyObservers(info, renderingGroupMask);
  17519. // Fire PRETRANSPARENT stage
  17520. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  17521. observable.notifyObservers(info, renderingGroupMask);
  17522. }
  17523. if (renderingGroup)
  17524. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  17525. // Fire POSTTRANSPARENT stage
  17526. if (observable && info) {
  17527. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  17528. observable.notifyObservers(info, renderingGroupMask);
  17529. }
  17530. }
  17531. };
  17532. RenderingManager.prototype.reset = function () {
  17533. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  17534. var renderingGroup = this._renderingGroups[index];
  17535. if (renderingGroup) {
  17536. renderingGroup.prepare();
  17537. }
  17538. }
  17539. };
  17540. RenderingManager.prototype.dispose = function () {
  17541. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  17542. var renderingGroup = this._renderingGroups[index];
  17543. if (renderingGroup) {
  17544. renderingGroup.dispose();
  17545. }
  17546. }
  17547. this._renderingGroups.length = 0;
  17548. };
  17549. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  17550. if (!this._renderingGroups[renderingGroupId]) {
  17551. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  17552. }
  17553. };
  17554. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  17555. var renderingGroupId = spriteManager.renderingGroupId || 0;
  17556. this._prepareRenderingGroup(renderingGroupId);
  17557. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  17558. };
  17559. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  17560. var renderingGroupId = particleSystem.renderingGroupId || 0;
  17561. this._prepareRenderingGroup(renderingGroupId);
  17562. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  17563. };
  17564. RenderingManager.prototype.dispatch = function (subMesh) {
  17565. var mesh = subMesh.getMesh();
  17566. var renderingGroupId = mesh.renderingGroupId || 0;
  17567. this._prepareRenderingGroup(renderingGroupId);
  17568. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  17569. };
  17570. /**
  17571. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  17572. * This allowed control for front to back rendering or reversly depending of the special needs.
  17573. *
  17574. * @param renderingGroupId The rendering group id corresponding to its index
  17575. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  17576. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  17577. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  17578. */
  17579. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  17580. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  17581. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  17582. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  17583. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  17584. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  17585. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  17586. if (this._renderingGroups[renderingGroupId]) {
  17587. var group = this._renderingGroups[renderingGroupId];
  17588. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  17589. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  17590. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  17591. }
  17592. };
  17593. /**
  17594. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  17595. *
  17596. * @param renderingGroupId The rendering group id corresponding to its index
  17597. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  17598. * @param depth Automatically clears depth between groups if true and autoClear is true.
  17599. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  17600. */
  17601. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  17602. if (depth === void 0) { depth = true; }
  17603. if (stencil === void 0) { stencil = true; }
  17604. this._autoClearDepthStencil[renderingGroupId] = {
  17605. autoClear: autoClearDepthStencil,
  17606. depth: depth,
  17607. stencil: stencil
  17608. };
  17609. };
  17610. /**
  17611. * The max id used for rendering groups (not included)
  17612. */
  17613. RenderingManager.MAX_RENDERINGGROUPS = 4;
  17614. /**
  17615. * The min id used for rendering groups (included)
  17616. */
  17617. RenderingManager.MIN_RENDERINGGROUPS = 0;
  17618. /**
  17619. * Used to globally prevent autoclearing scenes.
  17620. */
  17621. RenderingManager.AUTOCLEAR = true;
  17622. return RenderingManager;
  17623. }());
  17624. BABYLON.RenderingManager = RenderingManager;
  17625. })(BABYLON || (BABYLON = {}));
  17626. //# sourceMappingURL=babylon.renderingManager.js.map
  17627. var BABYLON;
  17628. (function (BABYLON) {
  17629. var RenderingGroup = /** @class */ (function () {
  17630. /**
  17631. * Creates a new rendering group.
  17632. * @param index The rendering group index
  17633. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  17634. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  17635. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  17636. */
  17637. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  17638. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  17639. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  17640. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  17641. this.index = index;
  17642. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  17643. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  17644. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  17645. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  17646. this._particleSystems = new BABYLON.SmartArray(256);
  17647. this._spriteManagers = new BABYLON.SmartArray(256);
  17648. this._edgesRenderers = new BABYLON.SmartArray(16);
  17649. this._scene = scene;
  17650. this.opaqueSortCompareFn = opaqueSortCompareFn;
  17651. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  17652. this.transparentSortCompareFn = transparentSortCompareFn;
  17653. }
  17654. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  17655. /**
  17656. * Set the opaque sort comparison function.
  17657. * If null the sub meshes will be render in the order they were created
  17658. */
  17659. set: function (value) {
  17660. this._opaqueSortCompareFn = value;
  17661. if (value) {
  17662. this._renderOpaque = this.renderOpaqueSorted;
  17663. }
  17664. else {
  17665. this._renderOpaque = RenderingGroup.renderUnsorted;
  17666. }
  17667. },
  17668. enumerable: true,
  17669. configurable: true
  17670. });
  17671. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  17672. /**
  17673. * Set the alpha test sort comparison function.
  17674. * If null the sub meshes will be render in the order they were created
  17675. */
  17676. set: function (value) {
  17677. this._alphaTestSortCompareFn = value;
  17678. if (value) {
  17679. this._renderAlphaTest = this.renderAlphaTestSorted;
  17680. }
  17681. else {
  17682. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  17683. }
  17684. },
  17685. enumerable: true,
  17686. configurable: true
  17687. });
  17688. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  17689. /**
  17690. * Set the transparent sort comparison function.
  17691. * If null the sub meshes will be render in the order they were created
  17692. */
  17693. set: function (value) {
  17694. if (value) {
  17695. this._transparentSortCompareFn = value;
  17696. }
  17697. else {
  17698. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  17699. }
  17700. this._renderTransparent = this.renderTransparentSorted;
  17701. },
  17702. enumerable: true,
  17703. configurable: true
  17704. });
  17705. /**
  17706. * Render all the sub meshes contained in the group.
  17707. * @param customRenderFunction Used to override the default render behaviour of the group.
  17708. * @returns true if rendered some submeshes.
  17709. */
  17710. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  17711. if (customRenderFunction) {
  17712. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  17713. return;
  17714. }
  17715. var engine = this._scene.getEngine();
  17716. // Depth only
  17717. if (this._depthOnlySubMeshes.length !== 0) {
  17718. engine.setAlphaTesting(true);
  17719. engine.setColorWrite(false);
  17720. this._renderAlphaTest(this._depthOnlySubMeshes);
  17721. engine.setAlphaTesting(false);
  17722. engine.setColorWrite(true);
  17723. }
  17724. // Opaque
  17725. if (this._opaqueSubMeshes.length !== 0) {
  17726. this._renderOpaque(this._opaqueSubMeshes);
  17727. }
  17728. // Alpha test
  17729. if (this._alphaTestSubMeshes.length !== 0) {
  17730. engine.setAlphaTesting(true);
  17731. this._renderAlphaTest(this._alphaTestSubMeshes);
  17732. engine.setAlphaTesting(false);
  17733. }
  17734. var stencilState = engine.getStencilBuffer();
  17735. engine.setStencilBuffer(false);
  17736. // Sprites
  17737. if (renderSprites) {
  17738. this._renderSprites();
  17739. }
  17740. // Particles
  17741. if (renderParticles) {
  17742. this._renderParticles(activeMeshes);
  17743. }
  17744. if (this.onBeforeTransparentRendering) {
  17745. this.onBeforeTransparentRendering();
  17746. }
  17747. // Transparent
  17748. if (this._transparentSubMeshes.length !== 0) {
  17749. this._renderTransparent(this._transparentSubMeshes);
  17750. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17751. }
  17752. // Set back stencil to false in case it changes before the edge renderer.
  17753. engine.setStencilBuffer(false);
  17754. // Edges
  17755. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  17756. this._edgesRenderers.data[edgesRendererIndex].render();
  17757. }
  17758. // Restore Stencil state.
  17759. engine.setStencilBuffer(stencilState);
  17760. };
  17761. /**
  17762. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  17763. * @param subMeshes The submeshes to render
  17764. */
  17765. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  17766. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  17767. };
  17768. /**
  17769. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  17770. * @param subMeshes The submeshes to render
  17771. */
  17772. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  17773. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  17774. };
  17775. /**
  17776. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  17777. * @param subMeshes The submeshes to render
  17778. */
  17779. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  17780. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  17781. };
  17782. /**
  17783. * Renders the submeshes in a specified order.
  17784. * @param subMeshes The submeshes to sort before render
  17785. * @param sortCompareFn The comparison function use to sort
  17786. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  17787. * @param transparent Specifies to activate blending if true
  17788. */
  17789. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  17790. var subIndex = 0;
  17791. var subMesh;
  17792. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  17793. for (; subIndex < subMeshes.length; subIndex++) {
  17794. subMesh = subMeshes.data[subIndex];
  17795. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  17796. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  17797. }
  17798. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  17799. if (sortCompareFn) {
  17800. sortedArray.sort(sortCompareFn);
  17801. }
  17802. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  17803. subMesh = sortedArray[subIndex];
  17804. if (transparent) {
  17805. var material = subMesh.getMaterial();
  17806. if (material && material.needDepthPrePass) {
  17807. var engine = material.getScene().getEngine();
  17808. engine.setColorWrite(false);
  17809. engine.setAlphaTesting(true);
  17810. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17811. subMesh.render(false);
  17812. engine.setAlphaTesting(false);
  17813. engine.setColorWrite(true);
  17814. }
  17815. }
  17816. subMesh.render(transparent);
  17817. }
  17818. };
  17819. /**
  17820. * Renders the submeshes in the order they were dispatched (no sort applied).
  17821. * @param subMeshes The submeshes to render
  17822. */
  17823. RenderingGroup.renderUnsorted = function (subMeshes) {
  17824. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  17825. var submesh = subMeshes.data[subIndex];
  17826. submesh.render(false);
  17827. }
  17828. };
  17829. /**
  17830. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17831. * are rendered back to front if in the same alpha index.
  17832. *
  17833. * @param a The first submesh
  17834. * @param b The second submesh
  17835. * @returns The result of the comparison
  17836. */
  17837. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  17838. // Alpha index first
  17839. if (a._alphaIndex > b._alphaIndex) {
  17840. return 1;
  17841. }
  17842. if (a._alphaIndex < b._alphaIndex) {
  17843. return -1;
  17844. }
  17845. // Then distance to camera
  17846. return RenderingGroup.backToFrontSortCompare(a, b);
  17847. };
  17848. /**
  17849. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17850. * are rendered back to front.
  17851. *
  17852. * @param a The first submesh
  17853. * @param b The second submesh
  17854. * @returns The result of the comparison
  17855. */
  17856. RenderingGroup.backToFrontSortCompare = function (a, b) {
  17857. // Then distance to camera
  17858. if (a._distanceToCamera < b._distanceToCamera) {
  17859. return 1;
  17860. }
  17861. if (a._distanceToCamera > b._distanceToCamera) {
  17862. return -1;
  17863. }
  17864. return 0;
  17865. };
  17866. /**
  17867. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17868. * are rendered front to back (prevent overdraw).
  17869. *
  17870. * @param a The first submesh
  17871. * @param b The second submesh
  17872. * @returns The result of the comparison
  17873. */
  17874. RenderingGroup.frontToBackSortCompare = function (a, b) {
  17875. // Then distance to camera
  17876. if (a._distanceToCamera < b._distanceToCamera) {
  17877. return -1;
  17878. }
  17879. if (a._distanceToCamera > b._distanceToCamera) {
  17880. return 1;
  17881. }
  17882. return 0;
  17883. };
  17884. /**
  17885. * Resets the different lists of submeshes to prepare a new frame.
  17886. */
  17887. RenderingGroup.prototype.prepare = function () {
  17888. this._opaqueSubMeshes.reset();
  17889. this._transparentSubMeshes.reset();
  17890. this._alphaTestSubMeshes.reset();
  17891. this._depthOnlySubMeshes.reset();
  17892. this._particleSystems.reset();
  17893. this._spriteManagers.reset();
  17894. this._edgesRenderers.reset();
  17895. };
  17896. RenderingGroup.prototype.dispose = function () {
  17897. this._opaqueSubMeshes.dispose();
  17898. this._transparentSubMeshes.dispose();
  17899. this._alphaTestSubMeshes.dispose();
  17900. this._depthOnlySubMeshes.dispose();
  17901. this._particleSystems.dispose();
  17902. this._spriteManagers.dispose();
  17903. this._edgesRenderers.dispose();
  17904. };
  17905. /**
  17906. * Inserts the submesh in its correct queue depending on its material.
  17907. * @param subMesh The submesh to dispatch
  17908. */
  17909. RenderingGroup.prototype.dispatch = function (subMesh) {
  17910. var material = subMesh.getMaterial();
  17911. var mesh = subMesh.getMesh();
  17912. if (!material) {
  17913. return;
  17914. }
  17915. if (material.needAlphaBlendingForMesh(mesh)) {
  17916. this._transparentSubMeshes.push(subMesh);
  17917. }
  17918. else if (material.needAlphaTesting()) {
  17919. if (material.needDepthPrePass) {
  17920. this._depthOnlySubMeshes.push(subMesh);
  17921. }
  17922. this._alphaTestSubMeshes.push(subMesh);
  17923. }
  17924. else {
  17925. if (material.needDepthPrePass) {
  17926. this._depthOnlySubMeshes.push(subMesh);
  17927. }
  17928. this._opaqueSubMeshes.push(subMesh); // Opaque
  17929. }
  17930. if (mesh._edgesRenderer) {
  17931. this._edgesRenderers.push(mesh._edgesRenderer);
  17932. }
  17933. };
  17934. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  17935. this._spriteManagers.push(spriteManager);
  17936. };
  17937. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  17938. this._particleSystems.push(particleSystem);
  17939. };
  17940. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  17941. if (this._particleSystems.length === 0) {
  17942. return;
  17943. }
  17944. // Particles
  17945. var activeCamera = this._scene.activeCamera;
  17946. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  17947. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  17948. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  17949. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  17950. continue;
  17951. }
  17952. var emitter = particleSystem.emitter;
  17953. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  17954. this._scene._activeParticles.addCount(particleSystem.render(), false);
  17955. }
  17956. }
  17957. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  17958. };
  17959. RenderingGroup.prototype._renderSprites = function () {
  17960. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  17961. return;
  17962. }
  17963. // Sprites
  17964. var activeCamera = this._scene.activeCamera;
  17965. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  17966. for (var id = 0; id < this._spriteManagers.length; id++) {
  17967. var spriteManager = this._spriteManagers.data[id];
  17968. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  17969. spriteManager.render();
  17970. }
  17971. }
  17972. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  17973. };
  17974. return RenderingGroup;
  17975. }());
  17976. BABYLON.RenderingGroup = RenderingGroup;
  17977. })(BABYLON || (BABYLON = {}));
  17978. //# sourceMappingURL=babylon.renderingGroup.js.map
  17979. var BABYLON;
  17980. (function (BABYLON) {
  17981. var ClickInfo = /** @class */ (function () {
  17982. function ClickInfo() {
  17983. this._singleClick = false;
  17984. this._doubleClick = false;
  17985. this._hasSwiped = false;
  17986. this._ignore = false;
  17987. }
  17988. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  17989. get: function () {
  17990. return this._singleClick;
  17991. },
  17992. set: function (b) {
  17993. this._singleClick = b;
  17994. },
  17995. enumerable: true,
  17996. configurable: true
  17997. });
  17998. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  17999. get: function () {
  18000. return this._doubleClick;
  18001. },
  18002. set: function (b) {
  18003. this._doubleClick = b;
  18004. },
  18005. enumerable: true,
  18006. configurable: true
  18007. });
  18008. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  18009. get: function () {
  18010. return this._hasSwiped;
  18011. },
  18012. set: function (b) {
  18013. this._hasSwiped = b;
  18014. },
  18015. enumerable: true,
  18016. configurable: true
  18017. });
  18018. Object.defineProperty(ClickInfo.prototype, "ignore", {
  18019. get: function () {
  18020. return this._ignore;
  18021. },
  18022. set: function (b) {
  18023. this._ignore = b;
  18024. },
  18025. enumerable: true,
  18026. configurable: true
  18027. });
  18028. return ClickInfo;
  18029. }());
  18030. /**
  18031. * This class is used by the onRenderingGroupObservable
  18032. */
  18033. var RenderingGroupInfo = /** @class */ (function () {
  18034. function RenderingGroupInfo() {
  18035. }
  18036. /**
  18037. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  18038. * This stage will be fired no matter what
  18039. */
  18040. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  18041. /**
  18042. * Called before opaque object are rendered.
  18043. * This stage will be fired only if there's 3D Opaque content to render
  18044. */
  18045. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  18046. /**
  18047. * Called after the opaque objects are rendered and before the transparent ones
  18048. * This stage will be fired only if there's 3D transparent content to render
  18049. */
  18050. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  18051. /**
  18052. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  18053. * This stage will be fired no matter what
  18054. */
  18055. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  18056. return RenderingGroupInfo;
  18057. }());
  18058. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  18059. /**
  18060. * Represents a scene to be rendered by the engine.
  18061. * @see http://doc.babylonjs.com/page.php?p=21911
  18062. */
  18063. var Scene = /** @class */ (function () {
  18064. /**
  18065. * @constructor
  18066. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  18067. */
  18068. function Scene(engine) {
  18069. // Members
  18070. this.autoClear = true;
  18071. this.autoClearDepthAndStencil = true;
  18072. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  18073. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  18074. this.forceWireframe = false;
  18075. this._forcePointsCloud = false;
  18076. this.forceShowBoundingBoxes = false;
  18077. this.animationsEnabled = true;
  18078. this.useConstantAnimationDeltaTime = false;
  18079. this.constantlyUpdateMeshUnderPointer = false;
  18080. this.hoverCursor = "pointer";
  18081. this.defaultCursor = "";
  18082. /**
  18083. * This is used to call preventDefault() on pointer down
  18084. * in order to block unwanted artifacts like system double clicks
  18085. */
  18086. this.preventDefaultOnPointerDown = true;
  18087. // Metadata
  18088. this.metadata = null;
  18089. /**
  18090. * An event triggered when the scene is disposed.
  18091. * @type {BABYLON.Observable}
  18092. */
  18093. this.onDisposeObservable = new BABYLON.Observable();
  18094. /**
  18095. * An event triggered before rendering the scene (right after animations and physics)
  18096. * @type {BABYLON.Observable}
  18097. */
  18098. this.onBeforeRenderObservable = new BABYLON.Observable();
  18099. /**
  18100. * An event triggered after rendering the scene
  18101. * @type {BABYLON.Observable}
  18102. */
  18103. this.onAfterRenderObservable = new BABYLON.Observable();
  18104. /**
  18105. * An event triggered before animating the scene
  18106. * @type {BABYLON.Observable}
  18107. */
  18108. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  18109. /**
  18110. * An event triggered after animations processing
  18111. * @type {BABYLON.Observable}
  18112. */
  18113. this.onAfterAnimationsObservable = new BABYLON.Observable();
  18114. /**
  18115. * An event triggered before draw calls are ready to be sent
  18116. * @type {BABYLON.Observable}
  18117. */
  18118. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  18119. /**
  18120. * An event triggered after draw calls have been sent
  18121. * @type {BABYLON.Observable}
  18122. */
  18123. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  18124. /**
  18125. * An event triggered when physic simulation is about to be run
  18126. * @type {BABYLON.Observable}
  18127. */
  18128. this.onBeforePhysicsObservable = new BABYLON.Observable();
  18129. /**
  18130. * An event triggered when physic simulation has been done
  18131. * @type {BABYLON.Observable}
  18132. */
  18133. this.onAfterPhysicsObservable = new BABYLON.Observable();
  18134. /**
  18135. * An event triggered when the scene is ready
  18136. * @type {BABYLON.Observable}
  18137. */
  18138. this.onReadyObservable = new BABYLON.Observable();
  18139. /**
  18140. * An event triggered before rendering a camera
  18141. * @type {BABYLON.Observable}
  18142. */
  18143. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  18144. /**
  18145. * An event triggered after rendering a camera
  18146. * @type {BABYLON.Observable}
  18147. */
  18148. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  18149. /**
  18150. * An event triggered when active meshes evaluation is about to start
  18151. * @type {BABYLON.Observable}
  18152. */
  18153. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  18154. /**
  18155. * An event triggered when active meshes evaluation is done
  18156. * @type {BABYLON.Observable}
  18157. */
  18158. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  18159. /**
  18160. * An event triggered when particles rendering is about to start
  18161. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  18162. * @type {BABYLON.Observable}
  18163. */
  18164. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  18165. /**
  18166. * An event triggered when particles rendering is done
  18167. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  18168. * @type {BABYLON.Observable}
  18169. */
  18170. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  18171. /**
  18172. * An event triggered when sprites rendering is about to start
  18173. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  18174. * @type {BABYLON.Observable}
  18175. */
  18176. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  18177. /**
  18178. * An event triggered when sprites rendering is done
  18179. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  18180. * @type {BABYLON.Observable}
  18181. */
  18182. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  18183. /**
  18184. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  18185. * @type {BABYLON.Observable}
  18186. */
  18187. this.onDataLoadedObservable = new BABYLON.Observable();
  18188. /**
  18189. * An event triggered when a camera is created
  18190. * @type {BABYLON.Observable}
  18191. */
  18192. this.onNewCameraAddedObservable = new BABYLON.Observable();
  18193. /**
  18194. * An event triggered when a camera is removed
  18195. * @type {BABYLON.Observable}
  18196. */
  18197. this.onCameraRemovedObservable = new BABYLON.Observable();
  18198. /**
  18199. * An event triggered when a light is created
  18200. * @type {BABYLON.Observable}
  18201. */
  18202. this.onNewLightAddedObservable = new BABYLON.Observable();
  18203. /**
  18204. * An event triggered when a light is removed
  18205. * @type {BABYLON.Observable}
  18206. */
  18207. this.onLightRemovedObservable = new BABYLON.Observable();
  18208. /**
  18209. * An event triggered when a geometry is created
  18210. * @type {BABYLON.Observable}
  18211. */
  18212. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  18213. /**
  18214. * An event triggered when a geometry is removed
  18215. * @type {BABYLON.Observable}
  18216. */
  18217. this.onGeometryRemovedObservable = new BABYLON.Observable();
  18218. /**
  18219. * An event triggered when a transform node is created
  18220. * @type {BABYLON.Observable}
  18221. */
  18222. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  18223. /**
  18224. * An event triggered when a transform node is removed
  18225. * @type {BABYLON.Observable}
  18226. */
  18227. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  18228. /**
  18229. * An event triggered when a mesh is created
  18230. * @type {BABYLON.Observable}
  18231. */
  18232. this.onNewMeshAddedObservable = new BABYLON.Observable();
  18233. /**
  18234. * An event triggered when a mesh is removed
  18235. * @type {BABYLON.Observable}
  18236. */
  18237. this.onMeshRemovedObservable = new BABYLON.Observable();
  18238. /**
  18239. * An event triggered when render targets are about to be rendered
  18240. * Can happen multiple times per frame.
  18241. * @type {BABYLON.Observable}
  18242. */
  18243. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  18244. /**
  18245. * An event triggered when render targets were rendered.
  18246. * Can happen multiple times per frame.
  18247. * @type {BABYLON.Observable}
  18248. */
  18249. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  18250. /**
  18251. * An event triggered before calculating deterministic simulation step
  18252. * @type {BABYLON.Observable}
  18253. */
  18254. this.onBeforeStepObservable = new BABYLON.Observable();
  18255. /**
  18256. * An event triggered after calculating deterministic simulation step
  18257. * @type {BABYLON.Observable}
  18258. */
  18259. this.onAfterStepObservable = new BABYLON.Observable();
  18260. /**
  18261. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  18262. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  18263. * 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)
  18264. */
  18265. this.onRenderingGroupObservable = new BABYLON.Observable();
  18266. // Animations
  18267. this.animations = [];
  18268. /**
  18269. * 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).
  18270. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  18271. */
  18272. this.onPrePointerObservable = new BABYLON.Observable();
  18273. /**
  18274. * Observable event triggered each time an input event is received from the rendering canvas
  18275. */
  18276. this.onPointerObservable = new BABYLON.Observable();
  18277. this._meshPickProceed = false;
  18278. this._currentPickResult = null;
  18279. this._previousPickResult = null;
  18280. this._totalPointersPressed = 0;
  18281. this._doubleClickOccured = false;
  18282. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  18283. this.cameraToUseForPointers = null;
  18284. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  18285. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  18286. this._startingPointerTime = 0;
  18287. this._previousStartingPointerTime = 0;
  18288. // Deterministic lockstep
  18289. this._timeAccumulator = 0;
  18290. this._currentStepId = 0;
  18291. this._currentInternalStep = 0;
  18292. // Keyboard
  18293. /**
  18294. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  18295. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  18296. */
  18297. this.onPreKeyboardObservable = new BABYLON.Observable();
  18298. /**
  18299. * Observable event triggered each time an keyboard event is received from the hosting window
  18300. */
  18301. this.onKeyboardObservable = new BABYLON.Observable();
  18302. // Coordinate system
  18303. /**
  18304. * use right-handed coordinate system on this scene.
  18305. * @type {boolean}
  18306. */
  18307. this._useRightHandedSystem = false;
  18308. // Fog
  18309. this._fogEnabled = true;
  18310. this._fogMode = Scene.FOGMODE_NONE;
  18311. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  18312. this.fogDensity = 0.1;
  18313. this.fogStart = 0;
  18314. this.fogEnd = 1000.0;
  18315. // Lights
  18316. /**
  18317. * is shadow enabled on this scene.
  18318. * @type {boolean}
  18319. */
  18320. this._shadowsEnabled = true;
  18321. /**
  18322. * is light enabled on this scene.
  18323. * @type {boolean}
  18324. */
  18325. this._lightsEnabled = true;
  18326. /**
  18327. * All of the lights added to this scene.
  18328. * @see BABYLON.Light
  18329. * @type {BABYLON.Light[]}
  18330. */
  18331. this.lights = new Array();
  18332. // Cameras
  18333. /** All of the cameras added to this scene. */
  18334. this.cameras = new Array();
  18335. /** All of the active cameras added to this scene. */
  18336. this.activeCameras = new Array();
  18337. // Meshes
  18338. /**
  18339. * All of the tranform nodes added to this scene.
  18340. * @see BABYLON.TransformNode
  18341. * @type {BABYLON.TransformNode[]}
  18342. */
  18343. this.transformNodes = new Array();
  18344. /**
  18345. * All of the (abstract) meshes added to this scene.
  18346. * @see BABYLON.AbstractMesh
  18347. * @type {BABYLON.AbstractMesh[]}
  18348. */
  18349. this.meshes = new Array();
  18350. /**
  18351. * All of the animation groups added to this scene.
  18352. * @see BABYLON.AnimationGroup
  18353. * @type {BABYLON.AnimationGroup[]}
  18354. */
  18355. this.animationGroups = new Array();
  18356. // Geometries
  18357. this._geometries = new Array();
  18358. this.materials = new Array();
  18359. this.multiMaterials = new Array();
  18360. // Textures
  18361. this._texturesEnabled = true;
  18362. this.textures = new Array();
  18363. // Particles
  18364. this.particlesEnabled = true;
  18365. this.particleSystems = new Array();
  18366. // Sprites
  18367. this.spritesEnabled = true;
  18368. this.spriteManagers = new Array();
  18369. // Layers
  18370. this.layers = new Array();
  18371. this.highlightLayers = new Array();
  18372. // Skeletons
  18373. this._skeletonsEnabled = true;
  18374. this.skeletons = new Array();
  18375. // Morph targets
  18376. this.morphTargetManagers = new Array();
  18377. // Lens flares
  18378. this.lensFlaresEnabled = true;
  18379. this.lensFlareSystems = new Array();
  18380. // Collisions
  18381. this.collisionsEnabled = true;
  18382. /** Defines the gravity applied to this scene */
  18383. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  18384. // Postprocesses
  18385. this.postProcesses = new Array();
  18386. this.postProcessesEnabled = true;
  18387. // Customs render targets
  18388. this.renderTargetsEnabled = true;
  18389. this.dumpNextRenderTargets = false;
  18390. this.customRenderTargets = new Array();
  18391. // Imported meshes
  18392. this.importedMeshesFiles = new Array();
  18393. // Probes
  18394. this.probesEnabled = true;
  18395. this.reflectionProbes = new Array();
  18396. this._actionManagers = new Array();
  18397. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  18398. // Procedural textures
  18399. this.proceduralTexturesEnabled = true;
  18400. this._proceduralTextures = new Array();
  18401. this.soundTracks = new Array();
  18402. this._audioEnabled = true;
  18403. this._headphone = false;
  18404. // Performance counters
  18405. this._totalVertices = new BABYLON.PerfCounter();
  18406. this._activeIndices = new BABYLON.PerfCounter();
  18407. this._activeParticles = new BABYLON.PerfCounter();
  18408. this._activeBones = new BABYLON.PerfCounter();
  18409. this._animationTime = 0;
  18410. this.animationTimeScale = 1;
  18411. this._renderId = 0;
  18412. this._executeWhenReadyTimeoutId = -1;
  18413. this._intermediateRendering = false;
  18414. this._viewUpdateFlag = -1;
  18415. this._projectionUpdateFlag = -1;
  18416. this._alternateViewUpdateFlag = -1;
  18417. this._alternateProjectionUpdateFlag = -1;
  18418. this._toBeDisposed = new BABYLON.SmartArray(256);
  18419. this._pendingData = new Array();
  18420. this._isDisposed = false;
  18421. this._activeMeshes = new BABYLON.SmartArray(256);
  18422. this._processedMaterials = new BABYLON.SmartArray(256);
  18423. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  18424. this._activeParticleSystems = new BABYLON.SmartArray(256);
  18425. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  18426. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  18427. this._activeAnimatables = new Array();
  18428. this._transformMatrix = BABYLON.Matrix.Zero();
  18429. this._useAlternateCameraConfiguration = false;
  18430. this._alternateRendering = false;
  18431. this.requireLightSorting = false;
  18432. this._activeMeshesFrozen = false;
  18433. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  18434. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  18435. this._engine.scenes.push(this);
  18436. this._uid = null;
  18437. this._renderingManager = new BABYLON.RenderingManager(this);
  18438. this.postProcessManager = new BABYLON.PostProcessManager(this);
  18439. if (BABYLON.OutlineRenderer) {
  18440. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  18441. }
  18442. if (BABYLON.Tools.IsWindowObjectExist()) {
  18443. this.attachControl();
  18444. }
  18445. //simplification queue
  18446. if (BABYLON.SimplificationQueue) {
  18447. this.simplificationQueue = new BABYLON.SimplificationQueue();
  18448. }
  18449. //collision coordinator initialization. For now legacy per default.
  18450. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  18451. // Uniform Buffer
  18452. this._createUbo();
  18453. // Default Image processing definition.
  18454. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  18455. }
  18456. Object.defineProperty(Scene, "FOGMODE_NONE", {
  18457. /** The fog is deactivated */
  18458. get: function () {
  18459. return Scene._FOGMODE_NONE;
  18460. },
  18461. enumerable: true,
  18462. configurable: true
  18463. });
  18464. Object.defineProperty(Scene, "FOGMODE_EXP", {
  18465. /** The fog density is following an exponential function */
  18466. get: function () {
  18467. return Scene._FOGMODE_EXP;
  18468. },
  18469. enumerable: true,
  18470. configurable: true
  18471. });
  18472. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  18473. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  18474. get: function () {
  18475. return Scene._FOGMODE_EXP2;
  18476. },
  18477. enumerable: true,
  18478. configurable: true
  18479. });
  18480. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  18481. /** The fog density is following a linear function. */
  18482. get: function () {
  18483. return Scene._FOGMODE_LINEAR;
  18484. },
  18485. enumerable: true,
  18486. configurable: true
  18487. });
  18488. Object.defineProperty(Scene.prototype, "environmentTexture", {
  18489. /**
  18490. * Texture used in all pbr material as the reflection texture.
  18491. * As in the majority of the scene they are the same (exception for multi room and so on),
  18492. * this is easier to reference from here than from all the materials.
  18493. */
  18494. get: function () {
  18495. return this._environmentTexture;
  18496. },
  18497. /**
  18498. * Texture used in all pbr material as the reflection texture.
  18499. * As in the majority of the scene they are the same (exception for multi room and so on),
  18500. * this is easier to set here than in all the materials.
  18501. */
  18502. set: function (value) {
  18503. if (this._environmentTexture === value) {
  18504. return;
  18505. }
  18506. this._environmentTexture = value;
  18507. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18508. },
  18509. enumerable: true,
  18510. configurable: true
  18511. });
  18512. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  18513. /**
  18514. * Default image processing configuration used either in the rendering
  18515. * Forward main pass or through the imageProcessingPostProcess if present.
  18516. * As in the majority of the scene they are the same (exception for multi camera),
  18517. * this is easier to reference from here than from all the materials and post process.
  18518. *
  18519. * No setter as we it is a shared configuration, you can set the values instead.
  18520. */
  18521. get: function () {
  18522. return this._imageProcessingConfiguration;
  18523. },
  18524. enumerable: true,
  18525. configurable: true
  18526. });
  18527. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  18528. get: function () {
  18529. return this._forcePointsCloud;
  18530. },
  18531. set: function (value) {
  18532. if (this._forcePointsCloud === value) {
  18533. return;
  18534. }
  18535. this._forcePointsCloud = value;
  18536. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18537. },
  18538. enumerable: true,
  18539. configurable: true
  18540. });
  18541. Object.defineProperty(Scene.prototype, "onDispose", {
  18542. /** A function to be executed when this scene is disposed. */
  18543. set: function (callback) {
  18544. if (this._onDisposeObserver) {
  18545. this.onDisposeObservable.remove(this._onDisposeObserver);
  18546. }
  18547. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18548. },
  18549. enumerable: true,
  18550. configurable: true
  18551. });
  18552. Object.defineProperty(Scene.prototype, "beforeRender", {
  18553. /** A function to be executed before rendering this scene */
  18554. set: function (callback) {
  18555. if (this._onBeforeRenderObserver) {
  18556. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  18557. }
  18558. if (callback) {
  18559. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  18560. }
  18561. },
  18562. enumerable: true,
  18563. configurable: true
  18564. });
  18565. Object.defineProperty(Scene.prototype, "afterRender", {
  18566. /** A function to be executed after rendering this scene */
  18567. set: function (callback) {
  18568. if (this._onAfterRenderObserver) {
  18569. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  18570. }
  18571. if (callback) {
  18572. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  18573. }
  18574. },
  18575. enumerable: true,
  18576. configurable: true
  18577. });
  18578. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  18579. set: function (callback) {
  18580. if (this._onBeforeCameraRenderObserver) {
  18581. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  18582. }
  18583. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  18584. },
  18585. enumerable: true,
  18586. configurable: true
  18587. });
  18588. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  18589. set: function (callback) {
  18590. if (this._onAfterCameraRenderObserver) {
  18591. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  18592. }
  18593. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  18594. },
  18595. enumerable: true,
  18596. configurable: true
  18597. });
  18598. Object.defineProperty(Scene.prototype, "gamepadManager", {
  18599. get: function () {
  18600. if (!this._gamepadManager) {
  18601. this._gamepadManager = new BABYLON.GamepadManager(this);
  18602. }
  18603. return this._gamepadManager;
  18604. },
  18605. enumerable: true,
  18606. configurable: true
  18607. });
  18608. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  18609. get: function () {
  18610. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  18611. },
  18612. enumerable: true,
  18613. configurable: true
  18614. });
  18615. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  18616. get: function () {
  18617. return this._useRightHandedSystem;
  18618. },
  18619. set: function (value) {
  18620. if (this._useRightHandedSystem === value) {
  18621. return;
  18622. }
  18623. this._useRightHandedSystem = value;
  18624. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18625. },
  18626. enumerable: true,
  18627. configurable: true
  18628. });
  18629. Scene.prototype.setStepId = function (newStepId) {
  18630. this._currentStepId = newStepId;
  18631. };
  18632. ;
  18633. Scene.prototype.getStepId = function () {
  18634. return this._currentStepId;
  18635. };
  18636. ;
  18637. Scene.prototype.getInternalStep = function () {
  18638. return this._currentInternalStep;
  18639. };
  18640. ;
  18641. Object.defineProperty(Scene.prototype, "fogEnabled", {
  18642. get: function () {
  18643. return this._fogEnabled;
  18644. },
  18645. /**
  18646. * is fog enabled on this scene.
  18647. */
  18648. set: function (value) {
  18649. if (this._fogEnabled === value) {
  18650. return;
  18651. }
  18652. this._fogEnabled = value;
  18653. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18654. },
  18655. enumerable: true,
  18656. configurable: true
  18657. });
  18658. Object.defineProperty(Scene.prototype, "fogMode", {
  18659. get: function () {
  18660. return this._fogMode;
  18661. },
  18662. set: function (value) {
  18663. if (this._fogMode === value) {
  18664. return;
  18665. }
  18666. this._fogMode = value;
  18667. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18668. },
  18669. enumerable: true,
  18670. configurable: true
  18671. });
  18672. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  18673. get: function () {
  18674. return this._shadowsEnabled;
  18675. },
  18676. set: function (value) {
  18677. if (this._shadowsEnabled === value) {
  18678. return;
  18679. }
  18680. this._shadowsEnabled = value;
  18681. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  18682. },
  18683. enumerable: true,
  18684. configurable: true
  18685. });
  18686. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  18687. get: function () {
  18688. return this._lightsEnabled;
  18689. },
  18690. set: function (value) {
  18691. if (this._lightsEnabled === value) {
  18692. return;
  18693. }
  18694. this._lightsEnabled = value;
  18695. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  18696. },
  18697. enumerable: true,
  18698. configurable: true
  18699. });
  18700. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  18701. /** The default material used on meshes when no material is affected */
  18702. get: function () {
  18703. if (!this._defaultMaterial) {
  18704. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  18705. }
  18706. return this._defaultMaterial;
  18707. },
  18708. /** The default material used on meshes when no material is affected */
  18709. set: function (value) {
  18710. this._defaultMaterial = value;
  18711. },
  18712. enumerable: true,
  18713. configurable: true
  18714. });
  18715. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  18716. get: function () {
  18717. return this._texturesEnabled;
  18718. },
  18719. set: function (value) {
  18720. if (this._texturesEnabled === value) {
  18721. return;
  18722. }
  18723. this._texturesEnabled = value;
  18724. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18725. },
  18726. enumerable: true,
  18727. configurable: true
  18728. });
  18729. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  18730. get: function () {
  18731. return this._skeletonsEnabled;
  18732. },
  18733. set: function (value) {
  18734. if (this._skeletonsEnabled === value) {
  18735. return;
  18736. }
  18737. this._skeletonsEnabled = value;
  18738. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  18739. },
  18740. enumerable: true,
  18741. configurable: true
  18742. });
  18743. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  18744. get: function () {
  18745. if (!this._postProcessRenderPipelineManager) {
  18746. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  18747. }
  18748. return this._postProcessRenderPipelineManager;
  18749. },
  18750. enumerable: true,
  18751. configurable: true
  18752. });
  18753. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  18754. get: function () {
  18755. if (!this._mainSoundTrack) {
  18756. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  18757. }
  18758. return this._mainSoundTrack;
  18759. },
  18760. enumerable: true,
  18761. configurable: true
  18762. });
  18763. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  18764. get: function () {
  18765. return this._alternateRendering;
  18766. },
  18767. enumerable: true,
  18768. configurable: true
  18769. });
  18770. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  18771. get: function () {
  18772. return this._frustumPlanes;
  18773. },
  18774. enumerable: true,
  18775. configurable: true
  18776. });
  18777. Object.defineProperty(Scene.prototype, "debugLayer", {
  18778. // Properties
  18779. get: function () {
  18780. if (!this._debugLayer) {
  18781. this._debugLayer = new BABYLON.DebugLayer(this);
  18782. }
  18783. return this._debugLayer;
  18784. },
  18785. enumerable: true,
  18786. configurable: true
  18787. });
  18788. Object.defineProperty(Scene.prototype, "workerCollisions", {
  18789. get: function () {
  18790. return this._workerCollisions;
  18791. },
  18792. set: function (enabled) {
  18793. if (!BABYLON.CollisionCoordinatorLegacy) {
  18794. return;
  18795. }
  18796. enabled = (enabled && !!Worker);
  18797. this._workerCollisions = enabled;
  18798. if (this.collisionCoordinator) {
  18799. this.collisionCoordinator.destroy();
  18800. }
  18801. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  18802. this.collisionCoordinator.init(this);
  18803. },
  18804. enumerable: true,
  18805. configurable: true
  18806. });
  18807. Object.defineProperty(Scene.prototype, "selectionOctree", {
  18808. get: function () {
  18809. return this._selectionOctree;
  18810. },
  18811. enumerable: true,
  18812. configurable: true
  18813. });
  18814. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  18815. /**
  18816. * The mesh that is currently under the pointer.
  18817. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  18818. */
  18819. get: function () {
  18820. return this._pointerOverMesh;
  18821. },
  18822. enumerable: true,
  18823. configurable: true
  18824. });
  18825. Object.defineProperty(Scene.prototype, "pointerX", {
  18826. /**
  18827. * Current on-screen X position of the pointer
  18828. * @return {number} X position of the pointer
  18829. */
  18830. get: function () {
  18831. return this._pointerX;
  18832. },
  18833. enumerable: true,
  18834. configurable: true
  18835. });
  18836. Object.defineProperty(Scene.prototype, "pointerY", {
  18837. /**
  18838. * Current on-screen Y position of the pointer
  18839. * @return {number} Y position of the pointer
  18840. */
  18841. get: function () {
  18842. return this._pointerY;
  18843. },
  18844. enumerable: true,
  18845. configurable: true
  18846. });
  18847. Scene.prototype.getCachedMaterial = function () {
  18848. return this._cachedMaterial;
  18849. };
  18850. Scene.prototype.getCachedEffect = function () {
  18851. return this._cachedEffect;
  18852. };
  18853. Scene.prototype.getCachedVisibility = function () {
  18854. return this._cachedVisibility;
  18855. };
  18856. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  18857. if (visibility === void 0) { visibility = 1; }
  18858. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  18859. };
  18860. Scene.prototype.getBoundingBoxRenderer = function () {
  18861. if (!this._boundingBoxRenderer) {
  18862. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  18863. }
  18864. return this._boundingBoxRenderer;
  18865. };
  18866. Scene.prototype.getOutlineRenderer = function () {
  18867. return this._outlineRenderer;
  18868. };
  18869. Scene.prototype.getEngine = function () {
  18870. return this._engine;
  18871. };
  18872. Scene.prototype.getTotalVertices = function () {
  18873. return this._totalVertices.current;
  18874. };
  18875. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  18876. get: function () {
  18877. return this._totalVertices;
  18878. },
  18879. enumerable: true,
  18880. configurable: true
  18881. });
  18882. Scene.prototype.getActiveIndices = function () {
  18883. return this._activeIndices.current;
  18884. };
  18885. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  18886. get: function () {
  18887. return this._activeIndices;
  18888. },
  18889. enumerable: true,
  18890. configurable: true
  18891. });
  18892. Scene.prototype.getActiveParticles = function () {
  18893. return this._activeParticles.current;
  18894. };
  18895. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  18896. get: function () {
  18897. return this._activeParticles;
  18898. },
  18899. enumerable: true,
  18900. configurable: true
  18901. });
  18902. Scene.prototype.getActiveBones = function () {
  18903. return this._activeBones.current;
  18904. };
  18905. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  18906. get: function () {
  18907. return this._activeBones;
  18908. },
  18909. enumerable: true,
  18910. configurable: true
  18911. });
  18912. // Stats
  18913. Scene.prototype.getInterFramePerfCounter = function () {
  18914. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18915. return 0;
  18916. };
  18917. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  18918. get: function () {
  18919. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18920. return null;
  18921. },
  18922. enumerable: true,
  18923. configurable: true
  18924. });
  18925. Scene.prototype.getLastFrameDuration = function () {
  18926. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  18927. return 0;
  18928. };
  18929. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  18930. get: function () {
  18931. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18932. return null;
  18933. },
  18934. enumerable: true,
  18935. configurable: true
  18936. });
  18937. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  18938. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  18939. return 0;
  18940. };
  18941. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  18942. get: function () {
  18943. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18944. return null;
  18945. },
  18946. enumerable: true,
  18947. configurable: true
  18948. });
  18949. Scene.prototype.getActiveMeshes = function () {
  18950. return this._activeMeshes;
  18951. };
  18952. Scene.prototype.getRenderTargetsDuration = function () {
  18953. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  18954. return 0;
  18955. };
  18956. Scene.prototype.getRenderDuration = function () {
  18957. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  18958. return 0;
  18959. };
  18960. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  18961. get: function () {
  18962. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18963. return null;
  18964. },
  18965. enumerable: true,
  18966. configurable: true
  18967. });
  18968. Scene.prototype.getParticlesDuration = function () {
  18969. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  18970. return 0;
  18971. };
  18972. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  18973. get: function () {
  18974. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18975. return null;
  18976. },
  18977. enumerable: true,
  18978. configurable: true
  18979. });
  18980. Scene.prototype.getSpritesDuration = function () {
  18981. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  18982. return 0;
  18983. };
  18984. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  18985. get: function () {
  18986. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  18987. return null;
  18988. },
  18989. enumerable: true,
  18990. configurable: true
  18991. });
  18992. Scene.prototype.getAnimationRatio = function () {
  18993. return this._animationRatio;
  18994. };
  18995. Scene.prototype.getRenderId = function () {
  18996. return this._renderId;
  18997. };
  18998. Scene.prototype.incrementRenderId = function () {
  18999. this._renderId++;
  19000. };
  19001. Scene.prototype._updatePointerPosition = function (evt) {
  19002. var canvasRect = this._engine.getRenderingCanvasClientRect();
  19003. if (!canvasRect) {
  19004. return;
  19005. }
  19006. this._pointerX = evt.clientX - canvasRect.left;
  19007. this._pointerY = evt.clientY - canvasRect.top;
  19008. this._unTranslatedPointerX = this._pointerX;
  19009. this._unTranslatedPointerY = this._pointerY;
  19010. };
  19011. Scene.prototype._createUbo = function () {
  19012. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  19013. this._sceneUbo.addUniform("viewProjection", 16);
  19014. this._sceneUbo.addUniform("view", 16);
  19015. };
  19016. Scene.prototype._createAlternateUbo = function () {
  19017. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  19018. this._alternateSceneUbo.addUniform("viewProjection", 16);
  19019. this._alternateSceneUbo.addUniform("view", 16);
  19020. };
  19021. // Pointers handling
  19022. /**
  19023. * Use this method to simulate a pointer move on a mesh
  19024. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  19025. */
  19026. Scene.prototype.simulatePointerMove = function (pickResult) {
  19027. var evt = new PointerEvent("pointermove");
  19028. return this._processPointerMove(pickResult, evt);
  19029. };
  19030. Scene.prototype._processPointerMove = function (pickResult, evt) {
  19031. var canvas = this._engine.getRenderingCanvas();
  19032. if (!canvas) {
  19033. return this;
  19034. }
  19035. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  19036. this.setPointerOverSprite(null);
  19037. this.setPointerOverMesh(pickResult.pickedMesh);
  19038. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  19039. if (this._pointerOverMesh.actionManager.hoverCursor) {
  19040. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  19041. }
  19042. else {
  19043. canvas.style.cursor = this.hoverCursor;
  19044. }
  19045. }
  19046. else {
  19047. canvas.style.cursor = this.defaultCursor;
  19048. }
  19049. }
  19050. else {
  19051. this.setPointerOverMesh(null);
  19052. // Sprites
  19053. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  19054. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  19055. this.setPointerOverSprite(pickResult.pickedSprite);
  19056. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  19057. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  19058. }
  19059. else {
  19060. canvas.style.cursor = this.hoverCursor;
  19061. }
  19062. }
  19063. else {
  19064. this.setPointerOverSprite(null);
  19065. // Restore pointer
  19066. canvas.style.cursor = this.defaultCursor;
  19067. }
  19068. }
  19069. if (pickResult) {
  19070. if (this.onPointerMove) {
  19071. this.onPointerMove(evt, pickResult);
  19072. }
  19073. if (this.onPointerObservable.hasObservers()) {
  19074. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  19075. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  19076. this.onPointerObservable.notifyObservers(pi, type);
  19077. }
  19078. }
  19079. return this;
  19080. };
  19081. /**
  19082. * Use this method to simulate a pointer down on a mesh
  19083. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  19084. */
  19085. Scene.prototype.simulatePointerDown = function (pickResult) {
  19086. var evt = new PointerEvent("pointerdown");
  19087. return this._processPointerDown(pickResult, evt);
  19088. };
  19089. Scene.prototype._processPointerDown = function (pickResult, evt) {
  19090. var _this = this;
  19091. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  19092. this._pickedDownMesh = pickResult.pickedMesh;
  19093. var actionManager = pickResult.pickedMesh.actionManager;
  19094. if (actionManager) {
  19095. if (actionManager.hasPickTriggers) {
  19096. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19097. switch (evt.button) {
  19098. case 0:
  19099. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19100. break;
  19101. case 1:
  19102. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19103. break;
  19104. case 2:
  19105. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19106. break;
  19107. }
  19108. }
  19109. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  19110. window.setTimeout(function () {
  19111. 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);
  19112. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  19113. if (_this._totalPointersPressed !== 0 &&
  19114. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  19115. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  19116. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  19117. _this._startingPointerTime = 0;
  19118. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19119. }
  19120. }
  19121. }, Scene.LongPressDelay);
  19122. }
  19123. }
  19124. }
  19125. if (pickResult) {
  19126. if (this.onPointerDown) {
  19127. this.onPointerDown(evt, pickResult);
  19128. }
  19129. if (this.onPointerObservable.hasObservers()) {
  19130. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  19131. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  19132. this.onPointerObservable.notifyObservers(pi, type);
  19133. }
  19134. }
  19135. return this;
  19136. };
  19137. /**
  19138. * Use this method to simulate a pointer up on a mesh
  19139. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  19140. */
  19141. Scene.prototype.simulatePointerUp = function (pickResult) {
  19142. var evt = new PointerEvent("pointerup");
  19143. var clickInfo = new ClickInfo();
  19144. clickInfo.singleClick = true;
  19145. clickInfo.ignore = true;
  19146. return this._processPointerUp(pickResult, evt, clickInfo);
  19147. };
  19148. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  19149. if (pickResult && pickResult && pickResult.pickedMesh) {
  19150. this._pickedUpMesh = pickResult.pickedMesh;
  19151. if (this._pickedDownMesh === this._pickedUpMesh) {
  19152. if (this.onPointerPick) {
  19153. this.onPointerPick(evt, pickResult);
  19154. }
  19155. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  19156. var type = BABYLON.PointerEventTypes.POINTERPICK;
  19157. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  19158. this.onPointerObservable.notifyObservers(pi, type);
  19159. }
  19160. }
  19161. if (pickResult.pickedMesh.actionManager) {
  19162. if (clickInfo.ignore) {
  19163. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19164. }
  19165. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  19166. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19167. }
  19168. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  19169. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19170. }
  19171. }
  19172. }
  19173. if (this._pickedDownMesh &&
  19174. this._pickedDownMesh.actionManager &&
  19175. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  19176. this._pickedDownMesh !== this._pickedUpMesh) {
  19177. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  19178. }
  19179. if (this.onPointerUp) {
  19180. this.onPointerUp(evt, pickResult);
  19181. }
  19182. if (this.onPointerObservable.hasObservers()) {
  19183. if (!clickInfo.ignore) {
  19184. if (!clickInfo.hasSwiped) {
  19185. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  19186. var type = BABYLON.PointerEventTypes.POINTERTAP;
  19187. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  19188. this.onPointerObservable.notifyObservers(pi, type);
  19189. }
  19190. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  19191. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  19192. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  19193. this.onPointerObservable.notifyObservers(pi, type);
  19194. }
  19195. }
  19196. }
  19197. else {
  19198. var type = BABYLON.PointerEventTypes.POINTERUP;
  19199. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  19200. this.onPointerObservable.notifyObservers(pi, type);
  19201. }
  19202. }
  19203. return this;
  19204. };
  19205. /**
  19206. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  19207. * @param attachUp defines if you want to attach events to pointerup
  19208. * @param attachDown defines if you want to attach events to pointerdown
  19209. * @param attachMove defines if you want to attach events to pointermove
  19210. */
  19211. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  19212. var _this = this;
  19213. if (attachUp === void 0) { attachUp = true; }
  19214. if (attachDown === void 0) { attachDown = true; }
  19215. if (attachMove === void 0) { attachMove = true; }
  19216. this._initActionManager = function (act, clickInfo) {
  19217. if (!_this._meshPickProceed) {
  19218. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  19219. _this._currentPickResult = pickResult;
  19220. if (pickResult) {
  19221. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  19222. }
  19223. _this._meshPickProceed = true;
  19224. }
  19225. return act;
  19226. };
  19227. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  19228. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  19229. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  19230. btn !== _this._previousButtonPressed) {
  19231. _this._doubleClickOccured = false;
  19232. clickInfo.singleClick = true;
  19233. clickInfo.ignore = false;
  19234. cb(clickInfo, _this._currentPickResult);
  19235. }
  19236. };
  19237. this._initClickEvent = function (obs1, obs2, evt, cb) {
  19238. var clickInfo = new ClickInfo();
  19239. _this._currentPickResult = null;
  19240. var act = null;
  19241. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  19242. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  19243. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  19244. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  19245. act = _this._initActionManager(act, clickInfo);
  19246. if (act)
  19247. checkPicking = act.hasPickTriggers;
  19248. }
  19249. if (checkPicking) {
  19250. var btn = evt.button;
  19251. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  19252. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  19253. if (!clickInfo.hasSwiped) {
  19254. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  19255. if (!checkSingleClickImmediately) {
  19256. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  19257. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  19258. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  19259. act = _this._initActionManager(act, clickInfo);
  19260. if (act)
  19261. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  19262. }
  19263. }
  19264. if (checkSingleClickImmediately) {
  19265. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  19266. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  19267. btn !== _this._previousButtonPressed) {
  19268. clickInfo.singleClick = true;
  19269. cb(clickInfo, _this._currentPickResult);
  19270. }
  19271. }
  19272. else {
  19273. // wait that no double click has been raised during the double click delay
  19274. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  19275. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  19276. }
  19277. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  19278. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  19279. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  19280. act = _this._initActionManager(act, clickInfo);
  19281. if (act)
  19282. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  19283. }
  19284. if (checkDoubleClick) {
  19285. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  19286. if (btn === _this._previousButtonPressed &&
  19287. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  19288. !_this._doubleClickOccured) {
  19289. // pointer has not moved for 2 clicks, it's a double click
  19290. if (!clickInfo.hasSwiped &&
  19291. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  19292. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  19293. _this._previousStartingPointerTime = 0;
  19294. _this._doubleClickOccured = true;
  19295. clickInfo.doubleClick = true;
  19296. clickInfo.ignore = false;
  19297. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  19298. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  19299. }
  19300. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  19301. cb(clickInfo, _this._currentPickResult);
  19302. }
  19303. else {
  19304. _this._doubleClickOccured = false;
  19305. _this._previousStartingPointerTime = _this._startingPointerTime;
  19306. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  19307. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  19308. _this._previousButtonPressed = btn;
  19309. if (Scene.ExclusiveDoubleClickMode) {
  19310. if (_this._previousDelayedSimpleClickTimeout) {
  19311. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  19312. }
  19313. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  19314. cb(clickInfo, _this._previousPickResult);
  19315. }
  19316. else {
  19317. cb(clickInfo, _this._currentPickResult);
  19318. }
  19319. }
  19320. }
  19321. else {
  19322. _this._doubleClickOccured = false;
  19323. _this._previousStartingPointerTime = _this._startingPointerTime;
  19324. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  19325. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  19326. _this._previousButtonPressed = btn;
  19327. }
  19328. }
  19329. }
  19330. }
  19331. clickInfo.ignore = true;
  19332. cb(clickInfo, _this._currentPickResult);
  19333. };
  19334. this._spritePredicate = function (sprite) {
  19335. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  19336. };
  19337. this._onPointerMove = function (evt) {
  19338. _this._updatePointerPosition(evt);
  19339. // PreObservable support
  19340. if (_this.onPrePointerObservable.hasObservers()) {
  19341. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  19342. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19343. _this.onPrePointerObservable.notifyObservers(pi, type);
  19344. if (pi.skipOnPointerObservable) {
  19345. return;
  19346. }
  19347. }
  19348. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19349. return;
  19350. }
  19351. if (!_this.pointerMovePredicate) {
  19352. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  19353. }
  19354. // Meshes
  19355. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  19356. _this._processPointerMove(pickResult, evt);
  19357. };
  19358. this._onPointerDown = function (evt) {
  19359. _this._totalPointersPressed++;
  19360. _this._pickedDownMesh = null;
  19361. _this._meshPickProceed = false;
  19362. _this._updatePointerPosition(evt);
  19363. if (_this.preventDefaultOnPointerDown && canvas) {
  19364. evt.preventDefault();
  19365. canvas.focus();
  19366. }
  19367. // PreObservable support
  19368. if (_this.onPrePointerObservable.hasObservers()) {
  19369. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  19370. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19371. _this.onPrePointerObservable.notifyObservers(pi, type);
  19372. if (pi.skipOnPointerObservable) {
  19373. return;
  19374. }
  19375. }
  19376. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19377. return;
  19378. }
  19379. _this._startingPointerPosition.x = _this._pointerX;
  19380. _this._startingPointerPosition.y = _this._pointerY;
  19381. _this._startingPointerTime = new Date().getTime();
  19382. if (!_this.pointerDownPredicate) {
  19383. _this.pointerDownPredicate = function (mesh) {
  19384. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  19385. };
  19386. }
  19387. // Meshes
  19388. _this._pickedDownMesh = null;
  19389. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  19390. _this._processPointerDown(pickResult, evt);
  19391. // Sprites
  19392. _this._pickedDownSprite = null;
  19393. if (_this.spriteManagers.length > 0) {
  19394. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  19395. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  19396. if (pickResult.pickedSprite.actionManager) {
  19397. _this._pickedDownSprite = pickResult.pickedSprite;
  19398. switch (evt.button) {
  19399. case 0:
  19400. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19401. break;
  19402. case 1:
  19403. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19404. break;
  19405. case 2:
  19406. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19407. break;
  19408. }
  19409. if (pickResult.pickedSprite.actionManager) {
  19410. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19411. }
  19412. }
  19413. }
  19414. }
  19415. };
  19416. this._onPointerUp = function (evt) {
  19417. if (_this._totalPointersPressed === 0) {
  19418. return; // So we need to test it the pointer down was pressed before.
  19419. }
  19420. _this._totalPointersPressed--;
  19421. _this._pickedUpMesh = null;
  19422. _this._meshPickProceed = false;
  19423. _this._updatePointerPosition(evt);
  19424. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  19425. // PreObservable support
  19426. if (_this.onPrePointerObservable.hasObservers()) {
  19427. if (!clickInfo.ignore) {
  19428. if (!clickInfo.hasSwiped) {
  19429. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  19430. var type = BABYLON.PointerEventTypes.POINTERTAP;
  19431. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19432. _this.onPrePointerObservable.notifyObservers(pi, type);
  19433. if (pi.skipOnPointerObservable) {
  19434. return;
  19435. }
  19436. }
  19437. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  19438. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  19439. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19440. _this.onPrePointerObservable.notifyObservers(pi, type);
  19441. if (pi.skipOnPointerObservable) {
  19442. return;
  19443. }
  19444. }
  19445. }
  19446. }
  19447. else {
  19448. var type = BABYLON.PointerEventTypes.POINTERUP;
  19449. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19450. _this.onPrePointerObservable.notifyObservers(pi, type);
  19451. if (pi.skipOnPointerObservable) {
  19452. return;
  19453. }
  19454. }
  19455. }
  19456. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19457. return;
  19458. }
  19459. if (!_this.pointerUpPredicate) {
  19460. _this.pointerUpPredicate = function (mesh) {
  19461. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  19462. };
  19463. }
  19464. // Meshes
  19465. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  19466. _this._initActionManager(null, clickInfo);
  19467. }
  19468. if (!pickResult) {
  19469. pickResult = _this._currentPickResult;
  19470. }
  19471. _this._processPointerUp(pickResult, evt, clickInfo);
  19472. // Sprites
  19473. if (_this.spriteManagers.length > 0) {
  19474. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  19475. if (spritePickResult) {
  19476. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  19477. if (spritePickResult.pickedSprite.actionManager) {
  19478. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  19479. if (spritePickResult.pickedSprite.actionManager) {
  19480. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  19481. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  19482. }
  19483. }
  19484. }
  19485. }
  19486. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  19487. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  19488. }
  19489. }
  19490. }
  19491. _this._previousPickResult = _this._currentPickResult;
  19492. });
  19493. };
  19494. this._onKeyDown = function (evt) {
  19495. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  19496. if (_this.onPreKeyboardObservable.hasObservers()) {
  19497. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  19498. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  19499. if (pi.skipOnPointerObservable) {
  19500. return;
  19501. }
  19502. }
  19503. if (_this.onKeyboardObservable.hasObservers()) {
  19504. var pi = new BABYLON.KeyboardInfo(type, evt);
  19505. _this.onKeyboardObservable.notifyObservers(pi, type);
  19506. }
  19507. if (_this.actionManager) {
  19508. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  19509. }
  19510. };
  19511. this._onKeyUp = function (evt) {
  19512. var type = BABYLON.KeyboardEventTypes.KEYUP;
  19513. if (_this.onPreKeyboardObservable.hasObservers()) {
  19514. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  19515. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  19516. if (pi.skipOnPointerObservable) {
  19517. return;
  19518. }
  19519. }
  19520. if (_this.onKeyboardObservable.hasObservers()) {
  19521. var pi = new BABYLON.KeyboardInfo(type, evt);
  19522. _this.onKeyboardObservable.notifyObservers(pi, type);
  19523. }
  19524. if (_this.actionManager) {
  19525. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  19526. }
  19527. };
  19528. var engine = this.getEngine();
  19529. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  19530. if (!canvas) {
  19531. return;
  19532. }
  19533. canvas.addEventListener("keydown", _this._onKeyDown, false);
  19534. canvas.addEventListener("keyup", _this._onKeyUp, false);
  19535. });
  19536. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  19537. if (!canvas) {
  19538. return;
  19539. }
  19540. canvas.removeEventListener("keydown", _this._onKeyDown);
  19541. canvas.removeEventListener("keyup", _this._onKeyUp);
  19542. });
  19543. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  19544. var canvas = this._engine.getRenderingCanvas();
  19545. if (!canvas) {
  19546. return;
  19547. }
  19548. if (attachMove) {
  19549. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  19550. // Wheel
  19551. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  19552. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  19553. }
  19554. if (attachDown) {
  19555. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  19556. }
  19557. if (attachUp) {
  19558. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  19559. }
  19560. canvas.tabIndex = 1;
  19561. };
  19562. Scene.prototype.detachControl = function () {
  19563. var engine = this.getEngine();
  19564. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  19565. var canvas = engine.getRenderingCanvas();
  19566. if (!canvas) {
  19567. return;
  19568. }
  19569. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  19570. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  19571. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  19572. if (this._onCanvasBlurObserver) {
  19573. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  19574. }
  19575. if (this._onCanvasFocusObserver) {
  19576. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  19577. }
  19578. // Wheel
  19579. canvas.removeEventListener('mousewheel', this._onPointerMove);
  19580. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  19581. // Keyboard
  19582. canvas.removeEventListener("keydown", this._onKeyDown);
  19583. canvas.removeEventListener("keyup", this._onKeyUp);
  19584. // Observables
  19585. this.onKeyboardObservable.clear();
  19586. this.onPreKeyboardObservable.clear();
  19587. this.onPointerObservable.clear();
  19588. this.onPrePointerObservable.clear();
  19589. };
  19590. // Ready
  19591. Scene.prototype.isReady = function () {
  19592. if (this._isDisposed) {
  19593. return false;
  19594. }
  19595. if (this._pendingData.length > 0) {
  19596. return false;
  19597. }
  19598. var index;
  19599. // Geometries
  19600. for (index = 0; index < this._geometries.length; index++) {
  19601. var geometry = this._geometries[index];
  19602. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19603. return false;
  19604. }
  19605. }
  19606. // Meshes
  19607. for (index = 0; index < this.meshes.length; index++) {
  19608. var mesh = this.meshes[index];
  19609. if (!mesh.isEnabled()) {
  19610. continue;
  19611. }
  19612. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  19613. continue;
  19614. }
  19615. if (!mesh.isReady()) {
  19616. return false;
  19617. }
  19618. var mat = mesh.material;
  19619. if (mat) {
  19620. if (!mat.isReady(mesh)) {
  19621. return false;
  19622. }
  19623. }
  19624. }
  19625. return true;
  19626. };
  19627. Scene.prototype.resetCachedMaterial = function () {
  19628. this._cachedMaterial = null;
  19629. this._cachedEffect = null;
  19630. this._cachedVisibility = null;
  19631. };
  19632. Scene.prototype.registerBeforeRender = function (func) {
  19633. this.onBeforeRenderObservable.add(func);
  19634. };
  19635. Scene.prototype.unregisterBeforeRender = function (func) {
  19636. this.onBeforeRenderObservable.removeCallback(func);
  19637. };
  19638. Scene.prototype.registerAfterRender = function (func) {
  19639. this.onAfterRenderObservable.add(func);
  19640. };
  19641. Scene.prototype.unregisterAfterRender = function (func) {
  19642. this.onAfterRenderObservable.removeCallback(func);
  19643. };
  19644. Scene.prototype._addPendingData = function (data) {
  19645. this._pendingData.push(data);
  19646. };
  19647. Scene.prototype._removePendingData = function (data) {
  19648. var wasLoading = this.isLoading;
  19649. var index = this._pendingData.indexOf(data);
  19650. if (index !== -1) {
  19651. this._pendingData.splice(index, 1);
  19652. }
  19653. if (wasLoading && !this.isLoading) {
  19654. this.onDataLoadedObservable.notifyObservers(this);
  19655. }
  19656. };
  19657. Scene.prototype.getWaitingItemsCount = function () {
  19658. return this._pendingData.length;
  19659. };
  19660. Object.defineProperty(Scene.prototype, "isLoading", {
  19661. get: function () {
  19662. return this._pendingData.length > 0;
  19663. },
  19664. enumerable: true,
  19665. configurable: true
  19666. });
  19667. /**
  19668. * Registers a function to be executed when the scene is ready.
  19669. * @param {Function} func - the function to be executed.
  19670. */
  19671. Scene.prototype.executeWhenReady = function (func) {
  19672. var _this = this;
  19673. this.onReadyObservable.add(func);
  19674. if (this._executeWhenReadyTimeoutId !== -1) {
  19675. return;
  19676. }
  19677. this._executeWhenReadyTimeoutId = setTimeout(function () {
  19678. _this._checkIsReady();
  19679. }, 150);
  19680. };
  19681. Scene.prototype._checkIsReady = function () {
  19682. var _this = this;
  19683. if (this.isReady()) {
  19684. this.onReadyObservable.notifyObservers(this);
  19685. this.onReadyObservable.clear();
  19686. this._executeWhenReadyTimeoutId = -1;
  19687. return;
  19688. }
  19689. this._executeWhenReadyTimeoutId = setTimeout(function () {
  19690. _this._checkIsReady();
  19691. }, 150);
  19692. };
  19693. // Animations
  19694. /**
  19695. * Will start the animation sequence of a given target
  19696. * @param target - the target
  19697. * @param {number} from - from which frame should animation start
  19698. * @param {number} to - till which frame should animation run.
  19699. * @param {boolean} [loop] - should the animation loop
  19700. * @param {number} [speedRatio] - the speed in which to run the animation
  19701. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  19702. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  19703. * Returns {BABYLON.Animatable} the animatable object created for this animation
  19704. * See BABYLON.Animatable
  19705. */
  19706. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  19707. if (speedRatio === void 0) { speedRatio = 1.0; }
  19708. if (from > to && speedRatio > 0) {
  19709. speedRatio *= -1;
  19710. }
  19711. this.stopAnimation(target);
  19712. if (!animatable) {
  19713. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  19714. }
  19715. // Local animations
  19716. if (target.animations) {
  19717. animatable.appendAnimations(target, target.animations);
  19718. }
  19719. // Children animations
  19720. if (target.getAnimatables) {
  19721. var animatables = target.getAnimatables();
  19722. for (var index = 0; index < animatables.length; index++) {
  19723. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  19724. }
  19725. }
  19726. animatable.reset();
  19727. return animatable;
  19728. };
  19729. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  19730. if (speedRatio === undefined) {
  19731. speedRatio = 1.0;
  19732. }
  19733. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  19734. return animatable;
  19735. };
  19736. Scene.prototype.getAnimatableByTarget = function (target) {
  19737. for (var index = 0; index < this._activeAnimatables.length; index++) {
  19738. if (this._activeAnimatables[index].target === target) {
  19739. return this._activeAnimatables[index];
  19740. }
  19741. }
  19742. return null;
  19743. };
  19744. Object.defineProperty(Scene.prototype, "Animatables", {
  19745. get: function () {
  19746. return this._activeAnimatables;
  19747. },
  19748. enumerable: true,
  19749. configurable: true
  19750. });
  19751. /**
  19752. * Will stop the animation of the given target
  19753. * @param target - the target
  19754. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  19755. * @see beginAnimation
  19756. */
  19757. Scene.prototype.stopAnimation = function (target, animationName) {
  19758. var animatable = this.getAnimatableByTarget(target);
  19759. if (animatable) {
  19760. animatable.stop(animationName);
  19761. }
  19762. };
  19763. /**
  19764. * Stops and removes all animations that have been applied to the scene
  19765. */
  19766. Scene.prototype.stopAllAnimations = function () {
  19767. if (this._activeAnimatables) {
  19768. for (var i = 0; i < this._activeAnimatables.length; i++) {
  19769. this._activeAnimatables[i].stop();
  19770. }
  19771. this._activeAnimatables = [];
  19772. }
  19773. };
  19774. Scene.prototype._animate = function () {
  19775. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  19776. return;
  19777. }
  19778. // Getting time
  19779. var now = BABYLON.Tools.Now;
  19780. if (!this._animationTimeLast) {
  19781. if (this._pendingData.length > 0) {
  19782. return;
  19783. }
  19784. this._animationTimeLast = now;
  19785. }
  19786. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  19787. this._animationTime += deltaTime;
  19788. this._animationTimeLast = now;
  19789. for (var index = 0; index < this._activeAnimatables.length; index++) {
  19790. this._activeAnimatables[index]._animate(this._animationTime);
  19791. }
  19792. };
  19793. // Matrix
  19794. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  19795. this._useAlternateCameraConfiguration = active;
  19796. };
  19797. Scene.prototype.getViewMatrix = function () {
  19798. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  19799. };
  19800. Scene.prototype.getProjectionMatrix = function () {
  19801. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  19802. };
  19803. Scene.prototype.getTransformMatrix = function () {
  19804. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  19805. };
  19806. Scene.prototype.setTransformMatrix = function (view, projection) {
  19807. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  19808. return;
  19809. }
  19810. this._viewUpdateFlag = view.updateFlag;
  19811. this._projectionUpdateFlag = projection.updateFlag;
  19812. this._viewMatrix = view;
  19813. this._projectionMatrix = projection;
  19814. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  19815. // Update frustum
  19816. if (!this._frustumPlanes) {
  19817. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  19818. }
  19819. else {
  19820. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  19821. }
  19822. if (this.activeCamera && this.activeCamera._alternateCamera) {
  19823. var otherCamera = this.activeCamera._alternateCamera;
  19824. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  19825. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  19826. }
  19827. if (this._sceneUbo.useUbo) {
  19828. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  19829. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  19830. this._sceneUbo.update();
  19831. }
  19832. };
  19833. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  19834. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  19835. return;
  19836. }
  19837. this._alternateViewUpdateFlag = view.updateFlag;
  19838. this._alternateProjectionUpdateFlag = projection.updateFlag;
  19839. this._alternateViewMatrix = view;
  19840. this._alternateProjectionMatrix = projection;
  19841. if (!this._alternateTransformMatrix) {
  19842. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  19843. }
  19844. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  19845. if (!this._alternateSceneUbo) {
  19846. this._createAlternateUbo();
  19847. }
  19848. if (this._alternateSceneUbo.useUbo) {
  19849. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  19850. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  19851. this._alternateSceneUbo.update();
  19852. }
  19853. };
  19854. Scene.prototype.getSceneUniformBuffer = function () {
  19855. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  19856. };
  19857. // Methods
  19858. Scene.prototype.getUniqueId = function () {
  19859. var result = Scene._uniqueIdCounter;
  19860. Scene._uniqueIdCounter++;
  19861. return result;
  19862. };
  19863. Scene.prototype.addMesh = function (newMesh) {
  19864. this.meshes.push(newMesh);
  19865. //notify the collision coordinator
  19866. if (this.collisionCoordinator) {
  19867. this.collisionCoordinator.onMeshAdded(newMesh);
  19868. }
  19869. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  19870. };
  19871. Scene.prototype.removeMesh = function (toRemove) {
  19872. var index = this.meshes.indexOf(toRemove);
  19873. if (index !== -1) {
  19874. // Remove from the scene if mesh found
  19875. this.meshes.splice(index, 1);
  19876. }
  19877. this.onMeshRemovedObservable.notifyObservers(toRemove);
  19878. return index;
  19879. };
  19880. Scene.prototype.addTransformNode = function (newTransformNode) {
  19881. this.transformNodes.push(newTransformNode);
  19882. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  19883. };
  19884. Scene.prototype.removeTransformNode = function (toRemove) {
  19885. var index = this.transformNodes.indexOf(toRemove);
  19886. if (index !== -1) {
  19887. // Remove from the scene if found
  19888. this.transformNodes.splice(index, 1);
  19889. }
  19890. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  19891. return index;
  19892. };
  19893. Scene.prototype.removeSkeleton = function (toRemove) {
  19894. var index = this.skeletons.indexOf(toRemove);
  19895. if (index !== -1) {
  19896. // Remove from the scene if found
  19897. this.skeletons.splice(index, 1);
  19898. }
  19899. return index;
  19900. };
  19901. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  19902. var index = this.morphTargetManagers.indexOf(toRemove);
  19903. if (index !== -1) {
  19904. // Remove from the scene if found
  19905. this.morphTargetManagers.splice(index, 1);
  19906. }
  19907. return index;
  19908. };
  19909. Scene.prototype.removeLight = function (toRemove) {
  19910. var index = this.lights.indexOf(toRemove);
  19911. if (index !== -1) {
  19912. // Remove from the scene if mesh found
  19913. this.lights.splice(index, 1);
  19914. this.sortLightsByPriority();
  19915. }
  19916. this.onLightRemovedObservable.notifyObservers(toRemove);
  19917. return index;
  19918. };
  19919. Scene.prototype.removeCamera = function (toRemove) {
  19920. var index = this.cameras.indexOf(toRemove);
  19921. if (index !== -1) {
  19922. // Remove from the scene if mesh found
  19923. this.cameras.splice(index, 1);
  19924. }
  19925. // Remove from activeCameras
  19926. var index2 = this.activeCameras.indexOf(toRemove);
  19927. if (index2 !== -1) {
  19928. // Remove from the scene if mesh found
  19929. this.activeCameras.splice(index2, 1);
  19930. }
  19931. // Reset the activeCamera
  19932. if (this.activeCamera === toRemove) {
  19933. if (this.cameras.length > 0) {
  19934. this.activeCamera = this.cameras[0];
  19935. }
  19936. else {
  19937. this.activeCamera = null;
  19938. }
  19939. }
  19940. this.onCameraRemovedObservable.notifyObservers(toRemove);
  19941. return index;
  19942. };
  19943. Scene.prototype.addLight = function (newLight) {
  19944. this.lights.push(newLight);
  19945. this.sortLightsByPriority();
  19946. this.onNewLightAddedObservable.notifyObservers(newLight);
  19947. };
  19948. Scene.prototype.sortLightsByPriority = function () {
  19949. if (this.requireLightSorting) {
  19950. this.lights.sort(BABYLON.Light.compareLightsPriority);
  19951. }
  19952. };
  19953. Scene.prototype.addCamera = function (newCamera) {
  19954. this.cameras.push(newCamera);
  19955. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  19956. };
  19957. /**
  19958. * Switch active camera
  19959. * @param {Camera} newCamera - new active camera
  19960. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  19961. */
  19962. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  19963. if (attachControl === void 0) { attachControl = true; }
  19964. var canvas = this._engine.getRenderingCanvas();
  19965. if (!canvas) {
  19966. return;
  19967. }
  19968. if (this.activeCamera) {
  19969. this.activeCamera.detachControl(canvas);
  19970. }
  19971. this.activeCamera = newCamera;
  19972. if (attachControl) {
  19973. newCamera.attachControl(canvas);
  19974. }
  19975. };
  19976. /**
  19977. * sets the active camera of the scene using its ID
  19978. * @param {string} id - the camera's ID
  19979. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  19980. * @see activeCamera
  19981. */
  19982. Scene.prototype.setActiveCameraByID = function (id) {
  19983. var camera = this.getCameraByID(id);
  19984. if (camera) {
  19985. this.activeCamera = camera;
  19986. return camera;
  19987. }
  19988. return null;
  19989. };
  19990. /**
  19991. * sets the active camera of the scene using its name
  19992. * @param {string} name - the camera's name
  19993. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  19994. * @see activeCamera
  19995. */
  19996. Scene.prototype.setActiveCameraByName = function (name) {
  19997. var camera = this.getCameraByName(name);
  19998. if (camera) {
  19999. this.activeCamera = camera;
  20000. return camera;
  20001. }
  20002. return null;
  20003. };
  20004. /**
  20005. * get an animation group using its name
  20006. * @param {string} the material's name
  20007. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  20008. */
  20009. Scene.prototype.getAnimationGroupByName = function (name) {
  20010. for (var index = 0; index < this.animationGroups.length; index++) {
  20011. if (this.animationGroups[index].name === name) {
  20012. return this.animationGroups[index];
  20013. }
  20014. }
  20015. return null;
  20016. };
  20017. /**
  20018. * get a material using its id
  20019. * @param {string} the material's ID
  20020. * @return {BABYLON.Material|null} the material or null if none found.
  20021. */
  20022. Scene.prototype.getMaterialByID = function (id) {
  20023. for (var index = 0; index < this.materials.length; index++) {
  20024. if (this.materials[index].id === id) {
  20025. return this.materials[index];
  20026. }
  20027. }
  20028. return null;
  20029. };
  20030. /**
  20031. * get a material using its name
  20032. * @param {string} the material's name
  20033. * @return {BABYLON.Material|null} the material or null if none found.
  20034. */
  20035. Scene.prototype.getMaterialByName = function (name) {
  20036. for (var index = 0; index < this.materials.length; index++) {
  20037. if (this.materials[index].name === name) {
  20038. return this.materials[index];
  20039. }
  20040. }
  20041. return null;
  20042. };
  20043. Scene.prototype.getLensFlareSystemByName = function (name) {
  20044. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  20045. if (this.lensFlareSystems[index].name === name) {
  20046. return this.lensFlareSystems[index];
  20047. }
  20048. }
  20049. return null;
  20050. };
  20051. Scene.prototype.getLensFlareSystemByID = function (id) {
  20052. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  20053. if (this.lensFlareSystems[index].id === id) {
  20054. return this.lensFlareSystems[index];
  20055. }
  20056. }
  20057. return null;
  20058. };
  20059. Scene.prototype.getCameraByID = function (id) {
  20060. for (var index = 0; index < this.cameras.length; index++) {
  20061. if (this.cameras[index].id === id) {
  20062. return this.cameras[index];
  20063. }
  20064. }
  20065. return null;
  20066. };
  20067. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  20068. for (var index = 0; index < this.cameras.length; index++) {
  20069. if (this.cameras[index].uniqueId === uniqueId) {
  20070. return this.cameras[index];
  20071. }
  20072. }
  20073. return null;
  20074. };
  20075. /**
  20076. * get a camera using its name
  20077. * @param {string} the camera's name
  20078. * @return {BABYLON.Camera|null} the camera or null if none found.
  20079. */
  20080. Scene.prototype.getCameraByName = function (name) {
  20081. for (var index = 0; index < this.cameras.length; index++) {
  20082. if (this.cameras[index].name === name) {
  20083. return this.cameras[index];
  20084. }
  20085. }
  20086. return null;
  20087. };
  20088. /**
  20089. * get a bone using its id
  20090. * @param {string} the bone's id
  20091. * @return {BABYLON.Bone|null} the bone or null if not found
  20092. */
  20093. Scene.prototype.getBoneByID = function (id) {
  20094. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  20095. var skeleton = this.skeletons[skeletonIndex];
  20096. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  20097. if (skeleton.bones[boneIndex].id === id) {
  20098. return skeleton.bones[boneIndex];
  20099. }
  20100. }
  20101. }
  20102. return null;
  20103. };
  20104. /**
  20105. * get a bone using its id
  20106. * @param {string} the bone's name
  20107. * @return {BABYLON.Bone|null} the bone or null if not found
  20108. */
  20109. Scene.prototype.getBoneByName = function (name) {
  20110. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  20111. var skeleton = this.skeletons[skeletonIndex];
  20112. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  20113. if (skeleton.bones[boneIndex].name === name) {
  20114. return skeleton.bones[boneIndex];
  20115. }
  20116. }
  20117. }
  20118. return null;
  20119. };
  20120. /**
  20121. * get a light node using its name
  20122. * @param {string} the light's name
  20123. * @return {BABYLON.Light|null} the light or null if none found.
  20124. */
  20125. Scene.prototype.getLightByName = function (name) {
  20126. for (var index = 0; index < this.lights.length; index++) {
  20127. if (this.lights[index].name === name) {
  20128. return this.lights[index];
  20129. }
  20130. }
  20131. return null;
  20132. };
  20133. /**
  20134. * get a light node using its ID
  20135. * @param {string} the light's id
  20136. * @return {BABYLON.Light|null} the light or null if none found.
  20137. */
  20138. Scene.prototype.getLightByID = function (id) {
  20139. for (var index = 0; index < this.lights.length; index++) {
  20140. if (this.lights[index].id === id) {
  20141. return this.lights[index];
  20142. }
  20143. }
  20144. return null;
  20145. };
  20146. /**
  20147. * get a light node using its scene-generated unique ID
  20148. * @param {number} the light's unique id
  20149. * @return {BABYLON.Light|null} the light or null if none found.
  20150. */
  20151. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  20152. for (var index = 0; index < this.lights.length; index++) {
  20153. if (this.lights[index].uniqueId === uniqueId) {
  20154. return this.lights[index];
  20155. }
  20156. }
  20157. return null;
  20158. };
  20159. /**
  20160. * get a particle system by id
  20161. * @param id {number} the particle system id
  20162. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  20163. */
  20164. Scene.prototype.getParticleSystemByID = function (id) {
  20165. for (var index = 0; index < this.particleSystems.length; index++) {
  20166. if (this.particleSystems[index].id === id) {
  20167. return this.particleSystems[index];
  20168. }
  20169. }
  20170. return null;
  20171. };
  20172. /**
  20173. * get a geometry using its ID
  20174. * @param {string} the geometry's id
  20175. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  20176. */
  20177. Scene.prototype.getGeometryByID = function (id) {
  20178. for (var index = 0; index < this._geometries.length; index++) {
  20179. if (this._geometries[index].id === id) {
  20180. return this._geometries[index];
  20181. }
  20182. }
  20183. return null;
  20184. };
  20185. /**
  20186. * add a new geometry to this scene.
  20187. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  20188. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  20189. * @return {boolean} was the geometry added or not
  20190. */
  20191. Scene.prototype.pushGeometry = function (geometry, force) {
  20192. if (!force && this.getGeometryByID(geometry.id)) {
  20193. return false;
  20194. }
  20195. this._geometries.push(geometry);
  20196. //notify the collision coordinator
  20197. if (this.collisionCoordinator) {
  20198. this.collisionCoordinator.onGeometryAdded(geometry);
  20199. }
  20200. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  20201. return true;
  20202. };
  20203. /**
  20204. * Removes an existing geometry
  20205. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  20206. * @return {boolean} was the geometry removed or not
  20207. */
  20208. Scene.prototype.removeGeometry = function (geometry) {
  20209. var index = this._geometries.indexOf(geometry);
  20210. if (index > -1) {
  20211. this._geometries.splice(index, 1);
  20212. //notify the collision coordinator
  20213. if (this.collisionCoordinator) {
  20214. this.collisionCoordinator.onGeometryDeleted(geometry);
  20215. }
  20216. this.onGeometryRemovedObservable.notifyObservers(geometry);
  20217. return true;
  20218. }
  20219. return false;
  20220. };
  20221. Scene.prototype.getGeometries = function () {
  20222. return this._geometries;
  20223. };
  20224. /**
  20225. * Get the first added mesh found of a given ID
  20226. * @param {string} id - the id to search for
  20227. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  20228. */
  20229. Scene.prototype.getMeshByID = function (id) {
  20230. for (var index = 0; index < this.meshes.length; index++) {
  20231. if (this.meshes[index].id === id) {
  20232. return this.meshes[index];
  20233. }
  20234. }
  20235. return null;
  20236. };
  20237. Scene.prototype.getMeshesByID = function (id) {
  20238. return this.meshes.filter(function (m) {
  20239. return m.id === id;
  20240. });
  20241. };
  20242. /**
  20243. * Get the first added transform node found of a given ID
  20244. * @param {string} id - the id to search for
  20245. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  20246. */
  20247. Scene.prototype.getTransformNodeByID = function (id) {
  20248. for (var index = 0; index < this.transformNodes.length; index++) {
  20249. if (this.transformNodes[index].id === id) {
  20250. return this.transformNodes[index];
  20251. }
  20252. }
  20253. return null;
  20254. };
  20255. Scene.prototype.getTransformNodesByID = function (id) {
  20256. return this.transformNodes.filter(function (m) {
  20257. return m.id === id;
  20258. });
  20259. };
  20260. /**
  20261. * Get a mesh with its auto-generated unique id
  20262. * @param {number} uniqueId - the unique id to search for
  20263. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  20264. */
  20265. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  20266. for (var index = 0; index < this.meshes.length; index++) {
  20267. if (this.meshes[index].uniqueId === uniqueId) {
  20268. return this.meshes[index];
  20269. }
  20270. }
  20271. return null;
  20272. };
  20273. /**
  20274. * Get a the last added mesh found of a given ID
  20275. * @param {string} id - the id to search for
  20276. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  20277. */
  20278. Scene.prototype.getLastMeshByID = function (id) {
  20279. for (var index = this.meshes.length - 1; index >= 0; index--) {
  20280. if (this.meshes[index].id === id) {
  20281. return this.meshes[index];
  20282. }
  20283. }
  20284. return null;
  20285. };
  20286. /**
  20287. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  20288. * @param {string} id - the id to search for
  20289. * @return {BABYLON.Node|null} the node found or null if not found at all.
  20290. */
  20291. Scene.prototype.getLastEntryByID = function (id) {
  20292. var index;
  20293. for (index = this.meshes.length - 1; index >= 0; index--) {
  20294. if (this.meshes[index].id === id) {
  20295. return this.meshes[index];
  20296. }
  20297. }
  20298. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  20299. if (this.transformNodes[index].id === id) {
  20300. return this.transformNodes[index];
  20301. }
  20302. }
  20303. for (index = this.cameras.length - 1; index >= 0; index--) {
  20304. if (this.cameras[index].id === id) {
  20305. return this.cameras[index];
  20306. }
  20307. }
  20308. for (index = this.lights.length - 1; index >= 0; index--) {
  20309. if (this.lights[index].id === id) {
  20310. return this.lights[index];
  20311. }
  20312. }
  20313. return null;
  20314. };
  20315. Scene.prototype.getNodeByID = function (id) {
  20316. var mesh = this.getMeshByID(id);
  20317. if (mesh) {
  20318. return mesh;
  20319. }
  20320. var light = this.getLightByID(id);
  20321. if (light) {
  20322. return light;
  20323. }
  20324. var camera = this.getCameraByID(id);
  20325. if (camera) {
  20326. return camera;
  20327. }
  20328. var bone = this.getBoneByID(id);
  20329. return bone;
  20330. };
  20331. Scene.prototype.getNodeByName = function (name) {
  20332. var mesh = this.getMeshByName(name);
  20333. if (mesh) {
  20334. return mesh;
  20335. }
  20336. var light = this.getLightByName(name);
  20337. if (light) {
  20338. return light;
  20339. }
  20340. var camera = this.getCameraByName(name);
  20341. if (camera) {
  20342. return camera;
  20343. }
  20344. var bone = this.getBoneByName(name);
  20345. return bone;
  20346. };
  20347. Scene.prototype.getMeshByName = function (name) {
  20348. for (var index = 0; index < this.meshes.length; index++) {
  20349. if (this.meshes[index].name === name) {
  20350. return this.meshes[index];
  20351. }
  20352. }
  20353. return null;
  20354. };
  20355. Scene.prototype.getTransformNodeByName = function (name) {
  20356. for (var index = 0; index < this.transformNodes.length; index++) {
  20357. if (this.transformNodes[index].name === name) {
  20358. return this.transformNodes[index];
  20359. }
  20360. }
  20361. return null;
  20362. };
  20363. Scene.prototype.getSoundByName = function (name) {
  20364. var index;
  20365. if (BABYLON.AudioEngine) {
  20366. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  20367. if (this.mainSoundTrack.soundCollection[index].name === name) {
  20368. return this.mainSoundTrack.soundCollection[index];
  20369. }
  20370. }
  20371. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  20372. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  20373. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  20374. return this.soundTracks[sdIndex].soundCollection[index];
  20375. }
  20376. }
  20377. }
  20378. }
  20379. return null;
  20380. };
  20381. Scene.prototype.getLastSkeletonByID = function (id) {
  20382. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  20383. if (this.skeletons[index].id === id) {
  20384. return this.skeletons[index];
  20385. }
  20386. }
  20387. return null;
  20388. };
  20389. Scene.prototype.getSkeletonById = function (id) {
  20390. for (var index = 0; index < this.skeletons.length; index++) {
  20391. if (this.skeletons[index].id === id) {
  20392. return this.skeletons[index];
  20393. }
  20394. }
  20395. return null;
  20396. };
  20397. Scene.prototype.getSkeletonByName = function (name) {
  20398. for (var index = 0; index < this.skeletons.length; index++) {
  20399. if (this.skeletons[index].name === name) {
  20400. return this.skeletons[index];
  20401. }
  20402. }
  20403. return null;
  20404. };
  20405. Scene.prototype.getMorphTargetManagerById = function (id) {
  20406. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  20407. if (this.morphTargetManagers[index].uniqueId === id) {
  20408. return this.morphTargetManagers[index];
  20409. }
  20410. }
  20411. return null;
  20412. };
  20413. Scene.prototype.isActiveMesh = function (mesh) {
  20414. return (this._activeMeshes.indexOf(mesh) !== -1);
  20415. };
  20416. /**
  20417. * Return a the first highlight layer of the scene with a given name.
  20418. * @param name The name of the highlight layer to look for.
  20419. * @return The highlight layer if found otherwise null.
  20420. */
  20421. Scene.prototype.getHighlightLayerByName = function (name) {
  20422. for (var index = 0; index < this.highlightLayers.length; index++) {
  20423. if (this.highlightLayers[index].name === name) {
  20424. return this.highlightLayers[index];
  20425. }
  20426. }
  20427. return null;
  20428. };
  20429. Object.defineProperty(Scene.prototype, "uid", {
  20430. /**
  20431. * Return a unique id as a string which can serve as an identifier for the scene
  20432. */
  20433. get: function () {
  20434. if (!this._uid) {
  20435. this._uid = BABYLON.Tools.RandomId();
  20436. }
  20437. return this._uid;
  20438. },
  20439. enumerable: true,
  20440. configurable: true
  20441. });
  20442. /**
  20443. * Add an externaly attached data from its key.
  20444. * This method call will fail and return false, if such key already exists.
  20445. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  20446. * @param key the unique key that identifies the data
  20447. * @param data the data object to associate to the key for this Engine instance
  20448. * @return true if no such key were already present and the data was added successfully, false otherwise
  20449. */
  20450. Scene.prototype.addExternalData = function (key, data) {
  20451. if (!this._externalData) {
  20452. this._externalData = new BABYLON.StringDictionary();
  20453. }
  20454. return this._externalData.add(key, data);
  20455. };
  20456. /**
  20457. * Get an externaly attached data from its key
  20458. * @param key the unique key that identifies the data
  20459. * @return the associated data, if present (can be null), or undefined if not present
  20460. */
  20461. Scene.prototype.getExternalData = function (key) {
  20462. if (!this._externalData) {
  20463. return null;
  20464. }
  20465. return this._externalData.get(key);
  20466. };
  20467. /**
  20468. * Get an externaly attached data from its key, create it using a factory if it's not already present
  20469. * @param key the unique key that identifies the data
  20470. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  20471. * @return the associated data, can be null if the factory returned null.
  20472. */
  20473. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  20474. if (!this._externalData) {
  20475. this._externalData = new BABYLON.StringDictionary();
  20476. }
  20477. return this._externalData.getOrAddWithFactory(key, factory);
  20478. };
  20479. /**
  20480. * Remove an externaly attached data from the Engine instance
  20481. * @param key the unique key that identifies the data
  20482. * @return true if the data was successfully removed, false if it doesn't exist
  20483. */
  20484. Scene.prototype.removeExternalData = function (key) {
  20485. return this._externalData.remove(key);
  20486. };
  20487. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  20488. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  20489. var material = subMesh.getMaterial();
  20490. if (mesh.showSubMeshesBoundingBox) {
  20491. var boundingInfo = subMesh.getBoundingInfo();
  20492. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  20493. }
  20494. if (material) {
  20495. // Render targets
  20496. if (material.getRenderTargetTextures) {
  20497. if (this._processedMaterials.indexOf(material) === -1) {
  20498. this._processedMaterials.push(material);
  20499. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  20500. }
  20501. }
  20502. // Dispatch
  20503. this._activeIndices.addCount(subMesh.indexCount, false);
  20504. this._renderingManager.dispatch(subMesh);
  20505. }
  20506. }
  20507. };
  20508. Scene.prototype._isInIntermediateRendering = function () {
  20509. return this._intermediateRendering;
  20510. };
  20511. /**
  20512. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  20513. */
  20514. Scene.prototype.freezeActiveMeshes = function () {
  20515. this._evaluateActiveMeshes();
  20516. this._activeMeshesFrozen = true;
  20517. return this;
  20518. };
  20519. /**
  20520. * Use this function to restart evaluating active meshes on every frame
  20521. */
  20522. Scene.prototype.unfreezeActiveMeshes = function () {
  20523. this._activeMeshesFrozen = false;
  20524. return this;
  20525. };
  20526. Scene.prototype._evaluateActiveMeshes = function () {
  20527. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  20528. return;
  20529. }
  20530. if (!this.activeCamera) {
  20531. return;
  20532. }
  20533. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  20534. this.activeCamera._activeMeshes.reset();
  20535. this._activeMeshes.reset();
  20536. this._renderingManager.reset();
  20537. this._processedMaterials.reset();
  20538. this._activeParticleSystems.reset();
  20539. this._activeSkeletons.reset();
  20540. this._softwareSkinnedMeshes.reset();
  20541. if (this._boundingBoxRenderer) {
  20542. this._boundingBoxRenderer.reset();
  20543. }
  20544. // Meshes
  20545. var meshes;
  20546. var len;
  20547. if (this._selectionOctree) {
  20548. var selection = this._selectionOctree.select(this._frustumPlanes);
  20549. meshes = selection.data;
  20550. len = selection.length;
  20551. }
  20552. else {
  20553. len = this.meshes.length;
  20554. meshes = this.meshes;
  20555. }
  20556. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  20557. var mesh = meshes[meshIndex];
  20558. if (mesh.isBlocked) {
  20559. continue;
  20560. }
  20561. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  20562. if (!mesh.isReady() || !mesh.isEnabled()) {
  20563. continue;
  20564. }
  20565. mesh.computeWorldMatrix();
  20566. // Intersections
  20567. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  20568. this._meshesForIntersections.pushNoDuplicate(mesh);
  20569. }
  20570. // Switch to current LOD
  20571. var meshLOD = mesh.getLOD(this.activeCamera);
  20572. if (!meshLOD) {
  20573. continue;
  20574. }
  20575. mesh._preActivate();
  20576. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  20577. this._activeMeshes.push(mesh);
  20578. this.activeCamera._activeMeshes.push(mesh);
  20579. mesh._activate(this._renderId);
  20580. if (meshLOD !== mesh) {
  20581. meshLOD._activate(this._renderId);
  20582. }
  20583. this._activeMesh(mesh, meshLOD);
  20584. }
  20585. }
  20586. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  20587. // Particle systems
  20588. if (this.particlesEnabled) {
  20589. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  20590. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  20591. var particleSystem = this.particleSystems[particleIndex];
  20592. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  20593. continue;
  20594. }
  20595. var emitter = particleSystem.emitter;
  20596. if (!emitter.position || emitter.isEnabled()) {
  20597. this._activeParticleSystems.push(particleSystem);
  20598. particleSystem.animate();
  20599. this._renderingManager.dispatchParticles(particleSystem);
  20600. }
  20601. }
  20602. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  20603. }
  20604. };
  20605. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  20606. if (mesh.skeleton && this.skeletonsEnabled) {
  20607. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  20608. mesh.skeleton.prepare();
  20609. }
  20610. if (!mesh.computeBonesUsingShaders) {
  20611. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  20612. }
  20613. }
  20614. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  20615. var boundingInfo = sourceMesh.getBoundingInfo();
  20616. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  20617. }
  20618. if (mesh && mesh.subMeshes) {
  20619. // Submeshes Octrees
  20620. var len;
  20621. var subMeshes;
  20622. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  20623. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  20624. len = intersections.length;
  20625. subMeshes = intersections.data;
  20626. }
  20627. else {
  20628. subMeshes = mesh.subMeshes;
  20629. len = subMeshes.length;
  20630. }
  20631. for (var subIndex = 0; subIndex < len; subIndex++) {
  20632. var subMesh = subMeshes[subIndex];
  20633. this._evaluateSubMesh(subMesh, mesh);
  20634. }
  20635. }
  20636. };
  20637. Scene.prototype.updateTransformMatrix = function (force) {
  20638. if (!this.activeCamera) {
  20639. return;
  20640. }
  20641. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  20642. };
  20643. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  20644. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  20645. };
  20646. Scene.prototype._renderForCamera = function (camera) {
  20647. if (camera && camera._skipRendering) {
  20648. return;
  20649. }
  20650. var engine = this._engine;
  20651. this.activeCamera = camera;
  20652. if (!this.activeCamera)
  20653. throw new Error("Active camera not set");
  20654. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  20655. // Viewport
  20656. engine.setViewport(this.activeCamera.viewport);
  20657. // Camera
  20658. this.resetCachedMaterial();
  20659. this._renderId++;
  20660. this.activeCamera.update();
  20661. this.updateTransformMatrix();
  20662. if (camera._alternateCamera) {
  20663. this.updateAlternateTransformMatrix(camera._alternateCamera);
  20664. this._alternateRendering = true;
  20665. }
  20666. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  20667. // Meshes
  20668. this._evaluateActiveMeshes();
  20669. // Software skinning
  20670. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  20671. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  20672. mesh.applySkeleton(mesh.skeleton);
  20673. }
  20674. // Render targets
  20675. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  20676. var needsRestoreFrameBuffer = false;
  20677. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  20678. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  20679. }
  20680. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  20681. this._intermediateRendering = true;
  20682. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  20683. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  20684. var renderTarget = this._renderTargets.data[renderIndex];
  20685. if (renderTarget._shouldRender()) {
  20686. this._renderId++;
  20687. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  20688. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  20689. }
  20690. }
  20691. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  20692. this._intermediateRendering = false;
  20693. this._renderId++;
  20694. needsRestoreFrameBuffer = true; // Restore back buffer
  20695. }
  20696. // Render HighlightLayer Texture
  20697. var stencilState = this._engine.getStencilBuffer();
  20698. var renderhighlights = false;
  20699. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  20700. this._intermediateRendering = true;
  20701. for (var i = 0; i < this.highlightLayers.length; i++) {
  20702. var highlightLayer = this.highlightLayers[i];
  20703. if (highlightLayer.shouldRender() &&
  20704. (!highlightLayer.camera ||
  20705. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  20706. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  20707. renderhighlights = true;
  20708. var renderTarget = highlightLayer._mainTexture;
  20709. if (renderTarget._shouldRender()) {
  20710. this._renderId++;
  20711. renderTarget.render(false, false);
  20712. needsRestoreFrameBuffer = true;
  20713. }
  20714. }
  20715. }
  20716. this._intermediateRendering = false;
  20717. this._renderId++;
  20718. }
  20719. if (needsRestoreFrameBuffer) {
  20720. engine.restoreDefaultFramebuffer(); // Restore back buffer
  20721. }
  20722. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  20723. // Prepare Frame
  20724. this.postProcessManager._prepareFrame();
  20725. // Backgrounds
  20726. var layerIndex;
  20727. var layer;
  20728. if (this.layers.length) {
  20729. engine.setDepthBuffer(false);
  20730. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  20731. layer = this.layers[layerIndex];
  20732. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  20733. layer.render();
  20734. }
  20735. }
  20736. engine.setDepthBuffer(true);
  20737. }
  20738. // Activate HighlightLayer stencil
  20739. if (renderhighlights) {
  20740. this._engine.setStencilBuffer(true);
  20741. }
  20742. // Render
  20743. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  20744. this._renderingManager.render(null, null, true, true);
  20745. this.onAfterDrawPhaseObservable.notifyObservers(this);
  20746. // Restore HighlightLayer stencil
  20747. if (renderhighlights) {
  20748. this._engine.setStencilBuffer(stencilState);
  20749. }
  20750. // Bounding boxes
  20751. if (this._boundingBoxRenderer) {
  20752. this._boundingBoxRenderer.render();
  20753. }
  20754. // Lens flares
  20755. if (this.lensFlaresEnabled) {
  20756. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  20757. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  20758. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  20759. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  20760. lensFlareSystem.render();
  20761. }
  20762. }
  20763. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  20764. }
  20765. // Foregrounds
  20766. if (this.layers.length) {
  20767. engine.setDepthBuffer(false);
  20768. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  20769. layer = this.layers[layerIndex];
  20770. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  20771. layer.render();
  20772. }
  20773. }
  20774. engine.setDepthBuffer(true);
  20775. }
  20776. // Highlight Layer
  20777. if (renderhighlights) {
  20778. engine.setDepthBuffer(false);
  20779. for (var i = 0; i < this.highlightLayers.length; i++) {
  20780. if (this.highlightLayers[i].shouldRender()) {
  20781. this.highlightLayers[i].render();
  20782. }
  20783. }
  20784. engine.setDepthBuffer(true);
  20785. }
  20786. // Finalize frame
  20787. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  20788. // Reset some special arrays
  20789. this._renderTargets.reset();
  20790. this._alternateRendering = false;
  20791. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  20792. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  20793. };
  20794. Scene.prototype._processSubCameras = function (camera) {
  20795. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  20796. this._renderForCamera(camera);
  20797. return;
  20798. }
  20799. // Update camera
  20800. if (this.activeCamera) {
  20801. this.activeCamera.update();
  20802. }
  20803. // rig cameras
  20804. for (var index = 0; index < camera._rigCameras.length; index++) {
  20805. this._renderForCamera(camera._rigCameras[index]);
  20806. }
  20807. this.activeCamera = camera;
  20808. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  20809. };
  20810. Scene.prototype._checkIntersections = function () {
  20811. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  20812. var sourceMesh = this._meshesForIntersections.data[index];
  20813. if (!sourceMesh.actionManager) {
  20814. continue;
  20815. }
  20816. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  20817. var action = sourceMesh.actionManager.actions[actionIndex];
  20818. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20819. var parameters = action.getTriggerParameter();
  20820. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  20821. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  20822. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  20823. if (areIntersecting && currentIntersectionInProgress === -1) {
  20824. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  20825. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  20826. sourceMesh._intersectionsInProgress.push(otherMesh);
  20827. }
  20828. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20829. sourceMesh._intersectionsInProgress.push(otherMesh);
  20830. }
  20831. }
  20832. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  20833. //They intersected, and now they don't.
  20834. //is this trigger an exit trigger? execute an event.
  20835. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20836. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  20837. }
  20838. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  20839. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20840. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  20841. }
  20842. }
  20843. }
  20844. }
  20845. }
  20846. };
  20847. Scene.prototype.render = function () {
  20848. if (this.isDisposed) {
  20849. return;
  20850. }
  20851. this._activeParticles.fetchNewFrame();
  20852. this._totalVertices.fetchNewFrame();
  20853. this._activeIndices.fetchNewFrame();
  20854. this._activeBones.fetchNewFrame();
  20855. this._meshesForIntersections.reset();
  20856. this.resetCachedMaterial();
  20857. this.onBeforeAnimationsObservable.notifyObservers(this);
  20858. // Actions
  20859. if (this.actionManager) {
  20860. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  20861. }
  20862. //Simplification Queue
  20863. if (this.simplificationQueue && !this.simplificationQueue.running) {
  20864. this.simplificationQueue.executeNext();
  20865. }
  20866. if (this._engine.isDeterministicLockStep()) {
  20867. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  20868. var defaultFPS = (60.0 / 1000.0);
  20869. var defaultFrameTime = 1000 / 60; // frame time in MS
  20870. if (this._physicsEngine) {
  20871. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  20872. }
  20873. var stepsTaken = 0;
  20874. var maxSubSteps = this._engine.getLockstepMaxSteps();
  20875. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  20876. internalSteps = Math.min(internalSteps, maxSubSteps);
  20877. do {
  20878. this.onBeforeStepObservable.notifyObservers(this);
  20879. // Animations
  20880. this._animationRatio = defaultFrameTime * defaultFPS;
  20881. this._animate();
  20882. this.onAfterAnimationsObservable.notifyObservers(this);
  20883. // Physics
  20884. if (this._physicsEngine) {
  20885. this.onBeforePhysicsObservable.notifyObservers(this);
  20886. this._physicsEngine._step(defaultFrameTime / 1000);
  20887. this.onAfterPhysicsObservable.notifyObservers(this);
  20888. }
  20889. this.onAfterStepObservable.notifyObservers(this);
  20890. this._currentStepId++;
  20891. stepsTaken++;
  20892. deltaTime -= defaultFrameTime;
  20893. } while (deltaTime > 0 && stepsTaken < internalSteps);
  20894. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  20895. }
  20896. else {
  20897. // Animations
  20898. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  20899. this._animationRatio = deltaTime * (60.0 / 1000.0);
  20900. this._animate();
  20901. this.onAfterAnimationsObservable.notifyObservers(this);
  20902. // Physics
  20903. if (this._physicsEngine) {
  20904. this.onBeforePhysicsObservable.notifyObservers(this);
  20905. this._physicsEngine._step(deltaTime / 1000.0);
  20906. this.onAfterPhysicsObservable.notifyObservers(this);
  20907. }
  20908. }
  20909. // update gamepad manager
  20910. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  20911. this._gamepadManager._checkGamepadsStatus();
  20912. }
  20913. // Before render
  20914. this.onBeforeRenderObservable.notifyObservers(this);
  20915. // Customs render targets
  20916. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  20917. var engine = this.getEngine();
  20918. var currentActiveCamera = this.activeCamera;
  20919. if (this.renderTargetsEnabled) {
  20920. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  20921. this._intermediateRendering = true;
  20922. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  20923. var renderTarget = this.customRenderTargets[customIndex];
  20924. if (renderTarget._shouldRender()) {
  20925. this._renderId++;
  20926. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  20927. if (!this.activeCamera)
  20928. throw new Error("Active camera not set");
  20929. // Viewport
  20930. engine.setViewport(this.activeCamera.viewport);
  20931. // Camera
  20932. this.updateTransformMatrix();
  20933. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  20934. }
  20935. }
  20936. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  20937. this._intermediateRendering = false;
  20938. this._renderId++;
  20939. }
  20940. // Restore back buffer
  20941. if (this.customRenderTargets.length > 0) {
  20942. engine.restoreDefaultFramebuffer();
  20943. }
  20944. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  20945. this.activeCamera = currentActiveCamera;
  20946. // Procedural textures
  20947. if (this.proceduralTexturesEnabled) {
  20948. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  20949. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  20950. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  20951. if (proceduralTexture._shouldRender()) {
  20952. proceduralTexture.render();
  20953. }
  20954. }
  20955. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  20956. }
  20957. // Clear
  20958. if (this.autoClearDepthAndStencil || this.autoClear) {
  20959. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  20960. }
  20961. // Shadows
  20962. if (this.shadowsEnabled) {
  20963. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  20964. var light = this.lights[lightIndex];
  20965. var shadowGenerator = light.getShadowGenerator();
  20966. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  20967. var shadowMap = (shadowGenerator.getShadowMap());
  20968. if (this.textures.indexOf(shadowMap) !== -1) {
  20969. this._renderTargets.push(shadowMap);
  20970. }
  20971. }
  20972. }
  20973. }
  20974. // Depth renderer
  20975. if (this._depthRenderer) {
  20976. this._renderTargets.push(this._depthRenderer.getDepthMap());
  20977. }
  20978. // Geometry renderer
  20979. if (this._geometryBufferRenderer) {
  20980. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  20981. }
  20982. // RenderPipeline
  20983. if (this._postProcessRenderPipelineManager) {
  20984. this._postProcessRenderPipelineManager.update();
  20985. }
  20986. // Multi-cameras?
  20987. if (this.activeCameras.length > 0) {
  20988. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  20989. if (cameraIndex > 0) {
  20990. this._engine.clear(null, false, true, true);
  20991. }
  20992. this._processSubCameras(this.activeCameras[cameraIndex]);
  20993. }
  20994. }
  20995. else {
  20996. if (!this.activeCamera) {
  20997. throw new Error("No camera defined");
  20998. }
  20999. this._processSubCameras(this.activeCamera);
  21000. }
  21001. // Intersection checks
  21002. this._checkIntersections();
  21003. // Update the audio listener attached to the camera
  21004. if (BABYLON.AudioEngine) {
  21005. this._updateAudioParameters();
  21006. }
  21007. // After render
  21008. if (this.afterRender) {
  21009. this.afterRender();
  21010. }
  21011. this.onAfterRenderObservable.notifyObservers(this);
  21012. // Cleaning
  21013. for (var index = 0; index < this._toBeDisposed.length; index++) {
  21014. var data = this._toBeDisposed.data[index];
  21015. if (data) {
  21016. data.dispose();
  21017. }
  21018. this._toBeDisposed[index] = null;
  21019. }
  21020. this._toBeDisposed.reset();
  21021. if (this.dumpNextRenderTargets) {
  21022. this.dumpNextRenderTargets = false;
  21023. }
  21024. this._activeBones.addCount(0, true);
  21025. this._activeIndices.addCount(0, true);
  21026. this._activeParticles.addCount(0, true);
  21027. };
  21028. Scene.prototype._updateAudioParameters = function () {
  21029. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  21030. return;
  21031. }
  21032. var listeningCamera;
  21033. var audioEngine = BABYLON.Engine.audioEngine;
  21034. if (this.activeCameras.length > 0) {
  21035. listeningCamera = this.activeCameras[0];
  21036. }
  21037. else {
  21038. listeningCamera = this.activeCamera;
  21039. }
  21040. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  21041. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  21042. // for VR cameras
  21043. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  21044. listeningCamera = listeningCamera.rigCameras[0];
  21045. }
  21046. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  21047. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  21048. cameraDirection.normalize();
  21049. // To avoid some errors on GearVR
  21050. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  21051. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  21052. }
  21053. var i;
  21054. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21055. var sound = this.mainSoundTrack.soundCollection[i];
  21056. if (sound.useCustomAttenuation) {
  21057. sound.updateDistanceFromListener();
  21058. }
  21059. }
  21060. for (i = 0; i < this.soundTracks.length; i++) {
  21061. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21062. sound = this.soundTracks[i].soundCollection[j];
  21063. if (sound.useCustomAttenuation) {
  21064. sound.updateDistanceFromListener();
  21065. }
  21066. }
  21067. }
  21068. }
  21069. };
  21070. Object.defineProperty(Scene.prototype, "audioEnabled", {
  21071. // Audio
  21072. get: function () {
  21073. return this._audioEnabled;
  21074. },
  21075. set: function (value) {
  21076. this._audioEnabled = value;
  21077. if (BABYLON.AudioEngine) {
  21078. if (this._audioEnabled) {
  21079. this._enableAudio();
  21080. }
  21081. else {
  21082. this._disableAudio();
  21083. }
  21084. }
  21085. },
  21086. enumerable: true,
  21087. configurable: true
  21088. });
  21089. Scene.prototype._disableAudio = function () {
  21090. var i;
  21091. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21092. this.mainSoundTrack.soundCollection[i].pause();
  21093. }
  21094. for (i = 0; i < this.soundTracks.length; i++) {
  21095. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21096. this.soundTracks[i].soundCollection[j].pause();
  21097. }
  21098. }
  21099. };
  21100. Scene.prototype._enableAudio = function () {
  21101. var i;
  21102. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21103. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  21104. this.mainSoundTrack.soundCollection[i].play();
  21105. }
  21106. }
  21107. for (i = 0; i < this.soundTracks.length; i++) {
  21108. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21109. if (this.soundTracks[i].soundCollection[j].isPaused) {
  21110. this.soundTracks[i].soundCollection[j].play();
  21111. }
  21112. }
  21113. }
  21114. };
  21115. Object.defineProperty(Scene.prototype, "headphone", {
  21116. get: function () {
  21117. return this._headphone;
  21118. },
  21119. set: function (value) {
  21120. this._headphone = value;
  21121. if (BABYLON.AudioEngine) {
  21122. if (this._headphone) {
  21123. this._switchAudioModeForHeadphones();
  21124. }
  21125. else {
  21126. this._switchAudioModeForNormalSpeakers();
  21127. }
  21128. }
  21129. },
  21130. enumerable: true,
  21131. configurable: true
  21132. });
  21133. Scene.prototype._switchAudioModeForHeadphones = function () {
  21134. this.mainSoundTrack.switchPanningModelToHRTF();
  21135. for (var i = 0; i < this.soundTracks.length; i++) {
  21136. this.soundTracks[i].switchPanningModelToHRTF();
  21137. }
  21138. };
  21139. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  21140. this.mainSoundTrack.switchPanningModelToEqualPower();
  21141. for (var i = 0; i < this.soundTracks.length; i++) {
  21142. this.soundTracks[i].switchPanningModelToEqualPower();
  21143. }
  21144. };
  21145. Scene.prototype.enableDepthRenderer = function () {
  21146. if (this._depthRenderer) {
  21147. return this._depthRenderer;
  21148. }
  21149. this._depthRenderer = new BABYLON.DepthRenderer(this);
  21150. return this._depthRenderer;
  21151. };
  21152. Scene.prototype.disableDepthRenderer = function () {
  21153. if (!this._depthRenderer) {
  21154. return;
  21155. }
  21156. this._depthRenderer.dispose();
  21157. this._depthRenderer = null;
  21158. };
  21159. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  21160. if (ratio === void 0) { ratio = 1; }
  21161. if (this._geometryBufferRenderer) {
  21162. return this._geometryBufferRenderer;
  21163. }
  21164. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  21165. if (!this._geometryBufferRenderer.isSupported) {
  21166. this._geometryBufferRenderer = null;
  21167. }
  21168. return this._geometryBufferRenderer;
  21169. };
  21170. Scene.prototype.disableGeometryBufferRenderer = function () {
  21171. if (!this._geometryBufferRenderer) {
  21172. return;
  21173. }
  21174. this._geometryBufferRenderer.dispose();
  21175. this._geometryBufferRenderer = null;
  21176. };
  21177. Scene.prototype.freezeMaterials = function () {
  21178. for (var i = 0; i < this.materials.length; i++) {
  21179. this.materials[i].freeze();
  21180. }
  21181. };
  21182. Scene.prototype.unfreezeMaterials = function () {
  21183. for (var i = 0; i < this.materials.length; i++) {
  21184. this.materials[i].unfreeze();
  21185. }
  21186. };
  21187. Scene.prototype.dispose = function () {
  21188. this.beforeRender = null;
  21189. this.afterRender = null;
  21190. this.skeletons = [];
  21191. this.morphTargetManagers = [];
  21192. this.importedMeshesFiles = new Array();
  21193. this.stopAllAnimations();
  21194. this.resetCachedMaterial();
  21195. if (this._depthRenderer) {
  21196. this._depthRenderer.dispose();
  21197. }
  21198. if (this._gamepadManager) {
  21199. this._gamepadManager.dispose();
  21200. this._gamepadManager = null;
  21201. }
  21202. // Smart arrays
  21203. if (this.activeCamera) {
  21204. this.activeCamera._activeMeshes.dispose();
  21205. this.activeCamera = null;
  21206. }
  21207. this._activeMeshes.dispose();
  21208. this._renderingManager.dispose();
  21209. this._processedMaterials.dispose();
  21210. this._activeParticleSystems.dispose();
  21211. this._activeSkeletons.dispose();
  21212. this._softwareSkinnedMeshes.dispose();
  21213. this._renderTargets.dispose();
  21214. if (this._boundingBoxRenderer) {
  21215. this._boundingBoxRenderer.dispose();
  21216. }
  21217. this._meshesForIntersections.dispose();
  21218. this._toBeDisposed.dispose();
  21219. // Debug layer
  21220. if (this._debugLayer) {
  21221. this._debugLayer.hide();
  21222. }
  21223. // Events
  21224. this.onDisposeObservable.notifyObservers(this);
  21225. this.onDisposeObservable.clear();
  21226. this.onBeforeRenderObservable.clear();
  21227. this.onAfterRenderObservable.clear();
  21228. this.OnBeforeRenderTargetsRenderObservable.clear();
  21229. this.OnAfterRenderTargetsRenderObservable.clear();
  21230. this.onAfterStepObservable.clear();
  21231. this.onBeforeStepObservable.clear();
  21232. this.onBeforeActiveMeshesEvaluationObservable.clear();
  21233. this.onAfterActiveMeshesEvaluationObservable.clear();
  21234. this.onBeforeParticlesRenderingObservable.clear();
  21235. this.onAfterParticlesRenderingObservable.clear();
  21236. this.onBeforeSpritesRenderingObservable.clear();
  21237. this.onAfterSpritesRenderingObservable.clear();
  21238. this.onBeforeDrawPhaseObservable.clear();
  21239. this.onAfterDrawPhaseObservable.clear();
  21240. this.onBeforePhysicsObservable.clear();
  21241. this.onAfterPhysicsObservable.clear();
  21242. this.onBeforeAnimationsObservable.clear();
  21243. this.onAfterAnimationsObservable.clear();
  21244. this.onDataLoadedObservable.clear();
  21245. this.detachControl();
  21246. // Release sounds & sounds tracks
  21247. if (BABYLON.AudioEngine) {
  21248. this.disposeSounds();
  21249. }
  21250. // VR Helper
  21251. if (this.VRHelper) {
  21252. this.VRHelper.dispose();
  21253. }
  21254. // Detach cameras
  21255. var canvas = this._engine.getRenderingCanvas();
  21256. if (canvas) {
  21257. var index;
  21258. for (index = 0; index < this.cameras.length; index++) {
  21259. this.cameras[index].detachControl(canvas);
  21260. }
  21261. }
  21262. // Release animation groups
  21263. while (this.animationGroups.length) {
  21264. this.animationGroups[0].dispose();
  21265. }
  21266. // Release lights
  21267. while (this.lights.length) {
  21268. this.lights[0].dispose();
  21269. }
  21270. // Release meshes
  21271. while (this.meshes.length) {
  21272. this.meshes[0].dispose(true);
  21273. }
  21274. while (this.transformNodes.length) {
  21275. this.removeTransformNode(this.transformNodes[0]);
  21276. }
  21277. // Release cameras
  21278. while (this.cameras.length) {
  21279. this.cameras[0].dispose();
  21280. }
  21281. // Release materials
  21282. if (this.defaultMaterial) {
  21283. this.defaultMaterial.dispose();
  21284. }
  21285. while (this.multiMaterials.length) {
  21286. this.multiMaterials[0].dispose();
  21287. }
  21288. while (this.materials.length) {
  21289. this.materials[0].dispose();
  21290. }
  21291. // Release particles
  21292. while (this.particleSystems.length) {
  21293. this.particleSystems[0].dispose();
  21294. }
  21295. // Release sprites
  21296. while (this.spriteManagers.length) {
  21297. this.spriteManagers[0].dispose();
  21298. }
  21299. // Release postProcesses
  21300. while (this.postProcesses.length) {
  21301. this.postProcesses[0].dispose();
  21302. }
  21303. // Release layers
  21304. while (this.layers.length) {
  21305. this.layers[0].dispose();
  21306. }
  21307. while (this.highlightLayers.length) {
  21308. this.highlightLayers[0].dispose();
  21309. }
  21310. // Release textures
  21311. while (this.textures.length) {
  21312. this.textures[0].dispose();
  21313. }
  21314. // Release UBO
  21315. this._sceneUbo.dispose();
  21316. if (this._alternateSceneUbo) {
  21317. this._alternateSceneUbo.dispose();
  21318. }
  21319. // Post-processes
  21320. this.postProcessManager.dispose();
  21321. if (this._postProcessRenderPipelineManager) {
  21322. this._postProcessRenderPipelineManager.dispose();
  21323. }
  21324. // Physics
  21325. if (this._physicsEngine) {
  21326. this.disablePhysicsEngine();
  21327. }
  21328. // Remove from engine
  21329. index = this._engine.scenes.indexOf(this);
  21330. if (index > -1) {
  21331. this._engine.scenes.splice(index, 1);
  21332. }
  21333. this._engine.wipeCaches(true);
  21334. this._isDisposed = true;
  21335. };
  21336. Object.defineProperty(Scene.prototype, "isDisposed", {
  21337. get: function () {
  21338. return this._isDisposed;
  21339. },
  21340. enumerable: true,
  21341. configurable: true
  21342. });
  21343. // Release sounds & sounds tracks
  21344. Scene.prototype.disposeSounds = function () {
  21345. if (!this._mainSoundTrack) {
  21346. return;
  21347. }
  21348. this.mainSoundTrack.dispose();
  21349. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  21350. this.soundTracks[scIndex].dispose();
  21351. }
  21352. };
  21353. // Octrees
  21354. Scene.prototype.getWorldExtends = function () {
  21355. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21356. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  21357. for (var index = 0; index < this.meshes.length; index++) {
  21358. var mesh = this.meshes[index];
  21359. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  21360. continue;
  21361. }
  21362. mesh.computeWorldMatrix(true);
  21363. var boundingInfo = mesh.getBoundingInfo();
  21364. var minBox = boundingInfo.boundingBox.minimumWorld;
  21365. var maxBox = boundingInfo.boundingBox.maximumWorld;
  21366. BABYLON.Tools.CheckExtends(minBox, min, max);
  21367. BABYLON.Tools.CheckExtends(maxBox, min, max);
  21368. }
  21369. return {
  21370. min: min,
  21371. max: max
  21372. };
  21373. };
  21374. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  21375. if (maxCapacity === void 0) { maxCapacity = 64; }
  21376. if (maxDepth === void 0) { maxDepth = 2; }
  21377. if (!this._selectionOctree) {
  21378. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  21379. }
  21380. var worldExtends = this.getWorldExtends();
  21381. // Update octree
  21382. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  21383. return this._selectionOctree;
  21384. };
  21385. // Picking
  21386. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  21387. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  21388. var result = BABYLON.Ray.Zero();
  21389. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  21390. return result;
  21391. };
  21392. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  21393. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  21394. var engine = this._engine;
  21395. if (!camera) {
  21396. if (!this.activeCamera)
  21397. throw new Error("Active camera not set");
  21398. camera = this.activeCamera;
  21399. }
  21400. var cameraViewport = camera.viewport;
  21401. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  21402. // Moving coordinates to local viewport world
  21403. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  21404. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  21405. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  21406. return this;
  21407. };
  21408. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  21409. var result = BABYLON.Ray.Zero();
  21410. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  21411. return result;
  21412. };
  21413. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  21414. if (!BABYLON.PickingInfo) {
  21415. return this;
  21416. }
  21417. var engine = this._engine;
  21418. if (!camera) {
  21419. if (!this.activeCamera)
  21420. throw new Error("Active camera not set");
  21421. camera = this.activeCamera;
  21422. }
  21423. var cameraViewport = camera.viewport;
  21424. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  21425. var identity = BABYLON.Matrix.Identity();
  21426. // Moving coordinates to local viewport world
  21427. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  21428. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  21429. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  21430. return this;
  21431. };
  21432. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  21433. if (!BABYLON.PickingInfo) {
  21434. return null;
  21435. }
  21436. var pickingInfo = null;
  21437. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  21438. var mesh = this.meshes[meshIndex];
  21439. if (predicate) {
  21440. if (!predicate(mesh)) {
  21441. continue;
  21442. }
  21443. }
  21444. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  21445. continue;
  21446. }
  21447. var world = mesh.getWorldMatrix();
  21448. var ray = rayFunction(world);
  21449. var result = mesh.intersects(ray, fastCheck);
  21450. if (!result || !result.hit)
  21451. continue;
  21452. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  21453. continue;
  21454. pickingInfo = result;
  21455. if (fastCheck) {
  21456. break;
  21457. }
  21458. }
  21459. return pickingInfo || new BABYLON.PickingInfo();
  21460. };
  21461. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  21462. if (!BABYLON.PickingInfo) {
  21463. return null;
  21464. }
  21465. var pickingInfos = new Array();
  21466. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  21467. var mesh = this.meshes[meshIndex];
  21468. if (predicate) {
  21469. if (!predicate(mesh)) {
  21470. continue;
  21471. }
  21472. }
  21473. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  21474. continue;
  21475. }
  21476. var world = mesh.getWorldMatrix();
  21477. var ray = rayFunction(world);
  21478. var result = mesh.intersects(ray, false);
  21479. if (!result || !result.hit)
  21480. continue;
  21481. pickingInfos.push(result);
  21482. }
  21483. return pickingInfos;
  21484. };
  21485. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  21486. if (!BABYLON.PickingInfo) {
  21487. return null;
  21488. }
  21489. var pickingInfo = null;
  21490. if (!camera) {
  21491. if (!this.activeCamera) {
  21492. return null;
  21493. }
  21494. camera = this.activeCamera;
  21495. }
  21496. if (this.spriteManagers.length > 0) {
  21497. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  21498. var spriteManager = this.spriteManagers[spriteIndex];
  21499. if (!spriteManager.isPickable) {
  21500. continue;
  21501. }
  21502. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  21503. if (!result || !result.hit)
  21504. continue;
  21505. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  21506. continue;
  21507. pickingInfo = result;
  21508. if (fastCheck) {
  21509. break;
  21510. }
  21511. }
  21512. }
  21513. return pickingInfo || new BABYLON.PickingInfo();
  21514. };
  21515. /** Launch a ray to try to pick a mesh in the scene
  21516. * @param x position on screen
  21517. * @param y position on screen
  21518. * @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
  21519. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  21520. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  21521. */
  21522. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  21523. var _this = this;
  21524. if (!BABYLON.PickingInfo) {
  21525. return null;
  21526. }
  21527. return this._internalPick(function (world) {
  21528. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  21529. return _this._tempPickingRay;
  21530. }, predicate, fastCheck);
  21531. };
  21532. /** Launch a ray to try to pick a sprite in the scene
  21533. * @param x position on screen
  21534. * @param y position on screen
  21535. * @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
  21536. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  21537. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  21538. */
  21539. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  21540. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  21541. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  21542. };
  21543. /** Use the given ray to pick a mesh in the scene
  21544. * @param ray The ray to use to pick meshes
  21545. * @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
  21546. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  21547. */
  21548. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  21549. var _this = this;
  21550. return this._internalPick(function (world) {
  21551. if (!_this._pickWithRayInverseMatrix) {
  21552. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  21553. }
  21554. world.invertToRef(_this._pickWithRayInverseMatrix);
  21555. if (!_this._cachedRayForTransform) {
  21556. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  21557. }
  21558. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  21559. return _this._cachedRayForTransform;
  21560. }, predicate, fastCheck);
  21561. };
  21562. /**
  21563. * Launch a ray to try to pick a mesh in the scene
  21564. * @param x X position on screen
  21565. * @param y Y position on screen
  21566. * @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
  21567. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  21568. */
  21569. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  21570. var _this = this;
  21571. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  21572. };
  21573. /**
  21574. * Launch a ray to try to pick a mesh in the scene
  21575. * @param ray Ray to use
  21576. * @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
  21577. */
  21578. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  21579. var _this = this;
  21580. return this._internalMultiPick(function (world) {
  21581. if (!_this._pickWithRayInverseMatrix) {
  21582. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  21583. }
  21584. world.invertToRef(_this._pickWithRayInverseMatrix);
  21585. if (!_this._cachedRayForTransform) {
  21586. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  21587. }
  21588. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  21589. return _this._cachedRayForTransform;
  21590. }, predicate);
  21591. };
  21592. Scene.prototype.setPointerOverMesh = function (mesh) {
  21593. if (this._pointerOverMesh === mesh) {
  21594. return;
  21595. }
  21596. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  21597. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  21598. }
  21599. this._pointerOverMesh = mesh;
  21600. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  21601. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  21602. }
  21603. };
  21604. Scene.prototype.getPointerOverMesh = function () {
  21605. return this._pointerOverMesh;
  21606. };
  21607. Scene.prototype.setPointerOverSprite = function (sprite) {
  21608. if (this._pointerOverSprite === sprite) {
  21609. return;
  21610. }
  21611. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  21612. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  21613. }
  21614. this._pointerOverSprite = sprite;
  21615. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  21616. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  21617. }
  21618. };
  21619. Scene.prototype.getPointerOverSprite = function () {
  21620. return this._pointerOverSprite;
  21621. };
  21622. // Physics
  21623. Scene.prototype.getPhysicsEngine = function () {
  21624. return this._physicsEngine;
  21625. };
  21626. /**
  21627. * Enables physics to the current scene
  21628. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  21629. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  21630. * @return {boolean} was the physics engine initialized
  21631. */
  21632. Scene.prototype.enablePhysics = function (gravity, plugin) {
  21633. if (gravity === void 0) { gravity = null; }
  21634. if (this._physicsEngine) {
  21635. return true;
  21636. }
  21637. try {
  21638. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  21639. return true;
  21640. }
  21641. catch (e) {
  21642. BABYLON.Tools.Error(e.message);
  21643. return false;
  21644. }
  21645. };
  21646. Scene.prototype.disablePhysicsEngine = function () {
  21647. if (!this._physicsEngine) {
  21648. return;
  21649. }
  21650. this._physicsEngine.dispose();
  21651. this._physicsEngine = null;
  21652. };
  21653. Scene.prototype.isPhysicsEnabled = function () {
  21654. return this._physicsEngine !== undefined;
  21655. };
  21656. Scene.prototype.deleteCompoundImpostor = function (compound) {
  21657. var mesh = compound.parts[0].mesh;
  21658. if (mesh.physicsImpostor) {
  21659. mesh.physicsImpostor.dispose();
  21660. mesh.physicsImpostor = null;
  21661. }
  21662. };
  21663. // Misc.
  21664. Scene.prototype._rebuildGeometries = function () {
  21665. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  21666. var geometry = _a[_i];
  21667. geometry._rebuild();
  21668. }
  21669. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  21670. var mesh = _c[_b];
  21671. mesh._rebuild();
  21672. }
  21673. if (this.postProcessManager) {
  21674. this.postProcessManager._rebuild();
  21675. }
  21676. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  21677. var layer = _e[_d];
  21678. layer._rebuild();
  21679. }
  21680. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  21681. var highlightLayer = _g[_f];
  21682. highlightLayer._rebuild();
  21683. }
  21684. if (this._boundingBoxRenderer) {
  21685. this._boundingBoxRenderer._rebuild();
  21686. }
  21687. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  21688. var system = _j[_h];
  21689. system.rebuild();
  21690. }
  21691. if (this._postProcessRenderPipelineManager) {
  21692. this._postProcessRenderPipelineManager._rebuild();
  21693. }
  21694. };
  21695. Scene.prototype._rebuildTextures = function () {
  21696. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  21697. var texture = _a[_i];
  21698. texture._rebuild();
  21699. }
  21700. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21701. };
  21702. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  21703. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  21704. if (replace === void 0) { replace = false; }
  21705. if (attachCameraControls === void 0) { attachCameraControls = false; }
  21706. // Dispose existing camera or light in replace mode.
  21707. if (replace) {
  21708. if (this.activeCamera) {
  21709. this.activeCamera.dispose();
  21710. this.activeCamera = null;
  21711. }
  21712. if (this.lights) {
  21713. for (var i = 0; i < this.lights.length; i++) {
  21714. this.lights[i].dispose();
  21715. }
  21716. }
  21717. }
  21718. // Light
  21719. if (this.lights.length === 0) {
  21720. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  21721. }
  21722. // Camera
  21723. if (!this.activeCamera) {
  21724. var worldExtends = this.getWorldExtends();
  21725. var worldSize = worldExtends.max.subtract(worldExtends.min);
  21726. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  21727. var camera;
  21728. var radius = worldSize.length() * 1.5;
  21729. if (createArcRotateCamera) {
  21730. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  21731. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  21732. arcRotateCamera.wheelPrecision = 100 / radius;
  21733. camera = arcRotateCamera;
  21734. }
  21735. else {
  21736. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  21737. freeCamera.setTarget(worldCenter);
  21738. camera = freeCamera;
  21739. }
  21740. camera.minZ = radius * 0.01;
  21741. camera.maxZ = radius * 1000;
  21742. camera.speed = radius * 0.2;
  21743. this.activeCamera = camera;
  21744. var canvas = this.getEngine().getRenderingCanvas();
  21745. if (attachCameraControls && canvas) {
  21746. camera.attachControl(canvas);
  21747. }
  21748. }
  21749. };
  21750. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  21751. if (pbr === void 0) { pbr = false; }
  21752. if (scale === void 0) { scale = 1000; }
  21753. if (blur === void 0) { blur = 0; }
  21754. if (environmentTexture) {
  21755. this.environmentTexture = environmentTexture;
  21756. }
  21757. if (!this.environmentTexture) {
  21758. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  21759. return null;
  21760. }
  21761. // Skybox
  21762. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  21763. if (pbr) {
  21764. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  21765. hdrSkyboxMaterial.backFaceCulling = false;
  21766. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  21767. if (hdrSkyboxMaterial.reflectionTexture) {
  21768. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  21769. }
  21770. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  21771. hdrSkyboxMaterial.disableLighting = true;
  21772. hdrSkyboxMaterial.twoSidedLighting = true;
  21773. hdrSkybox.infiniteDistance = true;
  21774. hdrSkybox.material = hdrSkyboxMaterial;
  21775. }
  21776. else {
  21777. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  21778. skyboxMaterial.backFaceCulling = false;
  21779. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  21780. if (skyboxMaterial.reflectionTexture) {
  21781. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  21782. }
  21783. skyboxMaterial.disableLighting = true;
  21784. hdrSkybox.infiniteDistance = true;
  21785. hdrSkybox.material = skyboxMaterial;
  21786. }
  21787. return hdrSkybox;
  21788. };
  21789. Scene.prototype.createDefaultEnvironment = function (options) {
  21790. if (BABYLON.EnvironmentHelper) {
  21791. return new BABYLON.EnvironmentHelper(options, this);
  21792. }
  21793. return null;
  21794. };
  21795. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  21796. if (webVROptions === void 0) { webVROptions = {}; }
  21797. return new BABYLON.VRExperienceHelper(this, webVROptions);
  21798. };
  21799. // Tags
  21800. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  21801. if (tagsQuery === undefined) {
  21802. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  21803. return list;
  21804. }
  21805. var listByTags = [];
  21806. forEach = forEach || (function (item) { return; });
  21807. for (var i in list) {
  21808. var item = list[i];
  21809. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  21810. listByTags.push(item);
  21811. forEach(item);
  21812. }
  21813. }
  21814. return listByTags;
  21815. };
  21816. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  21817. return this._getByTags(this.meshes, tagsQuery, forEach);
  21818. };
  21819. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  21820. return this._getByTags(this.cameras, tagsQuery, forEach);
  21821. };
  21822. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  21823. return this._getByTags(this.lights, tagsQuery, forEach);
  21824. };
  21825. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  21826. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  21827. };
  21828. /**
  21829. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  21830. * This allowed control for front to back rendering or reversly depending of the special needs.
  21831. *
  21832. * @param renderingGroupId The rendering group id corresponding to its index
  21833. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  21834. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  21835. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  21836. */
  21837. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21838. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21839. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21840. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21841. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  21842. };
  21843. /**
  21844. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  21845. *
  21846. * @param renderingGroupId The rendering group id corresponding to its index
  21847. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  21848. * @param depth Automatically clears depth between groups if true and autoClear is true.
  21849. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  21850. */
  21851. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  21852. if (depth === void 0) { depth = true; }
  21853. if (stencil === void 0) { stencil = true; }
  21854. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  21855. };
  21856. /**
  21857. * Will flag all materials as dirty to trigger new shader compilation
  21858. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  21859. */
  21860. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  21861. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  21862. var material = _a[_i];
  21863. if (predicate && !predicate(material)) {
  21864. continue;
  21865. }
  21866. material.markAsDirty(flag);
  21867. }
  21868. };
  21869. // Statics
  21870. Scene._FOGMODE_NONE = 0;
  21871. Scene._FOGMODE_EXP = 1;
  21872. Scene._FOGMODE_EXP2 = 2;
  21873. Scene._FOGMODE_LINEAR = 3;
  21874. Scene._uniqueIdCounter = 0;
  21875. Scene.MinDeltaTime = 1.0;
  21876. Scene.MaxDeltaTime = 1000.0;
  21877. /** The distance in pixel that you have to move to prevent some events */
  21878. Scene.DragMovementThreshold = 10; // in pixels
  21879. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  21880. Scene.LongPressDelay = 500; // in milliseconds
  21881. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  21882. Scene.DoubleClickDelay = 300; // in milliseconds
  21883. /** If you need to check double click without raising a single click at first click, enable this flag */
  21884. Scene.ExclusiveDoubleClickMode = false;
  21885. return Scene;
  21886. }());
  21887. BABYLON.Scene = Scene;
  21888. })(BABYLON || (BABYLON = {}));
  21889. //# sourceMappingURL=babylon.scene.js.map
  21890. var BABYLON;
  21891. (function (BABYLON) {
  21892. var Buffer = /** @class */ (function () {
  21893. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  21894. if (instanced === void 0) { instanced = false; }
  21895. if (engine instanceof BABYLON.Mesh) {
  21896. this._engine = engine.getScene().getEngine();
  21897. }
  21898. else {
  21899. this._engine = engine;
  21900. }
  21901. this._updatable = updatable;
  21902. this._data = data;
  21903. this._strideSize = stride;
  21904. if (!postponeInternalCreation) {
  21905. this.create();
  21906. }
  21907. this._instanced = instanced;
  21908. this._instanceDivisor = instanced ? 1 : 0;
  21909. }
  21910. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  21911. // a lot of these parameters are ignored as they are overriden by the buffer
  21912. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  21913. };
  21914. // Properties
  21915. Buffer.prototype.isUpdatable = function () {
  21916. return this._updatable;
  21917. };
  21918. Buffer.prototype.getData = function () {
  21919. return this._data;
  21920. };
  21921. Buffer.prototype.getBuffer = function () {
  21922. return this._buffer;
  21923. };
  21924. Buffer.prototype.getStrideSize = function () {
  21925. return this._strideSize;
  21926. };
  21927. Buffer.prototype.getIsInstanced = function () {
  21928. return this._instanced;
  21929. };
  21930. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  21931. get: function () {
  21932. return this._instanceDivisor;
  21933. },
  21934. set: function (value) {
  21935. this._instanceDivisor = value;
  21936. if (value == 0) {
  21937. this._instanced = false;
  21938. }
  21939. else {
  21940. this._instanced = true;
  21941. }
  21942. },
  21943. enumerable: true,
  21944. configurable: true
  21945. });
  21946. // Methods
  21947. Buffer.prototype.create = function (data) {
  21948. if (data === void 0) { data = null; }
  21949. if (!data && this._buffer) {
  21950. return; // nothing to do
  21951. }
  21952. data = data || this._data;
  21953. if (!data) {
  21954. return;
  21955. }
  21956. if (!this._buffer) {
  21957. if (this._updatable) {
  21958. this._buffer = this._engine.createDynamicVertexBuffer(data);
  21959. this._data = data;
  21960. }
  21961. else {
  21962. this._buffer = this._engine.createVertexBuffer(data);
  21963. }
  21964. }
  21965. else if (this._updatable) {
  21966. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  21967. this._data = data;
  21968. }
  21969. };
  21970. Buffer.prototype._rebuild = function () {
  21971. this._buffer = null;
  21972. this.create(this._data);
  21973. };
  21974. Buffer.prototype.update = function (data) {
  21975. this.create(data);
  21976. };
  21977. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  21978. if (!this._buffer) {
  21979. return;
  21980. }
  21981. if (this._updatable) {
  21982. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  21983. this._data = null;
  21984. }
  21985. };
  21986. Buffer.prototype.dispose = function () {
  21987. if (!this._buffer) {
  21988. return;
  21989. }
  21990. if (this._engine._releaseBuffer(this._buffer)) {
  21991. this._buffer = null;
  21992. }
  21993. };
  21994. return Buffer;
  21995. }());
  21996. BABYLON.Buffer = Buffer;
  21997. })(BABYLON || (BABYLON = {}));
  21998. //# sourceMappingURL=babylon.buffer.js.map
  21999. var BABYLON;
  22000. (function (BABYLON) {
  22001. var VertexBuffer = /** @class */ (function () {
  22002. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  22003. if (!stride) {
  22004. // Deduce stride from kind
  22005. switch (kind) {
  22006. case VertexBuffer.PositionKind:
  22007. stride = 3;
  22008. break;
  22009. case VertexBuffer.NormalKind:
  22010. stride = 3;
  22011. break;
  22012. case VertexBuffer.UVKind:
  22013. case VertexBuffer.UV2Kind:
  22014. case VertexBuffer.UV3Kind:
  22015. case VertexBuffer.UV4Kind:
  22016. case VertexBuffer.UV5Kind:
  22017. case VertexBuffer.UV6Kind:
  22018. stride = 2;
  22019. break;
  22020. case VertexBuffer.TangentKind:
  22021. case VertexBuffer.ColorKind:
  22022. stride = 4;
  22023. break;
  22024. case VertexBuffer.MatricesIndicesKind:
  22025. case VertexBuffer.MatricesIndicesExtraKind:
  22026. stride = 4;
  22027. break;
  22028. case VertexBuffer.MatricesWeightsKind:
  22029. case VertexBuffer.MatricesWeightsExtraKind:
  22030. default:
  22031. stride = 4;
  22032. break;
  22033. }
  22034. }
  22035. if (data instanceof BABYLON.Buffer) {
  22036. if (!stride) {
  22037. stride = data.getStrideSize();
  22038. }
  22039. this._buffer = data;
  22040. this._ownsBuffer = false;
  22041. }
  22042. else {
  22043. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  22044. this._ownsBuffer = true;
  22045. }
  22046. this._stride = stride;
  22047. this._offset = offset ? offset : 0;
  22048. this._size = size ? size : stride;
  22049. this._kind = kind;
  22050. }
  22051. VertexBuffer.prototype._rebuild = function () {
  22052. if (!this._buffer) {
  22053. return;
  22054. }
  22055. this._buffer._rebuild();
  22056. };
  22057. /**
  22058. * Returns the kind of the VertexBuffer (string).
  22059. */
  22060. VertexBuffer.prototype.getKind = function () {
  22061. return this._kind;
  22062. };
  22063. // Properties
  22064. /**
  22065. * Boolean : is the VertexBuffer updatable ?
  22066. */
  22067. VertexBuffer.prototype.isUpdatable = function () {
  22068. return this._buffer.isUpdatable();
  22069. };
  22070. /**
  22071. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  22072. */
  22073. VertexBuffer.prototype.getData = function () {
  22074. return this._buffer.getData();
  22075. };
  22076. /**
  22077. * Returns the WebGLBuffer associated to the VertexBuffer.
  22078. */
  22079. VertexBuffer.prototype.getBuffer = function () {
  22080. return this._buffer.getBuffer();
  22081. };
  22082. /**
  22083. * Returns the stride of the VertexBuffer (integer).
  22084. */
  22085. VertexBuffer.prototype.getStrideSize = function () {
  22086. return this._stride;
  22087. };
  22088. /**
  22089. * Returns the offset (integer).
  22090. */
  22091. VertexBuffer.prototype.getOffset = function () {
  22092. return this._offset;
  22093. };
  22094. /**
  22095. * Returns the VertexBuffer total size (integer).
  22096. */
  22097. VertexBuffer.prototype.getSize = function () {
  22098. return this._size;
  22099. };
  22100. /**
  22101. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  22102. */
  22103. VertexBuffer.prototype.getIsInstanced = function () {
  22104. return this._buffer.getIsInstanced();
  22105. };
  22106. /**
  22107. * Returns the instancing divisor, zero for non-instanced (integer).
  22108. */
  22109. VertexBuffer.prototype.getInstanceDivisor = function () {
  22110. return this._buffer.instanceDivisor;
  22111. };
  22112. // Methods
  22113. /**
  22114. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  22115. * Returns the created WebGLBuffer.
  22116. */
  22117. VertexBuffer.prototype.create = function (data) {
  22118. return this._buffer.create(data);
  22119. };
  22120. /**
  22121. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  22122. * Returns the updated WebGLBuffer.
  22123. */
  22124. VertexBuffer.prototype.update = function (data) {
  22125. return this._buffer.update(data);
  22126. };
  22127. /**
  22128. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  22129. * Returns the directly updated WebGLBuffer.
  22130. */
  22131. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  22132. return this._buffer.updateDirectly(data, offset);
  22133. };
  22134. /**
  22135. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  22136. */
  22137. VertexBuffer.prototype.dispose = function () {
  22138. if (this._ownsBuffer) {
  22139. this._buffer.dispose();
  22140. }
  22141. };
  22142. Object.defineProperty(VertexBuffer, "PositionKind", {
  22143. get: function () {
  22144. return VertexBuffer._PositionKind;
  22145. },
  22146. enumerable: true,
  22147. configurable: true
  22148. });
  22149. Object.defineProperty(VertexBuffer, "NormalKind", {
  22150. get: function () {
  22151. return VertexBuffer._NormalKind;
  22152. },
  22153. enumerable: true,
  22154. configurable: true
  22155. });
  22156. Object.defineProperty(VertexBuffer, "TangentKind", {
  22157. get: function () {
  22158. return VertexBuffer._TangentKind;
  22159. },
  22160. enumerable: true,
  22161. configurable: true
  22162. });
  22163. Object.defineProperty(VertexBuffer, "UVKind", {
  22164. get: function () {
  22165. return VertexBuffer._UVKind;
  22166. },
  22167. enumerable: true,
  22168. configurable: true
  22169. });
  22170. Object.defineProperty(VertexBuffer, "UV2Kind", {
  22171. get: function () {
  22172. return VertexBuffer._UV2Kind;
  22173. },
  22174. enumerable: true,
  22175. configurable: true
  22176. });
  22177. Object.defineProperty(VertexBuffer, "UV3Kind", {
  22178. get: function () {
  22179. return VertexBuffer._UV3Kind;
  22180. },
  22181. enumerable: true,
  22182. configurable: true
  22183. });
  22184. Object.defineProperty(VertexBuffer, "UV4Kind", {
  22185. get: function () {
  22186. return VertexBuffer._UV4Kind;
  22187. },
  22188. enumerable: true,
  22189. configurable: true
  22190. });
  22191. Object.defineProperty(VertexBuffer, "UV5Kind", {
  22192. get: function () {
  22193. return VertexBuffer._UV5Kind;
  22194. },
  22195. enumerable: true,
  22196. configurable: true
  22197. });
  22198. Object.defineProperty(VertexBuffer, "UV6Kind", {
  22199. get: function () {
  22200. return VertexBuffer._UV6Kind;
  22201. },
  22202. enumerable: true,
  22203. configurable: true
  22204. });
  22205. Object.defineProperty(VertexBuffer, "ColorKind", {
  22206. get: function () {
  22207. return VertexBuffer._ColorKind;
  22208. },
  22209. enumerable: true,
  22210. configurable: true
  22211. });
  22212. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  22213. get: function () {
  22214. return VertexBuffer._MatricesIndicesKind;
  22215. },
  22216. enumerable: true,
  22217. configurable: true
  22218. });
  22219. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  22220. get: function () {
  22221. return VertexBuffer._MatricesWeightsKind;
  22222. },
  22223. enumerable: true,
  22224. configurable: true
  22225. });
  22226. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  22227. get: function () {
  22228. return VertexBuffer._MatricesIndicesExtraKind;
  22229. },
  22230. enumerable: true,
  22231. configurable: true
  22232. });
  22233. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  22234. get: function () {
  22235. return VertexBuffer._MatricesWeightsExtraKind;
  22236. },
  22237. enumerable: true,
  22238. configurable: true
  22239. });
  22240. // Enums
  22241. VertexBuffer._PositionKind = "position";
  22242. VertexBuffer._NormalKind = "normal";
  22243. VertexBuffer._TangentKind = "tangent";
  22244. VertexBuffer._UVKind = "uv";
  22245. VertexBuffer._UV2Kind = "uv2";
  22246. VertexBuffer._UV3Kind = "uv3";
  22247. VertexBuffer._UV4Kind = "uv4";
  22248. VertexBuffer._UV5Kind = "uv5";
  22249. VertexBuffer._UV6Kind = "uv6";
  22250. VertexBuffer._ColorKind = "color";
  22251. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  22252. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  22253. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  22254. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  22255. return VertexBuffer;
  22256. }());
  22257. BABYLON.VertexBuffer = VertexBuffer;
  22258. })(BABYLON || (BABYLON = {}));
  22259. //# sourceMappingURL=babylon.vertexBuffer.js.map
  22260. var BABYLON;
  22261. (function (BABYLON) {
  22262. var InternalTexture = /** @class */ (function () {
  22263. function InternalTexture(engine, dataSource) {
  22264. this.onLoadedObservable = new BABYLON.Observable();
  22265. // Private
  22266. this._initialSlot = -1;
  22267. this._designatedSlot = -1;
  22268. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  22269. this._references = 1;
  22270. this._engine = engine;
  22271. this._dataSource = dataSource;
  22272. this._webGLTexture = engine._createTexture();
  22273. }
  22274. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  22275. get: function () {
  22276. return this._dataSource;
  22277. },
  22278. enumerable: true,
  22279. configurable: true
  22280. });
  22281. InternalTexture.prototype.incrementReferences = function () {
  22282. this._references++;
  22283. };
  22284. InternalTexture.prototype.updateSize = function (width, height, depth) {
  22285. if (depth === void 0) { depth = 1; }
  22286. this.width = width;
  22287. this.height = height;
  22288. this.depth = depth;
  22289. this.baseWidth = width;
  22290. this.baseHeight = height;
  22291. this.baseDepth = depth;
  22292. this._size = width * height * depth;
  22293. };
  22294. InternalTexture.prototype._rebuild = function () {
  22295. var _this = this;
  22296. var proxy;
  22297. this.isReady = false;
  22298. this._cachedCoordinatesMode = null;
  22299. this._cachedWrapU = null;
  22300. this._cachedWrapV = null;
  22301. this._cachedAnisotropicFilteringLevel = null;
  22302. switch (this._dataSource) {
  22303. case InternalTexture.DATASOURCE_TEMP:
  22304. return;
  22305. case InternalTexture.DATASOURCE_URL:
  22306. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  22307. _this.isReady = true;
  22308. }, null, this._buffer, undefined, this.format);
  22309. proxy._swapAndDie(this);
  22310. return;
  22311. case InternalTexture.DATASOURCE_RAW:
  22312. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  22313. proxy._swapAndDie(this);
  22314. this.isReady = true;
  22315. return;
  22316. case InternalTexture.DATASOURCE_RAW3D:
  22317. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  22318. proxy._swapAndDie(this);
  22319. this.isReady = true;
  22320. return;
  22321. case InternalTexture.DATASOURCE_DYNAMIC:
  22322. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  22323. proxy._swapAndDie(this);
  22324. // The engine will make sure to update content so no need to flag it as isReady = true
  22325. return;
  22326. case InternalTexture.DATASOURCE_RENDERTARGET:
  22327. var options = new BABYLON.RenderTargetCreationOptions();
  22328. options.generateDepthBuffer = this._generateDepthBuffer;
  22329. options.generateMipMaps = this.generateMipMaps;
  22330. options.generateStencilBuffer = this._generateStencilBuffer;
  22331. options.samplingMode = this.samplingMode;
  22332. options.type = this.type;
  22333. if (this.isCube) {
  22334. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  22335. }
  22336. else {
  22337. var size = {
  22338. width: this.width,
  22339. height: this.height
  22340. };
  22341. proxy = this._engine.createRenderTargetTexture(size, options);
  22342. }
  22343. proxy._swapAndDie(this);
  22344. this.isReady = true;
  22345. return;
  22346. case InternalTexture.DATASOURCE_CUBE:
  22347. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  22348. _this.isReady = true;
  22349. }, null, this.format, this._extension);
  22350. proxy._swapAndDie(this);
  22351. return;
  22352. case InternalTexture.DATASOURCE_CUBERAW:
  22353. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  22354. proxy._swapAndDie(this);
  22355. this.isReady = true;
  22356. return;
  22357. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  22358. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  22359. if (proxy) {
  22360. proxy._swapAndDie(_this);
  22361. }
  22362. _this.isReady = true;
  22363. }, null, this.format, this._extension);
  22364. return;
  22365. }
  22366. };
  22367. InternalTexture.prototype._swapAndDie = function (target) {
  22368. target._webGLTexture = this._webGLTexture;
  22369. if (this._framebuffer) {
  22370. target._framebuffer = this._framebuffer;
  22371. }
  22372. if (this._depthStencilBuffer) {
  22373. target._depthStencilBuffer = this._depthStencilBuffer;
  22374. }
  22375. if (this._lodTextureHigh) {
  22376. if (target._lodTextureHigh) {
  22377. target._lodTextureHigh.dispose();
  22378. }
  22379. target._lodTextureHigh = this._lodTextureHigh;
  22380. }
  22381. if (this._lodTextureMid) {
  22382. if (target._lodTextureMid) {
  22383. target._lodTextureMid.dispose();
  22384. }
  22385. target._lodTextureMid = this._lodTextureMid;
  22386. }
  22387. if (this._lodTextureLow) {
  22388. if (target._lodTextureLow) {
  22389. target._lodTextureLow.dispose();
  22390. }
  22391. target._lodTextureLow = this._lodTextureLow;
  22392. }
  22393. var cache = this._engine.getLoadedTexturesCache();
  22394. var index = cache.indexOf(this);
  22395. if (index !== -1) {
  22396. cache.splice(index, 1);
  22397. }
  22398. };
  22399. InternalTexture.prototype.dispose = function () {
  22400. if (!this._webGLTexture) {
  22401. return;
  22402. }
  22403. this._references--;
  22404. if (this._references === 0) {
  22405. this._engine._releaseTexture(this);
  22406. this._webGLTexture = null;
  22407. }
  22408. };
  22409. InternalTexture.DATASOURCE_UNKNOWN = 0;
  22410. InternalTexture.DATASOURCE_URL = 1;
  22411. InternalTexture.DATASOURCE_TEMP = 2;
  22412. InternalTexture.DATASOURCE_RAW = 3;
  22413. InternalTexture.DATASOURCE_DYNAMIC = 4;
  22414. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  22415. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  22416. InternalTexture.DATASOURCE_CUBE = 7;
  22417. InternalTexture.DATASOURCE_CUBERAW = 8;
  22418. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  22419. InternalTexture.DATASOURCE_RAW3D = 10;
  22420. return InternalTexture;
  22421. }());
  22422. BABYLON.InternalTexture = InternalTexture;
  22423. })(BABYLON || (BABYLON = {}));
  22424. //# sourceMappingURL=babylon.internalTexture.js.map
  22425. var BABYLON;
  22426. (function (BABYLON) {
  22427. var BaseTexture = /** @class */ (function () {
  22428. function BaseTexture(scene) {
  22429. this._hasAlpha = false;
  22430. this.getAlphaFromRGB = false;
  22431. this.level = 1;
  22432. this.coordinatesIndex = 0;
  22433. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  22434. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  22435. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  22436. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  22437. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  22438. this.isCube = false;
  22439. this.is3D = false;
  22440. this.gammaSpace = true;
  22441. this.invertZ = false;
  22442. this.lodLevelInAlpha = false;
  22443. this.lodGenerationOffset = 0.0;
  22444. this.lodGenerationScale = 0.8;
  22445. this.isRenderTarget = false;
  22446. this.animations = new Array();
  22447. /**
  22448. * An event triggered when the texture is disposed.
  22449. * @type {BABYLON.Observable}
  22450. */
  22451. this.onDisposeObservable = new BABYLON.Observable();
  22452. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22453. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  22454. if (this._scene) {
  22455. this._scene.textures.push(this);
  22456. }
  22457. this._uid = null;
  22458. }
  22459. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  22460. get: function () {
  22461. return this._hasAlpha;
  22462. },
  22463. set: function (value) {
  22464. if (this._hasAlpha === value) {
  22465. return;
  22466. }
  22467. this._hasAlpha = value;
  22468. if (this._scene) {
  22469. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22470. }
  22471. },
  22472. enumerable: true,
  22473. configurable: true
  22474. });
  22475. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  22476. get: function () {
  22477. return this._coordinatesMode;
  22478. },
  22479. set: function (value) {
  22480. if (this._coordinatesMode === value) {
  22481. return;
  22482. }
  22483. this._coordinatesMode = value;
  22484. if (this._scene) {
  22485. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22486. }
  22487. },
  22488. enumerable: true,
  22489. configurable: true
  22490. });
  22491. Object.defineProperty(BaseTexture.prototype, "uid", {
  22492. get: function () {
  22493. if (!this._uid) {
  22494. this._uid = BABYLON.Tools.RandomId();
  22495. }
  22496. return this._uid;
  22497. },
  22498. enumerable: true,
  22499. configurable: true
  22500. });
  22501. BaseTexture.prototype.toString = function () {
  22502. return this.name;
  22503. };
  22504. BaseTexture.prototype.getClassName = function () {
  22505. return "BaseTexture";
  22506. };
  22507. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  22508. set: function (callback) {
  22509. if (this._onDisposeObserver) {
  22510. this.onDisposeObservable.remove(this._onDisposeObserver);
  22511. }
  22512. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22513. },
  22514. enumerable: true,
  22515. configurable: true
  22516. });
  22517. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  22518. get: function () {
  22519. return true;
  22520. },
  22521. enumerable: true,
  22522. configurable: true
  22523. });
  22524. BaseTexture.prototype.getScene = function () {
  22525. return this._scene;
  22526. };
  22527. BaseTexture.prototype.getTextureMatrix = function () {
  22528. return BABYLON.Matrix.IdentityReadOnly;
  22529. };
  22530. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  22531. return BABYLON.Matrix.IdentityReadOnly;
  22532. };
  22533. BaseTexture.prototype.getInternalTexture = function () {
  22534. return this._texture;
  22535. };
  22536. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  22537. return !this.isBlocking || this.isReady();
  22538. };
  22539. BaseTexture.prototype.isReady = function () {
  22540. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22541. this.delayLoad();
  22542. return false;
  22543. }
  22544. if (this._texture) {
  22545. return this._texture.isReady;
  22546. }
  22547. return false;
  22548. };
  22549. BaseTexture.prototype.getSize = function () {
  22550. if (this._texture && this._texture.width) {
  22551. return new BABYLON.Size(this._texture.width, this._texture.height);
  22552. }
  22553. if (this._texture && this._texture._size) {
  22554. return new BABYLON.Size(this._texture._size, this._texture._size);
  22555. }
  22556. return BABYLON.Size.Zero();
  22557. };
  22558. BaseTexture.prototype.getBaseSize = function () {
  22559. if (!this.isReady() || !this._texture)
  22560. return BABYLON.Size.Zero();
  22561. if (this._texture._size) {
  22562. return new BABYLON.Size(this._texture._size, this._texture._size);
  22563. }
  22564. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  22565. };
  22566. BaseTexture.prototype.scale = function (ratio) {
  22567. };
  22568. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  22569. get: function () {
  22570. return false;
  22571. },
  22572. enumerable: true,
  22573. configurable: true
  22574. });
  22575. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  22576. if (!this._scene) {
  22577. return null;
  22578. }
  22579. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  22580. for (var index = 0; index < texturesCache.length; index++) {
  22581. var texturesCacheEntry = texturesCache[index];
  22582. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  22583. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  22584. texturesCacheEntry.incrementReferences();
  22585. return texturesCacheEntry;
  22586. }
  22587. }
  22588. }
  22589. return null;
  22590. };
  22591. BaseTexture.prototype._rebuild = function () {
  22592. };
  22593. BaseTexture.prototype.delayLoad = function () {
  22594. };
  22595. BaseTexture.prototype.clone = function () {
  22596. return null;
  22597. };
  22598. Object.defineProperty(BaseTexture.prototype, "textureType", {
  22599. get: function () {
  22600. if (!this._texture) {
  22601. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  22602. }
  22603. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  22604. },
  22605. enumerable: true,
  22606. configurable: true
  22607. });
  22608. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  22609. get: function () {
  22610. if (!this._texture) {
  22611. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  22612. }
  22613. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  22614. },
  22615. enumerable: true,
  22616. configurable: true
  22617. });
  22618. BaseTexture.prototype.readPixels = function (faceIndex) {
  22619. if (faceIndex === void 0) { faceIndex = 0; }
  22620. if (!this._texture) {
  22621. return null;
  22622. }
  22623. var size = this.getSize();
  22624. var scene = this.getScene();
  22625. if (!scene) {
  22626. return null;
  22627. }
  22628. var engine = scene.getEngine();
  22629. if (this._texture.isCube) {
  22630. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  22631. }
  22632. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  22633. };
  22634. BaseTexture.prototype.releaseInternalTexture = function () {
  22635. if (this._texture) {
  22636. this._texture.dispose();
  22637. this._texture = null;
  22638. }
  22639. };
  22640. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  22641. get: function () {
  22642. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  22643. return null;
  22644. }
  22645. if (!this._texture._sphericalPolynomial) {
  22646. this._texture._sphericalPolynomial =
  22647. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  22648. }
  22649. return this._texture._sphericalPolynomial;
  22650. },
  22651. set: function (value) {
  22652. if (this._texture) {
  22653. this._texture._sphericalPolynomial = value;
  22654. }
  22655. },
  22656. enumerable: true,
  22657. configurable: true
  22658. });
  22659. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  22660. get: function () {
  22661. if (this._texture) {
  22662. return this._texture._lodTextureHigh;
  22663. }
  22664. return null;
  22665. },
  22666. enumerable: true,
  22667. configurable: true
  22668. });
  22669. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  22670. get: function () {
  22671. if (this._texture) {
  22672. return this._texture._lodTextureMid;
  22673. }
  22674. return null;
  22675. },
  22676. enumerable: true,
  22677. configurable: true
  22678. });
  22679. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  22680. get: function () {
  22681. if (this._texture) {
  22682. return this._texture._lodTextureLow;
  22683. }
  22684. return null;
  22685. },
  22686. enumerable: true,
  22687. configurable: true
  22688. });
  22689. BaseTexture.prototype.dispose = function () {
  22690. if (!this._scene) {
  22691. return;
  22692. }
  22693. // Animations
  22694. this._scene.stopAnimation(this);
  22695. // Remove from scene
  22696. this._scene._removePendingData(this);
  22697. var index = this._scene.textures.indexOf(this);
  22698. if (index >= 0) {
  22699. this._scene.textures.splice(index, 1);
  22700. }
  22701. if (this._texture === undefined) {
  22702. return;
  22703. }
  22704. // Release
  22705. this.releaseInternalTexture();
  22706. // Callback
  22707. this.onDisposeObservable.notifyObservers(this);
  22708. this.onDisposeObservable.clear();
  22709. };
  22710. BaseTexture.prototype.serialize = function () {
  22711. if (!this.name) {
  22712. return null;
  22713. }
  22714. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22715. // Animations
  22716. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22717. return serializationObject;
  22718. };
  22719. BaseTexture.WhenAllReady = function (textures, callback) {
  22720. var numRemaining = textures.length;
  22721. if (numRemaining === 0) {
  22722. callback();
  22723. return;
  22724. }
  22725. var _loop_1 = function () {
  22726. texture = textures[i];
  22727. if (texture.isReady()) {
  22728. if (--numRemaining === 0) {
  22729. callback();
  22730. }
  22731. }
  22732. else {
  22733. onLoadObservable = texture.onLoadObservable;
  22734. var onLoadCallback_1 = function () {
  22735. onLoadObservable.removeCallback(onLoadCallback_1);
  22736. if (--numRemaining === 0) {
  22737. callback();
  22738. }
  22739. };
  22740. onLoadObservable.add(onLoadCallback_1);
  22741. }
  22742. };
  22743. var texture, onLoadObservable;
  22744. for (var i = 0; i < textures.length; i++) {
  22745. _loop_1();
  22746. }
  22747. };
  22748. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  22749. __decorate([
  22750. BABYLON.serialize()
  22751. ], BaseTexture.prototype, "name", void 0);
  22752. __decorate([
  22753. BABYLON.serialize("hasAlpha")
  22754. ], BaseTexture.prototype, "_hasAlpha", void 0);
  22755. __decorate([
  22756. BABYLON.serialize()
  22757. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  22758. __decorate([
  22759. BABYLON.serialize()
  22760. ], BaseTexture.prototype, "level", void 0);
  22761. __decorate([
  22762. BABYLON.serialize()
  22763. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  22764. __decorate([
  22765. BABYLON.serialize("coordinatesMode")
  22766. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  22767. __decorate([
  22768. BABYLON.serialize()
  22769. ], BaseTexture.prototype, "wrapU", void 0);
  22770. __decorate([
  22771. BABYLON.serialize()
  22772. ], BaseTexture.prototype, "wrapV", void 0);
  22773. __decorate([
  22774. BABYLON.serialize()
  22775. ], BaseTexture.prototype, "wrapR", void 0);
  22776. __decorate([
  22777. BABYLON.serialize()
  22778. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  22779. __decorate([
  22780. BABYLON.serialize()
  22781. ], BaseTexture.prototype, "isCube", void 0);
  22782. __decorate([
  22783. BABYLON.serialize()
  22784. ], BaseTexture.prototype, "is3D", void 0);
  22785. __decorate([
  22786. BABYLON.serialize()
  22787. ], BaseTexture.prototype, "gammaSpace", void 0);
  22788. __decorate([
  22789. BABYLON.serialize()
  22790. ], BaseTexture.prototype, "invertZ", void 0);
  22791. __decorate([
  22792. BABYLON.serialize()
  22793. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  22794. __decorate([
  22795. BABYLON.serialize()
  22796. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  22797. __decorate([
  22798. BABYLON.serialize()
  22799. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  22800. __decorate([
  22801. BABYLON.serialize()
  22802. ], BaseTexture.prototype, "isRenderTarget", void 0);
  22803. return BaseTexture;
  22804. }());
  22805. BABYLON.BaseTexture = BaseTexture;
  22806. })(BABYLON || (BABYLON = {}));
  22807. //# sourceMappingURL=babylon.baseTexture.js.map
  22808. var BABYLON;
  22809. (function (BABYLON) {
  22810. var Texture = /** @class */ (function (_super) {
  22811. __extends(Texture, _super);
  22812. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  22813. if (noMipmap === void 0) { noMipmap = false; }
  22814. if (invertY === void 0) { invertY = true; }
  22815. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22816. if (onLoad === void 0) { onLoad = null; }
  22817. if (onError === void 0) { onError = null; }
  22818. if (buffer === void 0) { buffer = null; }
  22819. if (deleteBuffer === void 0) { deleteBuffer = false; }
  22820. var _this = _super.call(this, scene) || this;
  22821. _this.uOffset = 0;
  22822. _this.vOffset = 0;
  22823. _this.uScale = 1.0;
  22824. _this.vScale = 1.0;
  22825. _this.uAng = 0;
  22826. _this.vAng = 0;
  22827. _this.wAng = 0;
  22828. _this._isBlocking = true;
  22829. _this.name = url || "";
  22830. _this.url = url;
  22831. _this._noMipmap = noMipmap;
  22832. _this._invertY = invertY;
  22833. _this._samplingMode = samplingMode;
  22834. _this._buffer = buffer;
  22835. _this._deleteBuffer = deleteBuffer;
  22836. if (format) {
  22837. _this._format = format;
  22838. }
  22839. scene = _this.getScene();
  22840. if (!scene) {
  22841. return _this;
  22842. }
  22843. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  22844. var load = function () {
  22845. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  22846. _this.onLoadObservable.notifyObservers(_this);
  22847. }
  22848. if (onLoad) {
  22849. onLoad();
  22850. }
  22851. if (!_this.isBlocking && scene) {
  22852. scene.resetCachedMaterial();
  22853. }
  22854. };
  22855. if (!_this.url) {
  22856. _this._delayedOnLoad = load;
  22857. _this._delayedOnError = onError;
  22858. return _this;
  22859. }
  22860. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  22861. if (!_this._texture) {
  22862. if (!scene.useDelayedTextureLoading) {
  22863. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  22864. if (deleteBuffer) {
  22865. delete _this._buffer;
  22866. }
  22867. }
  22868. else {
  22869. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22870. _this._delayedOnLoad = load;
  22871. _this._delayedOnError = onError;
  22872. }
  22873. }
  22874. else {
  22875. if (_this._texture.isReady) {
  22876. BABYLON.Tools.SetImmediate(function () { return load(); });
  22877. }
  22878. else {
  22879. _this._texture.onLoadedObservable.add(load);
  22880. }
  22881. }
  22882. return _this;
  22883. }
  22884. Object.defineProperty(Texture.prototype, "noMipmap", {
  22885. get: function () {
  22886. return this._noMipmap;
  22887. },
  22888. enumerable: true,
  22889. configurable: true
  22890. });
  22891. Object.defineProperty(Texture.prototype, "isBlocking", {
  22892. get: function () {
  22893. return this._isBlocking;
  22894. },
  22895. set: function (value) {
  22896. this._isBlocking = value;
  22897. },
  22898. enumerable: true,
  22899. configurable: true
  22900. });
  22901. Object.defineProperty(Texture.prototype, "samplingMode", {
  22902. get: function () {
  22903. return this._samplingMode;
  22904. },
  22905. enumerable: true,
  22906. configurable: true
  22907. });
  22908. Texture.prototype.updateURL = function (url) {
  22909. this.url = url;
  22910. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22911. this.delayLoad();
  22912. };
  22913. Texture.prototype.delayLoad = function () {
  22914. var _this = this;
  22915. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22916. return;
  22917. }
  22918. var scene = this.getScene();
  22919. if (!scene) {
  22920. return;
  22921. }
  22922. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22923. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  22924. if (!this._texture) {
  22925. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  22926. if (this._deleteBuffer) {
  22927. delete this._buffer;
  22928. }
  22929. }
  22930. else {
  22931. if (this._texture.isReady) {
  22932. BABYLON.Tools.SetImmediate(function () {
  22933. if (!_this._delayedOnLoad) {
  22934. return;
  22935. }
  22936. _this._delayedOnLoad();
  22937. });
  22938. }
  22939. else {
  22940. if (this._delayedOnLoad) {
  22941. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  22942. }
  22943. }
  22944. }
  22945. };
  22946. Texture.prototype.updateSamplingMode = function (samplingMode) {
  22947. if (!this._texture) {
  22948. return;
  22949. }
  22950. var scene = this.getScene();
  22951. if (!scene) {
  22952. return;
  22953. }
  22954. this._samplingMode = samplingMode;
  22955. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  22956. };
  22957. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  22958. x *= this.uScale;
  22959. y *= this.vScale;
  22960. x -= 0.5 * this.uScale;
  22961. y -= 0.5 * this.vScale;
  22962. z -= 0.5;
  22963. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  22964. t.x += 0.5 * this.uScale + this.uOffset;
  22965. t.y += 0.5 * this.vScale + this.vOffset;
  22966. t.z += 0.5;
  22967. };
  22968. Texture.prototype.getTextureMatrix = function () {
  22969. var _this = this;
  22970. if (this.uOffset === this._cachedUOffset &&
  22971. this.vOffset === this._cachedVOffset &&
  22972. this.uScale === this._cachedUScale &&
  22973. this.vScale === this._cachedVScale &&
  22974. this.uAng === this._cachedUAng &&
  22975. this.vAng === this._cachedVAng &&
  22976. this.wAng === this._cachedWAng) {
  22977. return this._cachedTextureMatrix;
  22978. }
  22979. this._cachedUOffset = this.uOffset;
  22980. this._cachedVOffset = this.vOffset;
  22981. this._cachedUScale = this.uScale;
  22982. this._cachedVScale = this.vScale;
  22983. this._cachedUAng = this.uAng;
  22984. this._cachedVAng = this.vAng;
  22985. this._cachedWAng = this.wAng;
  22986. if (!this._cachedTextureMatrix) {
  22987. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22988. this._rowGenerationMatrix = new BABYLON.Matrix();
  22989. this._t0 = BABYLON.Vector3.Zero();
  22990. this._t1 = BABYLON.Vector3.Zero();
  22991. this._t2 = BABYLON.Vector3.Zero();
  22992. }
  22993. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  22994. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  22995. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  22996. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  22997. this._t1.subtractInPlace(this._t0);
  22998. this._t2.subtractInPlace(this._t0);
  22999. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23000. this._cachedTextureMatrix.m[0] = this._t1.x;
  23001. this._cachedTextureMatrix.m[1] = this._t1.y;
  23002. this._cachedTextureMatrix.m[2] = this._t1.z;
  23003. this._cachedTextureMatrix.m[4] = this._t2.x;
  23004. this._cachedTextureMatrix.m[5] = this._t2.y;
  23005. this._cachedTextureMatrix.m[6] = this._t2.z;
  23006. this._cachedTextureMatrix.m[8] = this._t0.x;
  23007. this._cachedTextureMatrix.m[9] = this._t0.y;
  23008. this._cachedTextureMatrix.m[10] = this._t0.z;
  23009. var scene = this.getScene();
  23010. if (!scene) {
  23011. return this._cachedTextureMatrix;
  23012. }
  23013. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  23014. return mat.hasTexture(_this);
  23015. });
  23016. return this._cachedTextureMatrix;
  23017. };
  23018. Texture.prototype.getReflectionTextureMatrix = function () {
  23019. var _this = this;
  23020. var scene = this.getScene();
  23021. if (!scene) {
  23022. return this._cachedTextureMatrix;
  23023. }
  23024. if (this.uOffset === this._cachedUOffset &&
  23025. this.vOffset === this._cachedVOffset &&
  23026. this.uScale === this._cachedUScale &&
  23027. this.vScale === this._cachedVScale &&
  23028. this.coordinatesMode === this._cachedCoordinatesMode) {
  23029. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  23030. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  23031. return this._cachedTextureMatrix;
  23032. }
  23033. }
  23034. else {
  23035. return this._cachedTextureMatrix;
  23036. }
  23037. }
  23038. if (!this._cachedTextureMatrix) {
  23039. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  23040. }
  23041. if (!this._projectionModeMatrix) {
  23042. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  23043. }
  23044. this._cachedUOffset = this.uOffset;
  23045. this._cachedVOffset = this.vOffset;
  23046. this._cachedUScale = this.uScale;
  23047. this._cachedVScale = this.vScale;
  23048. this._cachedCoordinatesMode = this.coordinatesMode;
  23049. switch (this.coordinatesMode) {
  23050. case Texture.PLANAR_MODE:
  23051. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23052. this._cachedTextureMatrix[0] = this.uScale;
  23053. this._cachedTextureMatrix[5] = this.vScale;
  23054. this._cachedTextureMatrix[12] = this.uOffset;
  23055. this._cachedTextureMatrix[13] = this.vOffset;
  23056. break;
  23057. case Texture.PROJECTION_MODE:
  23058. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  23059. this._projectionModeMatrix.m[0] = 0.5;
  23060. this._projectionModeMatrix.m[5] = -0.5;
  23061. this._projectionModeMatrix.m[10] = 0.0;
  23062. this._projectionModeMatrix.m[12] = 0.5;
  23063. this._projectionModeMatrix.m[13] = 0.5;
  23064. this._projectionModeMatrix.m[14] = 1.0;
  23065. this._projectionModeMatrix.m[15] = 1.0;
  23066. var projectionMatrix = scene.getProjectionMatrix();
  23067. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  23068. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  23069. break;
  23070. default:
  23071. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23072. break;
  23073. }
  23074. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  23075. return (mat.getActiveTextures().indexOf(_this) !== -1);
  23076. });
  23077. return this._cachedTextureMatrix;
  23078. };
  23079. Texture.prototype.clone = function () {
  23080. var _this = this;
  23081. return BABYLON.SerializationHelper.Clone(function () {
  23082. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  23083. }, this);
  23084. };
  23085. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  23086. get: function () {
  23087. if (!this._onLoadObservable) {
  23088. this._onLoadObservable = new BABYLON.Observable();
  23089. }
  23090. return this._onLoadObservable;
  23091. },
  23092. enumerable: true,
  23093. configurable: true
  23094. });
  23095. Texture.prototype.serialize = function () {
  23096. var serializationObject = _super.prototype.serialize.call(this);
  23097. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  23098. serializationObject.base64String = this._buffer;
  23099. serializationObject.name = serializationObject.name.replace("data:", "");
  23100. }
  23101. return serializationObject;
  23102. };
  23103. Texture.prototype.getClassName = function () {
  23104. return "Texture";
  23105. };
  23106. Texture.prototype.dispose = function () {
  23107. _super.prototype.dispose.call(this);
  23108. if (this.onLoadObservable) {
  23109. this.onLoadObservable.clear();
  23110. this._onLoadObservable = null;
  23111. }
  23112. this._delayedOnLoad = null;
  23113. this._delayedOnError = null;
  23114. };
  23115. // Statics
  23116. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  23117. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23118. if (onLoad === void 0) { onLoad = null; }
  23119. if (onError === void 0) { onError = null; }
  23120. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  23121. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  23122. };
  23123. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  23124. if (parsedTexture.customType) {
  23125. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  23126. // Update Sampling Mode
  23127. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  23128. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  23129. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  23130. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  23131. }
  23132. }
  23133. return parsedCustomTexture;
  23134. }
  23135. if (parsedTexture.isCube) {
  23136. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  23137. }
  23138. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  23139. return null;
  23140. }
  23141. var texture = BABYLON.SerializationHelper.Parse(function () {
  23142. var generateMipMaps = true;
  23143. if (parsedTexture.noMipmap) {
  23144. generateMipMaps = false;
  23145. }
  23146. if (parsedTexture.mirrorPlane) {
  23147. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  23148. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  23149. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  23150. return mirrorTexture;
  23151. }
  23152. else if (parsedTexture.isRenderTarget) {
  23153. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  23154. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  23155. return renderTargetTexture;
  23156. }
  23157. else {
  23158. var texture;
  23159. if (parsedTexture.base64String) {
  23160. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  23161. }
  23162. else {
  23163. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  23164. }
  23165. return texture;
  23166. }
  23167. }, parsedTexture, scene);
  23168. // Update Sampling Mode
  23169. if (parsedTexture.samplingMode) {
  23170. var sampling = parsedTexture.samplingMode;
  23171. if (texture._samplingMode !== sampling) {
  23172. texture.updateSamplingMode(sampling);
  23173. }
  23174. }
  23175. // Animations
  23176. if (parsedTexture.animations) {
  23177. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  23178. var parsedAnimation = parsedTexture.animations[animationIndex];
  23179. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23180. }
  23181. }
  23182. return texture;
  23183. };
  23184. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  23185. if (deleteBuffer === void 0) { deleteBuffer = false; }
  23186. if (noMipmap === void 0) { noMipmap = false; }
  23187. if (invertY === void 0) { invertY = true; }
  23188. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23189. if (onLoad === void 0) { onLoad = null; }
  23190. if (onError === void 0) { onError = null; }
  23191. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  23192. if (name.substr(0, 5) !== "data:") {
  23193. name = "data:" + name;
  23194. }
  23195. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  23196. };
  23197. // Constants
  23198. Texture.NEAREST_SAMPLINGMODE = 1;
  23199. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  23200. Texture.BILINEAR_SAMPLINGMODE = 2;
  23201. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  23202. Texture.TRILINEAR_SAMPLINGMODE = 3;
  23203. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  23204. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  23205. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  23206. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  23207. Texture.NEAREST_LINEAR = 7;
  23208. Texture.NEAREST_NEAREST = 8;
  23209. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  23210. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  23211. Texture.LINEAR_LINEAR = 11;
  23212. Texture.LINEAR_NEAREST = 12;
  23213. Texture.EXPLICIT_MODE = 0;
  23214. Texture.SPHERICAL_MODE = 1;
  23215. Texture.PLANAR_MODE = 2;
  23216. Texture.CUBIC_MODE = 3;
  23217. Texture.PROJECTION_MODE = 4;
  23218. Texture.SKYBOX_MODE = 5;
  23219. Texture.INVCUBIC_MODE = 6;
  23220. Texture.EQUIRECTANGULAR_MODE = 7;
  23221. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  23222. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  23223. Texture.CLAMP_ADDRESSMODE = 0;
  23224. Texture.WRAP_ADDRESSMODE = 1;
  23225. Texture.MIRROR_ADDRESSMODE = 2;
  23226. __decorate([
  23227. BABYLON.serialize()
  23228. ], Texture.prototype, "url", void 0);
  23229. __decorate([
  23230. BABYLON.serialize()
  23231. ], Texture.prototype, "uOffset", void 0);
  23232. __decorate([
  23233. BABYLON.serialize()
  23234. ], Texture.prototype, "vOffset", void 0);
  23235. __decorate([
  23236. BABYLON.serialize()
  23237. ], Texture.prototype, "uScale", void 0);
  23238. __decorate([
  23239. BABYLON.serialize()
  23240. ], Texture.prototype, "vScale", void 0);
  23241. __decorate([
  23242. BABYLON.serialize()
  23243. ], Texture.prototype, "uAng", void 0);
  23244. __decorate([
  23245. BABYLON.serialize()
  23246. ], Texture.prototype, "vAng", void 0);
  23247. __decorate([
  23248. BABYLON.serialize()
  23249. ], Texture.prototype, "wAng", void 0);
  23250. __decorate([
  23251. BABYLON.serialize()
  23252. ], Texture.prototype, "isBlocking", null);
  23253. return Texture;
  23254. }(BABYLON.BaseTexture));
  23255. BABYLON.Texture = Texture;
  23256. })(BABYLON || (BABYLON = {}));
  23257. //# sourceMappingURL=babylon.texture.js.map
  23258. var BABYLON;
  23259. (function (BABYLON) {
  23260. var _InstancesBatch = /** @class */ (function () {
  23261. function _InstancesBatch() {
  23262. this.mustReturn = false;
  23263. this.visibleInstances = new Array();
  23264. this.renderSelf = new Array();
  23265. }
  23266. return _InstancesBatch;
  23267. }());
  23268. BABYLON._InstancesBatch = _InstancesBatch;
  23269. var Mesh = /** @class */ (function (_super) {
  23270. __extends(Mesh, _super);
  23271. /**
  23272. * @constructor
  23273. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  23274. * @param {Scene} scene The scene to add this mesh to.
  23275. * @param {Node} parent The parent of this mesh, if it has one
  23276. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  23277. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  23278. * When false, achieved by calling a clone(), also passing False.
  23279. * This will make creation of children, recursive.
  23280. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  23281. */
  23282. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  23283. if (scene === void 0) { scene = null; }
  23284. if (parent === void 0) { parent = null; }
  23285. if (source === void 0) { source = null; }
  23286. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  23287. var _this = _super.call(this, name, scene) || this;
  23288. // Events
  23289. /**
  23290. * An event triggered before rendering the mesh
  23291. * @type {BABYLON.Observable}
  23292. */
  23293. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23294. /**
  23295. * An event triggered after rendering the mesh
  23296. * @type {BABYLON.Observable}
  23297. */
  23298. _this.onAfterRenderObservable = new BABYLON.Observable();
  23299. /**
  23300. * An event triggered before drawing the mesh
  23301. * @type {BABYLON.Observable}
  23302. */
  23303. _this.onBeforeDrawObservable = new BABYLON.Observable();
  23304. // Members
  23305. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23306. _this.instances = new Array();
  23307. _this._LODLevels = new Array();
  23308. _this._visibleInstances = {};
  23309. _this._renderIdForInstances = new Array();
  23310. _this._batchCache = new _InstancesBatch();
  23311. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  23312. // Use by builder only to know what orientation were the mesh build in.
  23313. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  23314. _this.overrideMaterialSideOrientation = null;
  23315. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  23316. // Will be used to save a source mesh reference, If any
  23317. _this._source = null;
  23318. scene = _this.getScene();
  23319. if (source) {
  23320. // Source mesh
  23321. _this._source = source;
  23322. // Geometry
  23323. if (source._geometry) {
  23324. source._geometry.applyToMesh(_this);
  23325. }
  23326. // Deep copy
  23327. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source"], ["_poseMatrix", "_source"]);
  23328. // Tags
  23329. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  23330. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  23331. }
  23332. _this.metadata = source.metadata;
  23333. // Parent
  23334. _this.parent = source.parent;
  23335. // Pivot
  23336. _this.setPivotMatrix(source.getPivotMatrix());
  23337. _this.id = name + "." + source.id;
  23338. // Material
  23339. _this.material = source.material;
  23340. var index;
  23341. if (!doNotCloneChildren) {
  23342. // Children
  23343. var directDescendants = source.getDescendants(true);
  23344. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  23345. var child = directDescendants[index_1];
  23346. if (child.clone) {
  23347. child.clone(name + "." + child.name, _this);
  23348. }
  23349. }
  23350. }
  23351. // Physics clone
  23352. var physicsEngine = _this.getScene().getPhysicsEngine();
  23353. if (clonePhysicsImpostor && physicsEngine) {
  23354. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  23355. if (impostor) {
  23356. _this.physicsImpostor = impostor.clone(_this);
  23357. }
  23358. }
  23359. // Particles
  23360. for (index = 0; index < scene.particleSystems.length; index++) {
  23361. var system = scene.particleSystems[index];
  23362. if (system.emitter === source) {
  23363. system.clone(system.name, _this);
  23364. }
  23365. }
  23366. _this.computeWorldMatrix(true);
  23367. }
  23368. // Parent
  23369. if (parent !== null) {
  23370. _this.parent = parent;
  23371. }
  23372. return _this;
  23373. }
  23374. Object.defineProperty(Mesh, "FRONTSIDE", {
  23375. /**
  23376. * Mesh side orientation : usually the external or front surface
  23377. */
  23378. get: function () {
  23379. return Mesh._FRONTSIDE;
  23380. },
  23381. enumerable: true,
  23382. configurable: true
  23383. });
  23384. Object.defineProperty(Mesh, "BACKSIDE", {
  23385. /**
  23386. * Mesh side orientation : usually the internal or back surface
  23387. */
  23388. get: function () {
  23389. return Mesh._BACKSIDE;
  23390. },
  23391. enumerable: true,
  23392. configurable: true
  23393. });
  23394. Object.defineProperty(Mesh, "DOUBLESIDE", {
  23395. /**
  23396. * Mesh side orientation : both internal and external or front and back surfaces
  23397. */
  23398. get: function () {
  23399. return Mesh._DOUBLESIDE;
  23400. },
  23401. enumerable: true,
  23402. configurable: true
  23403. });
  23404. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  23405. /**
  23406. * Mesh side orientation : by default, `FRONTSIDE`
  23407. */
  23408. get: function () {
  23409. return Mesh._DEFAULTSIDE;
  23410. },
  23411. enumerable: true,
  23412. configurable: true
  23413. });
  23414. Object.defineProperty(Mesh, "NO_CAP", {
  23415. /**
  23416. * Mesh cap setting : no cap
  23417. */
  23418. get: function () {
  23419. return Mesh._NO_CAP;
  23420. },
  23421. enumerable: true,
  23422. configurable: true
  23423. });
  23424. Object.defineProperty(Mesh, "CAP_START", {
  23425. /**
  23426. * Mesh cap setting : one cap at the beginning of the mesh
  23427. */
  23428. get: function () {
  23429. return Mesh._CAP_START;
  23430. },
  23431. enumerable: true,
  23432. configurable: true
  23433. });
  23434. Object.defineProperty(Mesh, "CAP_END", {
  23435. /**
  23436. * Mesh cap setting : one cap at the end of the mesh
  23437. */
  23438. get: function () {
  23439. return Mesh._CAP_END;
  23440. },
  23441. enumerable: true,
  23442. configurable: true
  23443. });
  23444. Object.defineProperty(Mesh, "CAP_ALL", {
  23445. /**
  23446. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  23447. */
  23448. get: function () {
  23449. return Mesh._CAP_ALL;
  23450. },
  23451. enumerable: true,
  23452. configurable: true
  23453. });
  23454. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  23455. set: function (callback) {
  23456. if (this._onBeforeDrawObserver) {
  23457. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  23458. }
  23459. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  23460. },
  23461. enumerable: true,
  23462. configurable: true
  23463. });
  23464. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  23465. get: function () {
  23466. return this._morphTargetManager;
  23467. },
  23468. set: function (value) {
  23469. if (this._morphTargetManager === value) {
  23470. return;
  23471. }
  23472. this._morphTargetManager = value;
  23473. this._syncGeometryWithMorphTargetManager();
  23474. },
  23475. enumerable: true,
  23476. configurable: true
  23477. });
  23478. Object.defineProperty(Mesh.prototype, "source", {
  23479. get: function () {
  23480. return this._source;
  23481. },
  23482. enumerable: true,
  23483. configurable: true
  23484. });
  23485. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  23486. get: function () {
  23487. return this._unIndexed;
  23488. },
  23489. set: function (value) {
  23490. if (this._unIndexed !== value) {
  23491. this._unIndexed = value;
  23492. this._markSubMeshesAsAttributesDirty();
  23493. }
  23494. },
  23495. enumerable: true,
  23496. configurable: true
  23497. });
  23498. // Methods
  23499. /**
  23500. * Returns the string "Mesh".
  23501. */
  23502. Mesh.prototype.getClassName = function () {
  23503. return "Mesh";
  23504. };
  23505. /**
  23506. * Returns a string.
  23507. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  23508. */
  23509. Mesh.prototype.toString = function (fullDetails) {
  23510. var ret = _super.prototype.toString.call(this, fullDetails);
  23511. ret += ", n vertices: " + this.getTotalVertices();
  23512. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  23513. if (this.animations) {
  23514. for (var i = 0; i < this.animations.length; i++) {
  23515. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  23516. }
  23517. }
  23518. if (fullDetails) {
  23519. if (this._geometry) {
  23520. var ib = this.getIndices();
  23521. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23522. if (vb && ib) {
  23523. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  23524. }
  23525. }
  23526. else {
  23527. ret += ", flat shading: UNKNOWN";
  23528. }
  23529. }
  23530. return ret;
  23531. };
  23532. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  23533. /**
  23534. * True if the mesh has some Levels Of Details (LOD).
  23535. * Returns a boolean.
  23536. */
  23537. get: function () {
  23538. return this._LODLevels.length > 0;
  23539. },
  23540. enumerable: true,
  23541. configurable: true
  23542. });
  23543. Mesh.prototype._sortLODLevels = function () {
  23544. this._LODLevels.sort(function (a, b) {
  23545. if (a.distance < b.distance) {
  23546. return 1;
  23547. }
  23548. if (a.distance > b.distance) {
  23549. return -1;
  23550. }
  23551. return 0;
  23552. });
  23553. };
  23554. /**
  23555. * Add a mesh as LOD level triggered at the given distance.
  23556. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23557. * @param {number} distance The distance from the center of the object to show this level
  23558. * @param {Mesh} mesh The mesh to be added as LOD level
  23559. * @return {Mesh} This mesh (for chaining)
  23560. */
  23561. Mesh.prototype.addLODLevel = function (distance, mesh) {
  23562. if (mesh && mesh._masterMesh) {
  23563. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  23564. return this;
  23565. }
  23566. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  23567. this._LODLevels.push(level);
  23568. if (mesh) {
  23569. mesh._masterMesh = this;
  23570. }
  23571. this._sortLODLevels();
  23572. return this;
  23573. };
  23574. /**
  23575. * Returns the LOD level mesh at the passed distance or null if not found.
  23576. * It is related to the method `addLODLevel(distance, mesh)`.
  23577. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23578. * Returns an object Mesh or `null`.
  23579. */
  23580. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  23581. for (var index = 0; index < this._LODLevels.length; index++) {
  23582. var level = this._LODLevels[index];
  23583. if (level.distance === distance) {
  23584. return level.mesh;
  23585. }
  23586. }
  23587. return null;
  23588. };
  23589. /**
  23590. * Remove a mesh from the LOD array
  23591. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23592. * @param {Mesh} mesh The mesh to be removed.
  23593. * @return {Mesh} This mesh (for chaining)
  23594. */
  23595. Mesh.prototype.removeLODLevel = function (mesh) {
  23596. for (var index = 0; index < this._LODLevels.length; index++) {
  23597. if (this._LODLevels[index].mesh === mesh) {
  23598. this._LODLevels.splice(index, 1);
  23599. if (mesh) {
  23600. mesh._masterMesh = null;
  23601. }
  23602. }
  23603. }
  23604. this._sortLODLevels();
  23605. return this;
  23606. };
  23607. /**
  23608. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  23609. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23610. */
  23611. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  23612. if (!this._LODLevels || this._LODLevels.length === 0) {
  23613. return this;
  23614. }
  23615. var bSphere;
  23616. if (boundingSphere) {
  23617. bSphere = boundingSphere;
  23618. }
  23619. else {
  23620. var boundingInfo = this.getBoundingInfo();
  23621. bSphere = boundingInfo.boundingSphere;
  23622. }
  23623. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  23624. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  23625. if (this.onLODLevelSelection) {
  23626. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  23627. }
  23628. return this;
  23629. }
  23630. for (var index = 0; index < this._LODLevels.length; index++) {
  23631. var level = this._LODLevels[index];
  23632. if (level.distance < distanceToCamera) {
  23633. if (level.mesh) {
  23634. level.mesh._preActivate();
  23635. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  23636. }
  23637. if (this.onLODLevelSelection) {
  23638. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  23639. }
  23640. return level.mesh;
  23641. }
  23642. }
  23643. if (this.onLODLevelSelection) {
  23644. this.onLODLevelSelection(distanceToCamera, this, this);
  23645. }
  23646. return this;
  23647. };
  23648. Object.defineProperty(Mesh.prototype, "geometry", {
  23649. /**
  23650. * Returns the mesh internal Geometry object.
  23651. */
  23652. get: function () {
  23653. return this._geometry;
  23654. },
  23655. enumerable: true,
  23656. configurable: true
  23657. });
  23658. /**
  23659. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  23660. */
  23661. Mesh.prototype.getTotalVertices = function () {
  23662. if (!this._geometry) {
  23663. return 0;
  23664. }
  23665. return this._geometry.getTotalVertices();
  23666. };
  23667. /**
  23668. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  23669. * 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.
  23670. * You can force the copy with forceCopy === true
  23671. * Returns null if the mesh has no geometry or no vertex buffer.
  23672. * Possible `kind` values :
  23673. * - BABYLON.VertexBuffer.PositionKind
  23674. * - BABYLON.VertexBuffer.UVKind
  23675. * - BABYLON.VertexBuffer.UV2Kind
  23676. * - BABYLON.VertexBuffer.UV3Kind
  23677. * - BABYLON.VertexBuffer.UV4Kind
  23678. * - BABYLON.VertexBuffer.UV5Kind
  23679. * - BABYLON.VertexBuffer.UV6Kind
  23680. * - BABYLON.VertexBuffer.ColorKind
  23681. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23682. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23683. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23684. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23685. */
  23686. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  23687. if (!this._geometry) {
  23688. return null;
  23689. }
  23690. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  23691. };
  23692. /**
  23693. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  23694. * Returns `null` if the mesh has no geometry.
  23695. * Possible `kind` values :
  23696. * - BABYLON.VertexBuffer.PositionKind
  23697. * - BABYLON.VertexBuffer.UVKind
  23698. * - BABYLON.VertexBuffer.UV2Kind
  23699. * - BABYLON.VertexBuffer.UV3Kind
  23700. * - BABYLON.VertexBuffer.UV4Kind
  23701. * - BABYLON.VertexBuffer.UV5Kind
  23702. * - BABYLON.VertexBuffer.UV6Kind
  23703. * - BABYLON.VertexBuffer.ColorKind
  23704. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23705. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23706. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23707. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23708. */
  23709. Mesh.prototype.getVertexBuffer = function (kind) {
  23710. if (!this._geometry) {
  23711. return null;
  23712. }
  23713. return this._geometry.getVertexBuffer(kind);
  23714. };
  23715. /**
  23716. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  23717. * Possible `kind` values :
  23718. * - BABYLON.VertexBuffer.PositionKind
  23719. * - BABYLON.VertexBuffer.UVKind
  23720. * - BABYLON.VertexBuffer.UV2Kind
  23721. * - BABYLON.VertexBuffer.UV3Kind
  23722. * - BABYLON.VertexBuffer.UV4Kind
  23723. * - BABYLON.VertexBuffer.UV5Kind
  23724. * - BABYLON.VertexBuffer.UV6Kind
  23725. * - BABYLON.VertexBuffer.ColorKind
  23726. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23727. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23728. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23729. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23730. */
  23731. Mesh.prototype.isVerticesDataPresent = function (kind) {
  23732. if (!this._geometry) {
  23733. if (this._delayInfo) {
  23734. return this._delayInfo.indexOf(kind) !== -1;
  23735. }
  23736. return false;
  23737. }
  23738. return this._geometry.isVerticesDataPresent(kind);
  23739. };
  23740. /**
  23741. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  23742. * Possible `kind` values :
  23743. * - BABYLON.VertexBuffer.PositionKind
  23744. * - BABYLON.VertexBuffer.UVKind
  23745. * - BABYLON.VertexBuffer.UV2Kind
  23746. * - BABYLON.VertexBuffer.UV3Kind
  23747. * - BABYLON.VertexBuffer.UV4Kind
  23748. * - BABYLON.VertexBuffer.UV5Kind
  23749. * - BABYLON.VertexBuffer.UV6Kind
  23750. * - BABYLON.VertexBuffer.ColorKind
  23751. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23752. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23753. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23754. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23755. */
  23756. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  23757. if (!this._geometry) {
  23758. if (this._delayInfo) {
  23759. return this._delayInfo.indexOf(kind) !== -1;
  23760. }
  23761. return false;
  23762. }
  23763. return this._geometry.isVertexBufferUpdatable(kind);
  23764. };
  23765. /**
  23766. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  23767. * Possible `kind` values :
  23768. * - BABYLON.VertexBuffer.PositionKind
  23769. * - BABYLON.VertexBuffer.UVKind
  23770. * - BABYLON.VertexBuffer.UV2Kind
  23771. * - BABYLON.VertexBuffer.UV3Kind
  23772. * - BABYLON.VertexBuffer.UV4Kind
  23773. * - BABYLON.VertexBuffer.UV5Kind
  23774. * - BABYLON.VertexBuffer.UV6Kind
  23775. * - BABYLON.VertexBuffer.ColorKind
  23776. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23777. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23778. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23779. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23780. */
  23781. Mesh.prototype.getVerticesDataKinds = function () {
  23782. if (!this._geometry) {
  23783. var result = new Array();
  23784. if (this._delayInfo) {
  23785. this._delayInfo.forEach(function (kind, index, array) {
  23786. result.push(kind);
  23787. });
  23788. }
  23789. return result;
  23790. }
  23791. return this._geometry.getVerticesDataKinds();
  23792. };
  23793. /**
  23794. * Returns a positive integer : the total number of indices in this mesh geometry.
  23795. * Returns zero if the mesh has no geometry.
  23796. */
  23797. Mesh.prototype.getTotalIndices = function () {
  23798. if (!this._geometry) {
  23799. return 0;
  23800. }
  23801. return this._geometry.getTotalIndices();
  23802. };
  23803. /**
  23804. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  23805. * 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.
  23806. * Returns an empty array if the mesh has no geometry.
  23807. */
  23808. Mesh.prototype.getIndices = function (copyWhenShared) {
  23809. if (!this._geometry) {
  23810. return [];
  23811. }
  23812. return this._geometry.getIndices(copyWhenShared);
  23813. };
  23814. Object.defineProperty(Mesh.prototype, "isBlocked", {
  23815. get: function () {
  23816. return this._masterMesh !== null && this._masterMesh !== undefined;
  23817. },
  23818. enumerable: true,
  23819. configurable: true
  23820. });
  23821. /**
  23822. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  23823. */
  23824. Mesh.prototype.isReady = function () {
  23825. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23826. return false;
  23827. }
  23828. return _super.prototype.isReady.call(this);
  23829. };
  23830. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  23831. /**
  23832. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  23833. * This property is pertinent only for updatable parametric shapes.
  23834. */
  23835. get: function () {
  23836. return this._areNormalsFrozen;
  23837. },
  23838. enumerable: true,
  23839. configurable: true
  23840. });
  23841. /**
  23842. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  23843. * It has no effect at all on other shapes.
  23844. * It prevents the mesh normals from being recomputed on next `positions` array update.
  23845. * Returns the Mesh.
  23846. */
  23847. Mesh.prototype.freezeNormals = function () {
  23848. this._areNormalsFrozen = true;
  23849. return this;
  23850. };
  23851. /**
  23852. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  23853. * It has no effect at all on other shapes.
  23854. * It reactivates the mesh normals computation if it was previously frozen.
  23855. * Returns the Mesh.
  23856. */
  23857. Mesh.prototype.unfreezeNormals = function () {
  23858. this._areNormalsFrozen = false;
  23859. return this;
  23860. };
  23861. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  23862. /**
  23863. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  23864. */
  23865. set: function (count) {
  23866. this._overridenInstanceCount = count;
  23867. },
  23868. enumerable: true,
  23869. configurable: true
  23870. });
  23871. // Methods
  23872. Mesh.prototype._preActivate = function () {
  23873. var sceneRenderId = this.getScene().getRenderId();
  23874. if (this._preActivateId === sceneRenderId) {
  23875. return this;
  23876. }
  23877. this._preActivateId = sceneRenderId;
  23878. this._visibleInstances = null;
  23879. return this;
  23880. };
  23881. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  23882. if (this._visibleInstances) {
  23883. this._visibleInstances.intermediateDefaultRenderId = renderId;
  23884. }
  23885. return this;
  23886. };
  23887. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  23888. if (!this._visibleInstances) {
  23889. this._visibleInstances = {};
  23890. this._visibleInstances.defaultRenderId = renderId;
  23891. this._visibleInstances.selfDefaultRenderId = this._renderId;
  23892. }
  23893. if (!this._visibleInstances[renderId]) {
  23894. this._visibleInstances[renderId] = new Array();
  23895. }
  23896. this._visibleInstances[renderId].push(instance);
  23897. return this;
  23898. };
  23899. /**
  23900. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  23901. * This means the mesh underlying bounding box and sphere are recomputed.
  23902. * Returns the Mesh.
  23903. */
  23904. Mesh.prototype.refreshBoundingInfo = function () {
  23905. return this._refreshBoundingInfo(false);
  23906. };
  23907. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  23908. if (this._boundingInfo && this._boundingInfo.isLocked) {
  23909. return this;
  23910. }
  23911. var data = this._getPositionData(applySkeleton);
  23912. if (data) {
  23913. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  23914. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23915. }
  23916. if (this.subMeshes) {
  23917. for (var index = 0; index < this.subMeshes.length; index++) {
  23918. this.subMeshes[index].refreshBoundingInfo();
  23919. }
  23920. }
  23921. this._updateBoundingInfo();
  23922. return this;
  23923. };
  23924. Mesh.prototype._getPositionData = function (applySkeleton) {
  23925. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23926. if (data && applySkeleton && this.skeleton) {
  23927. data = data.slice();
  23928. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  23929. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  23930. if (matricesWeightsData && matricesIndicesData) {
  23931. var needExtras = this.numBoneInfluencers > 4;
  23932. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  23933. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  23934. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  23935. var tempVector = BABYLON.Tmp.Vector3[0];
  23936. var finalMatrix = BABYLON.Tmp.Matrix[0];
  23937. var tempMatrix = BABYLON.Tmp.Matrix[1];
  23938. var matWeightIdx = 0;
  23939. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  23940. finalMatrix.reset();
  23941. var inf;
  23942. var weight;
  23943. for (inf = 0; inf < 4; inf++) {
  23944. weight = matricesWeightsData[matWeightIdx + inf];
  23945. if (weight <= 0)
  23946. break;
  23947. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23948. finalMatrix.addToSelf(tempMatrix);
  23949. }
  23950. if (needExtras) {
  23951. for (inf = 0; inf < 4; inf++) {
  23952. weight = matricesWeightsExtraData[matWeightIdx + inf];
  23953. if (weight <= 0)
  23954. break;
  23955. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23956. finalMatrix.addToSelf(tempMatrix);
  23957. }
  23958. }
  23959. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  23960. tempVector.toArray(data, index);
  23961. }
  23962. }
  23963. }
  23964. return data;
  23965. };
  23966. Mesh.prototype._createGlobalSubMesh = function (force) {
  23967. var totalVertices = this.getTotalVertices();
  23968. if (!totalVertices || !this.getIndices()) {
  23969. return null;
  23970. }
  23971. // Check if we need to recreate the submeshes
  23972. if (this.subMeshes && this.subMeshes.length > 0) {
  23973. var ib = this.getIndices();
  23974. if (!ib) {
  23975. return null;
  23976. }
  23977. var totalIndices = ib.length;
  23978. var needToRecreate = false;
  23979. if (force) {
  23980. needToRecreate = true;
  23981. }
  23982. else {
  23983. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  23984. var submesh = _a[_i];
  23985. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  23986. needToRecreate = true;
  23987. break;
  23988. }
  23989. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  23990. needToRecreate = true;
  23991. break;
  23992. }
  23993. }
  23994. }
  23995. if (!needToRecreate) {
  23996. return this.subMeshes[0];
  23997. }
  23998. }
  23999. this.releaseSubMeshes();
  24000. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  24001. };
  24002. Mesh.prototype.subdivide = function (count) {
  24003. if (count < 1) {
  24004. return;
  24005. }
  24006. var totalIndices = this.getTotalIndices();
  24007. var subdivisionSize = (totalIndices / count) | 0;
  24008. var offset = 0;
  24009. // Ensure that subdivisionSize is a multiple of 3
  24010. while (subdivisionSize % 3 !== 0) {
  24011. subdivisionSize++;
  24012. }
  24013. this.releaseSubMeshes();
  24014. for (var index = 0; index < count; index++) {
  24015. if (offset >= totalIndices) {
  24016. break;
  24017. }
  24018. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  24019. offset += subdivisionSize;
  24020. }
  24021. this.synchronizeInstances();
  24022. };
  24023. /**
  24024. * Sets the vertex data of the mesh geometry for the requested `kind`.
  24025. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  24026. * The `data` are either a numeric array either a Float32Array.
  24027. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  24028. * 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).
  24029. * Note that a new underlying VertexBuffer object is created each call.
  24030. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  24031. *
  24032. * Possible `kind` values :
  24033. * - BABYLON.VertexBuffer.PositionKind
  24034. * - BABYLON.VertexBuffer.UVKind
  24035. * - BABYLON.VertexBuffer.UV2Kind
  24036. * - BABYLON.VertexBuffer.UV3Kind
  24037. * - BABYLON.VertexBuffer.UV4Kind
  24038. * - BABYLON.VertexBuffer.UV5Kind
  24039. * - BABYLON.VertexBuffer.UV6Kind
  24040. * - BABYLON.VertexBuffer.ColorKind
  24041. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24042. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24043. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24044. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24045. *
  24046. * Returns the Mesh.
  24047. */
  24048. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  24049. if (updatable === void 0) { updatable = false; }
  24050. if (!this._geometry) {
  24051. var vertexData = new BABYLON.VertexData();
  24052. vertexData.set(data, kind);
  24053. var scene = this.getScene();
  24054. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  24055. }
  24056. else {
  24057. this._geometry.setVerticesData(kind, data, updatable, stride);
  24058. }
  24059. return this;
  24060. };
  24061. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  24062. if (updatable === void 0) { updatable = true; }
  24063. var vb = this.getVertexBuffer(kind);
  24064. if (!vb || vb.isUpdatable() === updatable) {
  24065. return;
  24066. }
  24067. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  24068. };
  24069. /**
  24070. * Sets the mesh VertexBuffer.
  24071. * Returns the Mesh.
  24072. */
  24073. Mesh.prototype.setVerticesBuffer = function (buffer) {
  24074. if (!this._geometry) {
  24075. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  24076. }
  24077. this._geometry.setVerticesBuffer(buffer);
  24078. return this;
  24079. };
  24080. /**
  24081. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  24082. * If the mesh has no geometry, it is simply returned as it is.
  24083. * The `data` are either a numeric array either a Float32Array.
  24084. * No new underlying VertexBuffer object is created.
  24085. * 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.
  24086. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  24087. *
  24088. * Possible `kind` values :
  24089. * - BABYLON.VertexBuffer.PositionKind
  24090. * - BABYLON.VertexBuffer.UVKind
  24091. * - BABYLON.VertexBuffer.UV2Kind
  24092. * - BABYLON.VertexBuffer.UV3Kind
  24093. * - BABYLON.VertexBuffer.UV4Kind
  24094. * - BABYLON.VertexBuffer.UV5Kind
  24095. * - BABYLON.VertexBuffer.UV6Kind
  24096. * - BABYLON.VertexBuffer.ColorKind
  24097. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24098. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24099. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24100. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24101. *
  24102. * Returns the Mesh.
  24103. */
  24104. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  24105. if (!this._geometry) {
  24106. return this;
  24107. }
  24108. if (!makeItUnique) {
  24109. this._geometry.updateVerticesData(kind, data, updateExtends);
  24110. }
  24111. else {
  24112. this.makeGeometryUnique();
  24113. this.updateVerticesData(kind, data, updateExtends, false);
  24114. }
  24115. return this;
  24116. };
  24117. /**
  24118. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  24119. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  24120. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  24121. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  24122. * Returns the Mesh.
  24123. */
  24124. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  24125. if (computeNormals === void 0) { computeNormals = true; }
  24126. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24127. if (!positions) {
  24128. return this;
  24129. }
  24130. positionFunction(positions);
  24131. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  24132. if (computeNormals) {
  24133. var indices = this.getIndices();
  24134. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24135. if (!normals) {
  24136. return this;
  24137. }
  24138. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  24139. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  24140. }
  24141. return this;
  24142. };
  24143. /**
  24144. * Creates a un-shared specific occurence of the geometry for the mesh.
  24145. * Returns the Mesh.
  24146. */
  24147. Mesh.prototype.makeGeometryUnique = function () {
  24148. if (!this._geometry) {
  24149. return this;
  24150. }
  24151. var oldGeometry = this._geometry;
  24152. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  24153. oldGeometry.releaseForMesh(this, true);
  24154. geometry.applyToMesh(this);
  24155. return this;
  24156. };
  24157. /**
  24158. * Sets the mesh indices.
  24159. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  24160. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  24161. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  24162. * This method creates a new index buffer each call.
  24163. * Returns the Mesh.
  24164. */
  24165. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  24166. if (totalVertices === void 0) { totalVertices = null; }
  24167. if (updatable === void 0) { updatable = false; }
  24168. if (!this._geometry) {
  24169. var vertexData = new BABYLON.VertexData();
  24170. vertexData.indices = indices;
  24171. var scene = this.getScene();
  24172. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  24173. }
  24174. else {
  24175. this._geometry.setIndices(indices, totalVertices, updatable);
  24176. }
  24177. return this;
  24178. };
  24179. /**
  24180. * Update the current index buffer
  24181. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  24182. * Returns the Mesh.
  24183. */
  24184. Mesh.prototype.updateIndices = function (indices, offset) {
  24185. if (!this._geometry) {
  24186. return this;
  24187. }
  24188. this._geometry.updateIndices(indices, offset);
  24189. return this;
  24190. };
  24191. /**
  24192. * Invert the geometry to move from a right handed system to a left handed one.
  24193. * Returns the Mesh.
  24194. */
  24195. Mesh.prototype.toLeftHanded = function () {
  24196. if (!this._geometry) {
  24197. return this;
  24198. }
  24199. this._geometry.toLeftHanded();
  24200. return this;
  24201. };
  24202. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  24203. if (!this._geometry) {
  24204. return this;
  24205. }
  24206. var engine = this.getScene().getEngine();
  24207. // Wireframe
  24208. var indexToBind;
  24209. if (this._unIndexed) {
  24210. indexToBind = null;
  24211. }
  24212. else {
  24213. switch (fillMode) {
  24214. case BABYLON.Material.PointFillMode:
  24215. indexToBind = null;
  24216. break;
  24217. case BABYLON.Material.WireFrameFillMode:
  24218. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  24219. break;
  24220. default:
  24221. case BABYLON.Material.TriangleFillMode:
  24222. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  24223. break;
  24224. }
  24225. }
  24226. // VBOs
  24227. this._geometry._bind(effect, indexToBind);
  24228. return this;
  24229. };
  24230. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  24231. if (alternate === void 0) { alternate = false; }
  24232. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  24233. return this;
  24234. }
  24235. this.onBeforeDrawObservable.notifyObservers(this);
  24236. var scene = this.getScene();
  24237. var engine = scene.getEngine();
  24238. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  24239. // or triangles as points
  24240. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  24241. }
  24242. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  24243. // Triangles as wireframe
  24244. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  24245. }
  24246. else {
  24247. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  24248. }
  24249. if (scene._isAlternateRenderingEnabled && !alternate) {
  24250. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  24251. if (!effect || !scene.activeCamera) {
  24252. return this;
  24253. }
  24254. scene._switchToAlternateCameraConfiguration(true);
  24255. this._effectiveMaterial.bindView(effect);
  24256. this._effectiveMaterial.bindViewProjection(effect);
  24257. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  24258. this._draw(subMesh, fillMode, instancesCount, true);
  24259. engine.setViewport(scene.activeCamera.viewport);
  24260. scene._switchToAlternateCameraConfiguration(false);
  24261. this._effectiveMaterial.bindView(effect);
  24262. this._effectiveMaterial.bindViewProjection(effect);
  24263. }
  24264. return this;
  24265. };
  24266. /**
  24267. * Registers for this mesh a javascript function called just before the rendering process.
  24268. * This function is passed the current mesh.
  24269. * Return the Mesh.
  24270. */
  24271. Mesh.prototype.registerBeforeRender = function (func) {
  24272. this.onBeforeRenderObservable.add(func);
  24273. return this;
  24274. };
  24275. /**
  24276. * Disposes a previously registered javascript function called before the rendering.
  24277. * This function is passed the current mesh.
  24278. * Returns the Mesh.
  24279. */
  24280. Mesh.prototype.unregisterBeforeRender = function (func) {
  24281. this.onBeforeRenderObservable.removeCallback(func);
  24282. return this;
  24283. };
  24284. /**
  24285. * Registers for this mesh a javascript function called just after the rendering is complete.
  24286. * This function is passed the current mesh.
  24287. * Returns the Mesh.
  24288. */
  24289. Mesh.prototype.registerAfterRender = function (func) {
  24290. this.onAfterRenderObservable.add(func);
  24291. return this;
  24292. };
  24293. /**
  24294. * Disposes a previously registered javascript function called after the rendering.
  24295. * This function is passed the current mesh.
  24296. * Return the Mesh.
  24297. */
  24298. Mesh.prototype.unregisterAfterRender = function (func) {
  24299. this.onAfterRenderObservable.removeCallback(func);
  24300. return this;
  24301. };
  24302. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  24303. var scene = this.getScene();
  24304. this._batchCache.mustReturn = false;
  24305. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  24306. this._batchCache.visibleInstances[subMeshId] = null;
  24307. if (this._visibleInstances) {
  24308. var currentRenderId = scene.getRenderId();
  24309. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  24310. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  24311. var selfRenderId = this._renderId;
  24312. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  24313. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  24314. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  24315. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  24316. }
  24317. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  24318. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  24319. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  24320. this._batchCache.mustReturn = true;
  24321. return this._batchCache;
  24322. }
  24323. if (currentRenderId !== selfRenderId) {
  24324. this._batchCache.renderSelf[subMeshId] = false;
  24325. }
  24326. }
  24327. this._renderIdForInstances[subMeshId] = currentRenderId;
  24328. }
  24329. return this._batchCache;
  24330. };
  24331. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  24332. var visibleInstances = batch.visibleInstances[subMesh._id];
  24333. if (!visibleInstances) {
  24334. return this;
  24335. }
  24336. var matricesCount = visibleInstances.length + 1;
  24337. var bufferSize = matricesCount * 16 * 4;
  24338. var currentInstancesBufferSize = this._instancesBufferSize;
  24339. var instancesBuffer = this._instancesBuffer;
  24340. while (this._instancesBufferSize < bufferSize) {
  24341. this._instancesBufferSize *= 2;
  24342. }
  24343. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  24344. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  24345. }
  24346. var offset = 0;
  24347. var instancesCount = 0;
  24348. var world = this.getWorldMatrix();
  24349. if (batch.renderSelf[subMesh._id]) {
  24350. world.copyToArray(this._instancesData, offset);
  24351. offset += 16;
  24352. instancesCount++;
  24353. }
  24354. if (visibleInstances) {
  24355. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  24356. var instance = visibleInstances[instanceIndex];
  24357. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  24358. offset += 16;
  24359. instancesCount++;
  24360. }
  24361. }
  24362. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  24363. if (instancesBuffer) {
  24364. instancesBuffer.dispose();
  24365. }
  24366. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  24367. this._instancesBuffer = instancesBuffer;
  24368. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  24369. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  24370. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  24371. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  24372. }
  24373. else {
  24374. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  24375. }
  24376. this._bind(subMesh, effect, fillMode);
  24377. this._draw(subMesh, fillMode, instancesCount);
  24378. engine.unbindInstanceAttributes();
  24379. return this;
  24380. };
  24381. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  24382. var scene = this.getScene();
  24383. var engine = scene.getEngine();
  24384. if (hardwareInstancedRendering) {
  24385. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  24386. }
  24387. else {
  24388. if (batch.renderSelf[subMesh._id]) {
  24389. // Draw
  24390. if (onBeforeDraw) {
  24391. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  24392. }
  24393. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  24394. }
  24395. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  24396. if (visibleInstancesForSubMesh) {
  24397. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  24398. var instance = visibleInstancesForSubMesh[instanceIndex];
  24399. // World
  24400. var world = instance.getWorldMatrix();
  24401. if (onBeforeDraw) {
  24402. onBeforeDraw(true, world, effectiveMaterial);
  24403. }
  24404. // Draw
  24405. this._draw(subMesh, fillMode);
  24406. }
  24407. }
  24408. }
  24409. return this;
  24410. };
  24411. /**
  24412. * Triggers the draw call for the mesh.
  24413. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  24414. * Returns the Mesh.
  24415. */
  24416. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  24417. this.checkOcclusionQuery();
  24418. if (this._isOccluded) {
  24419. return this;
  24420. }
  24421. var scene = this.getScene();
  24422. // Managing instances
  24423. var batch = this._getInstancesRenderList(subMesh._id);
  24424. if (batch.mustReturn) {
  24425. return this;
  24426. }
  24427. // Checking geometry state
  24428. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  24429. return this;
  24430. }
  24431. this.onBeforeRenderObservable.notifyObservers(this);
  24432. var engine = scene.getEngine();
  24433. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  24434. // Material
  24435. var material = subMesh.getMaterial();
  24436. if (!material) {
  24437. return this;
  24438. }
  24439. this._effectiveMaterial = material;
  24440. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  24441. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  24442. return this;
  24443. }
  24444. }
  24445. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  24446. return this;
  24447. }
  24448. // Alpha mode
  24449. if (enableAlphaMode) {
  24450. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  24451. }
  24452. // Outline - step 1
  24453. var savedDepthWrite = engine.getDepthWrite();
  24454. if (this.renderOutline) {
  24455. engine.setDepthWrite(false);
  24456. scene.getOutlineRenderer().render(subMesh, batch);
  24457. engine.setDepthWrite(savedDepthWrite);
  24458. }
  24459. var effect;
  24460. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  24461. effect = subMesh.effect;
  24462. }
  24463. else {
  24464. effect = this._effectiveMaterial.getEffect();
  24465. }
  24466. if (!effect) {
  24467. return this;
  24468. }
  24469. var sideOrientation = this.overrideMaterialSideOrientation;
  24470. if (sideOrientation == null) {
  24471. sideOrientation = this._effectiveMaterial.sideOrientation;
  24472. if (this._getWorldMatrixDeterminant() < 0) {
  24473. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  24474. }
  24475. }
  24476. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  24477. if (this._effectiveMaterial.forceDepthWrite) {
  24478. engine.setDepthWrite(true);
  24479. }
  24480. // Bind
  24481. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  24482. if (!hardwareInstancedRendering) {
  24483. this._bind(subMesh, effect, fillMode);
  24484. }
  24485. var world = this.getWorldMatrix();
  24486. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  24487. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  24488. }
  24489. else {
  24490. this._effectiveMaterial.bind(world, this);
  24491. }
  24492. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  24493. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  24494. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  24495. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  24496. }
  24497. // Draw
  24498. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  24499. // Unbind
  24500. this._effectiveMaterial.unbind();
  24501. // Outline - step 2
  24502. if (this.renderOutline && savedDepthWrite) {
  24503. engine.setDepthWrite(true);
  24504. engine.setColorWrite(false);
  24505. scene.getOutlineRenderer().render(subMesh, batch);
  24506. engine.setColorWrite(true);
  24507. }
  24508. // Overlay
  24509. if (this.renderOverlay) {
  24510. var currentMode = engine.getAlphaMode();
  24511. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  24512. scene.getOutlineRenderer().render(subMesh, batch, true);
  24513. engine.setAlphaMode(currentMode);
  24514. }
  24515. this.onAfterRenderObservable.notifyObservers(this);
  24516. return this;
  24517. };
  24518. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  24519. if (isInstance && effectiveMaterial) {
  24520. effectiveMaterial.bindOnlyWorldMatrix(world);
  24521. }
  24522. };
  24523. /**
  24524. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  24525. */
  24526. Mesh.prototype.getEmittedParticleSystems = function () {
  24527. var results = new Array();
  24528. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  24529. var particleSystem = this.getScene().particleSystems[index];
  24530. if (particleSystem.emitter === this) {
  24531. results.push(particleSystem);
  24532. }
  24533. }
  24534. return results;
  24535. };
  24536. /**
  24537. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  24538. */
  24539. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  24540. var results = new Array();
  24541. var descendants = this.getDescendants();
  24542. descendants.push(this);
  24543. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  24544. var particleSystem = this.getScene().particleSystems[index];
  24545. var emitter = particleSystem.emitter;
  24546. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  24547. results.push(particleSystem);
  24548. }
  24549. }
  24550. return results;
  24551. };
  24552. Mesh.prototype._checkDelayState = function () {
  24553. var scene = this.getScene();
  24554. if (this._geometry) {
  24555. this._geometry.load(scene);
  24556. }
  24557. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24558. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  24559. this._queueLoad(scene);
  24560. }
  24561. return this;
  24562. };
  24563. Mesh.prototype._queueLoad = function (scene) {
  24564. var _this = this;
  24565. scene._addPendingData(this);
  24566. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  24567. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  24568. if (data instanceof ArrayBuffer) {
  24569. _this._delayLoadingFunction(data, _this);
  24570. }
  24571. else {
  24572. _this._delayLoadingFunction(JSON.parse(data), _this);
  24573. }
  24574. _this.instances.forEach(function (instance) {
  24575. instance._syncSubMeshes();
  24576. });
  24577. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24578. scene._removePendingData(_this);
  24579. }, function () { }, scene.database, getBinaryData);
  24580. return this;
  24581. };
  24582. /**
  24583. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  24584. */
  24585. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  24586. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  24587. return false;
  24588. }
  24589. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  24590. return false;
  24591. }
  24592. this._checkDelayState();
  24593. return true;
  24594. };
  24595. /**
  24596. * Sets the mesh material by the material or multiMaterial `id` property.
  24597. * The material `id` is a string identifying the material or the multiMaterial.
  24598. * This method returns the Mesh.
  24599. */
  24600. Mesh.prototype.setMaterialByID = function (id) {
  24601. var materials = this.getScene().materials;
  24602. var index;
  24603. for (index = materials.length - 1; index > -1; index--) {
  24604. if (materials[index].id === id) {
  24605. this.material = materials[index];
  24606. return this;
  24607. }
  24608. }
  24609. // Multi
  24610. var multiMaterials = this.getScene().multiMaterials;
  24611. for (index = multiMaterials.length - 1; index > -1; index--) {
  24612. if (multiMaterials[index].id === id) {
  24613. this.material = multiMaterials[index];
  24614. return this;
  24615. }
  24616. }
  24617. return this;
  24618. };
  24619. /**
  24620. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  24621. */
  24622. Mesh.prototype.getAnimatables = function () {
  24623. var results = new Array();
  24624. if (this.material) {
  24625. results.push(this.material);
  24626. }
  24627. if (this.skeleton) {
  24628. results.push(this.skeleton);
  24629. }
  24630. return results;
  24631. };
  24632. /**
  24633. * Modifies the mesh geometry according to the passed transformation matrix.
  24634. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  24635. * The mesh normals are modified accordingly the same transformation.
  24636. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  24637. * Note that, under the hood, this method sets a new VertexBuffer each call.
  24638. * Returns the Mesh.
  24639. */
  24640. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  24641. // Position
  24642. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24643. return this;
  24644. }
  24645. var submeshes = this.subMeshes.splice(0);
  24646. this._resetPointsArrayCache();
  24647. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24648. var temp = new Array();
  24649. var index;
  24650. for (index = 0; index < data.length; index += 3) {
  24651. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  24652. }
  24653. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  24654. // Normals
  24655. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24656. return this;
  24657. }
  24658. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24659. temp = [];
  24660. for (index = 0; index < data.length; index += 3) {
  24661. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  24662. }
  24663. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  24664. // flip faces?
  24665. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  24666. this.flipFaces();
  24667. }
  24668. // Restore submeshes
  24669. this.releaseSubMeshes();
  24670. this.subMeshes = submeshes;
  24671. return this;
  24672. };
  24673. /**
  24674. * Modifies the mesh geometry according to its own current World Matrix.
  24675. * The mesh World Matrix is then reset.
  24676. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  24677. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  24678. * Note that, under the hood, this method sets a new VertexBuffer each call.
  24679. * Returns the Mesh.
  24680. */
  24681. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  24682. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  24683. this.scaling.copyFromFloats(1, 1, 1);
  24684. this.position.copyFromFloats(0, 0, 0);
  24685. this.rotation.copyFromFloats(0, 0, 0);
  24686. //only if quaternion is already set
  24687. if (this.rotationQuaternion) {
  24688. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  24689. }
  24690. this._worldMatrix = BABYLON.Matrix.Identity();
  24691. return this;
  24692. };
  24693. Object.defineProperty(Mesh.prototype, "_positions", {
  24694. // Cache
  24695. get: function () {
  24696. if (this._geometry) {
  24697. return this._geometry._positions;
  24698. }
  24699. return null;
  24700. },
  24701. enumerable: true,
  24702. configurable: true
  24703. });
  24704. Mesh.prototype._resetPointsArrayCache = function () {
  24705. if (this._geometry) {
  24706. this._geometry._resetPointsArrayCache();
  24707. }
  24708. return this;
  24709. };
  24710. Mesh.prototype._generatePointsArray = function () {
  24711. if (this._geometry) {
  24712. return this._geometry._generatePointsArray();
  24713. }
  24714. return false;
  24715. };
  24716. /**
  24717. * Returns a new Mesh object generated from the current mesh properties.
  24718. * This method must not get confused with createInstance().
  24719. * The parameter `name` is a string, the name given to the new mesh.
  24720. * The optional parameter `newParent` can be any Node object (default `null`).
  24721. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  24722. * 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.
  24723. */
  24724. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  24725. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  24726. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  24727. };
  24728. /**
  24729. * Disposes the Mesh.
  24730. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  24731. * Returns nothing.
  24732. */
  24733. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  24734. var _this = this;
  24735. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  24736. this.morphTargetManager = null;
  24737. if (this._geometry) {
  24738. this._geometry.releaseForMesh(this, true);
  24739. }
  24740. // Sources
  24741. var meshes = this.getScene().meshes;
  24742. meshes.forEach(function (abstractMesh) {
  24743. var mesh = abstractMesh;
  24744. if (mesh._source && mesh._source === _this) {
  24745. mesh._source = null;
  24746. }
  24747. });
  24748. this._source = null;
  24749. // Instances
  24750. if (this._instancesBuffer) {
  24751. this._instancesBuffer.dispose();
  24752. this._instancesBuffer = null;
  24753. }
  24754. while (this.instances.length) {
  24755. this.instances[0].dispose();
  24756. }
  24757. // Highlight layers.
  24758. var highlightLayers = this.getScene().highlightLayers;
  24759. for (var i = 0; i < highlightLayers.length; i++) {
  24760. var highlightLayer = highlightLayers[i];
  24761. if (highlightLayer) {
  24762. highlightLayer.removeMesh(this);
  24763. highlightLayer.removeExcludedMesh(this);
  24764. }
  24765. }
  24766. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  24767. };
  24768. /**
  24769. * Modifies the mesh geometry according to a displacement map.
  24770. * 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.
  24771. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  24772. * This method returns nothing.
  24773. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  24774. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  24775. * 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.
  24776. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  24777. * The parameter `uvScale` is an optional vector2 used to scale UV.
  24778. *
  24779. * Returns the Mesh.
  24780. */
  24781. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  24782. var _this = this;
  24783. var scene = this.getScene();
  24784. var onload = function (img) {
  24785. // Getting height map data
  24786. var canvas = document.createElement("canvas");
  24787. var context = canvas.getContext("2d");
  24788. var heightMapWidth = img.width;
  24789. var heightMapHeight = img.height;
  24790. canvas.width = heightMapWidth;
  24791. canvas.height = heightMapHeight;
  24792. context.drawImage(img, 0, 0);
  24793. // Create VertexData from map data
  24794. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  24795. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  24796. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  24797. //execute success callback, if set
  24798. if (onSuccess) {
  24799. onSuccess(_this);
  24800. }
  24801. };
  24802. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  24803. return this;
  24804. };
  24805. /**
  24806. * Modifies the mesh geometry according to a displacementMap buffer.
  24807. * 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.
  24808. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  24809. * This method returns nothing.
  24810. * 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.
  24811. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  24812. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  24813. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  24814. * The parameter `uvScale` is an optional vector2 used to scale UV.
  24815. *
  24816. * Returns the Mesh.
  24817. */
  24818. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  24819. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  24820. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  24821. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24822. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  24823. return this;
  24824. }
  24825. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24826. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24827. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  24828. var position = BABYLON.Vector3.Zero();
  24829. var normal = BABYLON.Vector3.Zero();
  24830. var uv = BABYLON.Vector2.Zero();
  24831. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  24832. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  24833. for (var index = 0; index < positions.length; index += 3) {
  24834. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  24835. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  24836. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  24837. // Compute height
  24838. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  24839. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  24840. var pos = (u + v * heightMapWidth) * 4;
  24841. var r = buffer[pos] / 255.0;
  24842. var g = buffer[pos + 1] / 255.0;
  24843. var b = buffer[pos + 2] / 255.0;
  24844. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  24845. normal.normalize();
  24846. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  24847. position = position.add(normal);
  24848. position.toArray(positions, index);
  24849. }
  24850. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  24851. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  24852. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  24853. return this;
  24854. };
  24855. /**
  24856. * Modify the mesh to get a flat shading rendering.
  24857. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  24858. * This method returns the Mesh.
  24859. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  24860. */
  24861. Mesh.prototype.convertToFlatShadedMesh = function () {
  24862. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  24863. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  24864. var kinds = this.getVerticesDataKinds();
  24865. var vbs = {};
  24866. var data = {};
  24867. var newdata = {};
  24868. var updatableNormals = false;
  24869. var kindIndex;
  24870. var kind;
  24871. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24872. kind = kinds[kindIndex];
  24873. var vertexBuffer = this.getVertexBuffer(kind);
  24874. if (kind === BABYLON.VertexBuffer.NormalKind) {
  24875. updatableNormals = vertexBuffer.isUpdatable();
  24876. kinds.splice(kindIndex, 1);
  24877. kindIndex--;
  24878. continue;
  24879. }
  24880. vbs[kind] = vertexBuffer;
  24881. data[kind] = vbs[kind].getData();
  24882. newdata[kind] = [];
  24883. }
  24884. // Save previous submeshes
  24885. var previousSubmeshes = this.subMeshes.slice(0);
  24886. var indices = this.getIndices();
  24887. var totalIndices = this.getTotalIndices();
  24888. // Generating unique vertices per face
  24889. var index;
  24890. for (index = 0; index < totalIndices; index++) {
  24891. var vertexIndex = indices[index];
  24892. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24893. kind = kinds[kindIndex];
  24894. var stride = vbs[kind].getStrideSize();
  24895. for (var offset = 0; offset < stride; offset++) {
  24896. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  24897. }
  24898. }
  24899. }
  24900. // Updating faces & normal
  24901. var normals = [];
  24902. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  24903. for (index = 0; index < totalIndices; index += 3) {
  24904. indices[index] = index;
  24905. indices[index + 1] = index + 1;
  24906. indices[index + 2] = index + 2;
  24907. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  24908. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  24909. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  24910. var p1p2 = p1.subtract(p2);
  24911. var p3p2 = p3.subtract(p2);
  24912. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  24913. // Store same normals for every vertex
  24914. for (var localIndex = 0; localIndex < 3; localIndex++) {
  24915. normals.push(normal.x);
  24916. normals.push(normal.y);
  24917. normals.push(normal.z);
  24918. }
  24919. }
  24920. this.setIndices(indices);
  24921. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  24922. // Updating vertex buffers
  24923. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24924. kind = kinds[kindIndex];
  24925. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24926. }
  24927. // Updating submeshes
  24928. this.releaseSubMeshes();
  24929. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24930. var previousOne = previousSubmeshes[submeshIndex];
  24931. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24932. }
  24933. this.synchronizeInstances();
  24934. return this;
  24935. };
  24936. /**
  24937. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  24938. * In other words, more vertices, no more indices and a single bigger VBO.
  24939. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  24940. * Returns the Mesh.
  24941. */
  24942. Mesh.prototype.convertToUnIndexedMesh = function () {
  24943. /// <summary>Remove indices by unfolding faces into buffers</summary>
  24944. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  24945. var kinds = this.getVerticesDataKinds();
  24946. var vbs = {};
  24947. var data = {};
  24948. var newdata = {};
  24949. var kindIndex;
  24950. var kind;
  24951. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24952. kind = kinds[kindIndex];
  24953. var vertexBuffer = this.getVertexBuffer(kind);
  24954. vbs[kind] = vertexBuffer;
  24955. data[kind] = vbs[kind].getData();
  24956. newdata[kind] = [];
  24957. }
  24958. // Save previous submeshes
  24959. var previousSubmeshes = this.subMeshes.slice(0);
  24960. var indices = this.getIndices();
  24961. var totalIndices = this.getTotalIndices();
  24962. // Generating unique vertices per face
  24963. var index;
  24964. for (index = 0; index < totalIndices; index++) {
  24965. var vertexIndex = indices[index];
  24966. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24967. kind = kinds[kindIndex];
  24968. var stride = vbs[kind].getStrideSize();
  24969. for (var offset = 0; offset < stride; offset++) {
  24970. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  24971. }
  24972. }
  24973. }
  24974. // Updating indices
  24975. for (index = 0; index < totalIndices; index += 3) {
  24976. indices[index] = index;
  24977. indices[index + 1] = index + 1;
  24978. indices[index + 2] = index + 2;
  24979. }
  24980. this.setIndices(indices);
  24981. // Updating vertex buffers
  24982. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24983. kind = kinds[kindIndex];
  24984. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24985. }
  24986. // Updating submeshes
  24987. this.releaseSubMeshes();
  24988. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24989. var previousOne = previousSubmeshes[submeshIndex];
  24990. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24991. }
  24992. this._unIndexed = true;
  24993. this.synchronizeInstances();
  24994. return this;
  24995. };
  24996. /**
  24997. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  24998. * This method returns the Mesh.
  24999. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  25000. */
  25001. Mesh.prototype.flipFaces = function (flipNormals) {
  25002. if (flipNormals === void 0) { flipNormals = false; }
  25003. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  25004. var i;
  25005. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  25006. for (i = 0; i < vertex_data.normals.length; i++) {
  25007. vertex_data.normals[i] *= -1;
  25008. }
  25009. }
  25010. if (vertex_data.indices) {
  25011. var temp;
  25012. for (i = 0; i < vertex_data.indices.length; i += 3) {
  25013. // reassign indices
  25014. temp = vertex_data.indices[i + 1];
  25015. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  25016. vertex_data.indices[i + 2] = temp;
  25017. }
  25018. }
  25019. vertex_data.applyToMesh(this);
  25020. return this;
  25021. };
  25022. // Instances
  25023. /**
  25024. * Creates a new InstancedMesh object from the mesh model.
  25025. * An instance shares the same properties and the same material than its model.
  25026. * Only these properties of each instance can then be set individually :
  25027. * - position
  25028. * - rotation
  25029. * - rotationQuaternion
  25030. * - setPivotMatrix
  25031. * - scaling
  25032. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  25033. * Warning : this method is not supported for Line mesh and LineSystem
  25034. */
  25035. Mesh.prototype.createInstance = function (name) {
  25036. return new BABYLON.InstancedMesh(name, this);
  25037. };
  25038. /**
  25039. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  25040. * After this call, all the mesh instances have the same submeshes than the current mesh.
  25041. * This method returns the Mesh.
  25042. */
  25043. Mesh.prototype.synchronizeInstances = function () {
  25044. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  25045. var instance = this.instances[instanceIndex];
  25046. instance._syncSubMeshes();
  25047. }
  25048. return this;
  25049. };
  25050. /**
  25051. * Simplify the mesh according to the given array of settings.
  25052. * Function will return immediately and will simplify async. It returns the Mesh.
  25053. * @param settings a collection of simplification settings.
  25054. * @param parallelProcessing should all levels calculate parallel or one after the other.
  25055. * @param type the type of simplification to run.
  25056. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  25057. */
  25058. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  25059. if (parallelProcessing === void 0) { parallelProcessing = true; }
  25060. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  25061. this.getScene().simplificationQueue.addTask({
  25062. settings: settings,
  25063. parallelProcessing: parallelProcessing,
  25064. mesh: this,
  25065. simplificationType: simplificationType,
  25066. successCallback: successCallback
  25067. });
  25068. return this;
  25069. };
  25070. /**
  25071. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  25072. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  25073. * This should be used together with the simplification to avoid disappearing triangles.
  25074. * Returns the Mesh.
  25075. * @param successCallback an optional success callback to be called after the optimization finished.
  25076. */
  25077. Mesh.prototype.optimizeIndices = function (successCallback) {
  25078. var _this = this;
  25079. var indices = this.getIndices();
  25080. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25081. if (!positions || !indices) {
  25082. return this;
  25083. }
  25084. var vectorPositions = new Array();
  25085. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  25086. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  25087. }
  25088. var dupes = new Array();
  25089. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  25090. var realPos = vectorPositions.length - 1 - iteration;
  25091. var testedPosition = vectorPositions[realPos];
  25092. for (var j = 0; j < realPos; ++j) {
  25093. var againstPosition = vectorPositions[j];
  25094. if (testedPosition.equals(againstPosition)) {
  25095. dupes[realPos] = j;
  25096. break;
  25097. }
  25098. }
  25099. }, function () {
  25100. for (var i = 0; i < indices.length; ++i) {
  25101. indices[i] = dupes[indices[i]] || indices[i];
  25102. }
  25103. //indices are now reordered
  25104. var originalSubMeshes = _this.subMeshes.slice(0);
  25105. _this.setIndices(indices);
  25106. _this.subMeshes = originalSubMeshes;
  25107. if (successCallback) {
  25108. successCallback(_this);
  25109. }
  25110. });
  25111. return this;
  25112. };
  25113. Mesh.prototype.serialize = function (serializationObject) {
  25114. serializationObject.name = this.name;
  25115. serializationObject.id = this.id;
  25116. serializationObject.type = this.getClassName();
  25117. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  25118. serializationObject.tags = BABYLON.Tags.GetTags(this);
  25119. }
  25120. serializationObject.position = this.position.asArray();
  25121. if (this.rotationQuaternion) {
  25122. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  25123. }
  25124. else if (this.rotation) {
  25125. serializationObject.rotation = this.rotation.asArray();
  25126. }
  25127. serializationObject.scaling = this.scaling.asArray();
  25128. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  25129. serializationObject.isEnabled = this.isEnabled();
  25130. serializationObject.isVisible = this.isVisible;
  25131. serializationObject.infiniteDistance = this.infiniteDistance;
  25132. serializationObject.pickable = this.isPickable;
  25133. serializationObject.receiveShadows = this.receiveShadows;
  25134. serializationObject.billboardMode = this.billboardMode;
  25135. serializationObject.visibility = this.visibility;
  25136. serializationObject.checkCollisions = this.checkCollisions;
  25137. serializationObject.isBlocker = this.isBlocker;
  25138. // Parent
  25139. if (this.parent) {
  25140. serializationObject.parentId = this.parent.id;
  25141. }
  25142. // Geometry
  25143. serializationObject.isUnIndexed = this.isUnIndexed;
  25144. var geometry = this._geometry;
  25145. if (geometry) {
  25146. var geometryId = geometry.id;
  25147. serializationObject.geometryId = geometryId;
  25148. // SubMeshes
  25149. serializationObject.subMeshes = [];
  25150. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  25151. var subMesh = this.subMeshes[subIndex];
  25152. serializationObject.subMeshes.push({
  25153. materialIndex: subMesh.materialIndex,
  25154. verticesStart: subMesh.verticesStart,
  25155. verticesCount: subMesh.verticesCount,
  25156. indexStart: subMesh.indexStart,
  25157. indexCount: subMesh.indexCount
  25158. });
  25159. }
  25160. }
  25161. // Material
  25162. if (this.material) {
  25163. serializationObject.materialId = this.material.id;
  25164. }
  25165. else {
  25166. this.material = null;
  25167. }
  25168. // Morph targets
  25169. if (this.morphTargetManager) {
  25170. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  25171. }
  25172. // Skeleton
  25173. if (this.skeleton) {
  25174. serializationObject.skeletonId = this.skeleton.id;
  25175. }
  25176. // Physics
  25177. //TODO implement correct serialization for physics impostors.
  25178. var impostor = this.getPhysicsImpostor();
  25179. if (impostor) {
  25180. serializationObject.physicsMass = impostor.getParam("mass");
  25181. serializationObject.physicsFriction = impostor.getParam("friction");
  25182. serializationObject.physicsRestitution = impostor.getParam("mass");
  25183. serializationObject.physicsImpostor = impostor.type;
  25184. }
  25185. // Metadata
  25186. if (this.metadata) {
  25187. serializationObject.metadata = this.metadata;
  25188. }
  25189. // Instances
  25190. serializationObject.instances = [];
  25191. for (var index = 0; index < this.instances.length; index++) {
  25192. var instance = this.instances[index];
  25193. var serializationInstance = {
  25194. name: instance.name,
  25195. id: instance.id,
  25196. position: instance.position.asArray(),
  25197. scaling: instance.scaling.asArray()
  25198. };
  25199. if (instance.rotationQuaternion) {
  25200. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  25201. }
  25202. else if (instance.rotation) {
  25203. serializationInstance.rotation = instance.rotation.asArray();
  25204. }
  25205. serializationObject.instances.push(serializationInstance);
  25206. // Animations
  25207. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  25208. serializationInstance.ranges = instance.serializeAnimationRanges();
  25209. }
  25210. //
  25211. // Animations
  25212. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  25213. serializationObject.ranges = this.serializeAnimationRanges();
  25214. // Layer mask
  25215. serializationObject.layerMask = this.layerMask;
  25216. // Alpha
  25217. serializationObject.alphaIndex = this.alphaIndex;
  25218. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  25219. // Overlay
  25220. serializationObject.overlayAlpha = this.overlayAlpha;
  25221. serializationObject.overlayColor = this.overlayColor.asArray();
  25222. serializationObject.renderOverlay = this.renderOverlay;
  25223. // Fog
  25224. serializationObject.applyFog = this.applyFog;
  25225. // Action Manager
  25226. if (this.actionManager) {
  25227. serializationObject.actions = this.actionManager.serialize(this.name);
  25228. }
  25229. };
  25230. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  25231. if (!this.geometry) {
  25232. return;
  25233. }
  25234. this._markSubMeshesAsAttributesDirty();
  25235. var morphTargetManager = this._morphTargetManager;
  25236. if (morphTargetManager && morphTargetManager.vertexCount) {
  25237. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  25238. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  25239. this.morphTargetManager = null;
  25240. return;
  25241. }
  25242. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  25243. var morphTarget = morphTargetManager.getActiveTarget(index);
  25244. var positions = morphTarget.getPositions();
  25245. if (!positions) {
  25246. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  25247. return;
  25248. }
  25249. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  25250. var normals = morphTarget.getNormals();
  25251. if (normals) {
  25252. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  25253. }
  25254. var tangents = morphTarget.getTangents();
  25255. if (tangents) {
  25256. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  25257. }
  25258. }
  25259. }
  25260. else {
  25261. var index = 0;
  25262. // Positions
  25263. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  25264. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  25265. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  25266. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  25267. }
  25268. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  25269. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  25270. }
  25271. index++;
  25272. }
  25273. }
  25274. };
  25275. // Statics
  25276. /**
  25277. * Returns a new Mesh object parsed from the source provided.
  25278. * The parameter `parsedMesh` is the source.
  25279. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  25280. */
  25281. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  25282. var mesh;
  25283. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  25284. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  25285. }
  25286. else {
  25287. mesh = new Mesh(parsedMesh.name, scene);
  25288. }
  25289. mesh.id = parsedMesh.id;
  25290. if (BABYLON.Tags) {
  25291. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  25292. }
  25293. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  25294. if (parsedMesh.metadata !== undefined) {
  25295. mesh.metadata = parsedMesh.metadata;
  25296. }
  25297. if (parsedMesh.rotationQuaternion) {
  25298. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  25299. }
  25300. else if (parsedMesh.rotation) {
  25301. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  25302. }
  25303. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  25304. if (parsedMesh.localMatrix) {
  25305. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  25306. }
  25307. else if (parsedMesh.pivotMatrix) {
  25308. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  25309. }
  25310. mesh.setEnabled(parsedMesh.isEnabled);
  25311. mesh.isVisible = parsedMesh.isVisible;
  25312. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  25313. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  25314. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  25315. if (parsedMesh.applyFog !== undefined) {
  25316. mesh.applyFog = parsedMesh.applyFog;
  25317. }
  25318. if (parsedMesh.pickable !== undefined) {
  25319. mesh.isPickable = parsedMesh.pickable;
  25320. }
  25321. if (parsedMesh.alphaIndex !== undefined) {
  25322. mesh.alphaIndex = parsedMesh.alphaIndex;
  25323. }
  25324. mesh.receiveShadows = parsedMesh.receiveShadows;
  25325. mesh.billboardMode = parsedMesh.billboardMode;
  25326. if (parsedMesh.visibility !== undefined) {
  25327. mesh.visibility = parsedMesh.visibility;
  25328. }
  25329. mesh.checkCollisions = parsedMesh.checkCollisions;
  25330. if (parsedMesh.isBlocker !== undefined) {
  25331. mesh.isBlocker = parsedMesh.isBlocker;
  25332. }
  25333. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  25334. // freezeWorldMatrix
  25335. if (parsedMesh.freezeWorldMatrix) {
  25336. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  25337. }
  25338. // Parent
  25339. if (parsedMesh.parentId) {
  25340. mesh._waitingParentId = parsedMesh.parentId;
  25341. }
  25342. // Actions
  25343. if (parsedMesh.actions !== undefined) {
  25344. mesh._waitingActions = parsedMesh.actions;
  25345. }
  25346. // Overlay
  25347. if (parsedMesh.overlayAlpha !== undefined) {
  25348. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  25349. }
  25350. if (parsedMesh.overlayColor !== undefined) {
  25351. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  25352. }
  25353. if (parsedMesh.renderOverlay !== undefined) {
  25354. mesh.renderOverlay = parsedMesh.renderOverlay;
  25355. }
  25356. // Geometry
  25357. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  25358. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  25359. if (parsedMesh.delayLoadingFile) {
  25360. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  25361. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  25362. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  25363. if (parsedMesh._binaryInfo) {
  25364. mesh._binaryInfo = parsedMesh._binaryInfo;
  25365. }
  25366. mesh._delayInfo = [];
  25367. if (parsedMesh.hasUVs) {
  25368. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  25369. }
  25370. if (parsedMesh.hasUVs2) {
  25371. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  25372. }
  25373. if (parsedMesh.hasUVs3) {
  25374. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  25375. }
  25376. if (parsedMesh.hasUVs4) {
  25377. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  25378. }
  25379. if (parsedMesh.hasUVs5) {
  25380. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  25381. }
  25382. if (parsedMesh.hasUVs6) {
  25383. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  25384. }
  25385. if (parsedMesh.hasColors) {
  25386. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  25387. }
  25388. if (parsedMesh.hasMatricesIndices) {
  25389. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25390. }
  25391. if (parsedMesh.hasMatricesWeights) {
  25392. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25393. }
  25394. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  25395. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  25396. mesh._checkDelayState();
  25397. }
  25398. }
  25399. else {
  25400. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  25401. }
  25402. // Material
  25403. if (parsedMesh.materialId) {
  25404. mesh.setMaterialByID(parsedMesh.materialId);
  25405. }
  25406. else {
  25407. mesh.material = null;
  25408. }
  25409. // Morph targets
  25410. if (parsedMesh.morphTargetManagerId > -1) {
  25411. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  25412. }
  25413. // Skeleton
  25414. if (parsedMesh.skeletonId > -1) {
  25415. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  25416. if (parsedMesh.numBoneInfluencers) {
  25417. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  25418. }
  25419. }
  25420. // Animations
  25421. if (parsedMesh.animations) {
  25422. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  25423. var parsedAnimation = parsedMesh.animations[animationIndex];
  25424. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25425. }
  25426. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  25427. }
  25428. if (parsedMesh.autoAnimate) {
  25429. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  25430. }
  25431. // Layer Mask
  25432. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  25433. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  25434. }
  25435. else {
  25436. mesh.layerMask = 0x0FFFFFFF;
  25437. }
  25438. // Physics
  25439. if (parsedMesh.physicsImpostor) {
  25440. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  25441. mass: parsedMesh.physicsMass,
  25442. friction: parsedMesh.physicsFriction,
  25443. restitution: parsedMesh.physicsRestitution
  25444. }, scene);
  25445. }
  25446. // Instances
  25447. if (parsedMesh.instances) {
  25448. for (var index = 0; index < parsedMesh.instances.length; index++) {
  25449. var parsedInstance = parsedMesh.instances[index];
  25450. var instance = mesh.createInstance(parsedInstance.name);
  25451. if (parsedInstance.id) {
  25452. instance.id = parsedInstance.id;
  25453. }
  25454. if (BABYLON.Tags) {
  25455. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  25456. }
  25457. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  25458. if (parsedInstance.parentId) {
  25459. instance._waitingParentId = parsedInstance.parentId;
  25460. }
  25461. if (parsedInstance.rotationQuaternion) {
  25462. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  25463. }
  25464. else if (parsedInstance.rotation) {
  25465. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  25466. }
  25467. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  25468. instance.checkCollisions = mesh.checkCollisions;
  25469. if (parsedMesh.animations) {
  25470. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  25471. parsedAnimation = parsedMesh.animations[animationIndex];
  25472. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25473. }
  25474. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  25475. }
  25476. }
  25477. }
  25478. return mesh;
  25479. };
  25480. /**
  25481. * Creates a ribbon mesh.
  25482. * Please consider using the same method from the MeshBuilder class instead.
  25483. * 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.
  25484. *
  25485. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  25486. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  25487. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  25488. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  25489. * 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.
  25490. * 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.
  25491. * 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
  25492. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25493. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25494. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25495. */
  25496. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  25497. if (closeArray === void 0) { closeArray = false; }
  25498. if (updatable === void 0) { updatable = false; }
  25499. return BABYLON.MeshBuilder.CreateRibbon(name, {
  25500. pathArray: pathArray,
  25501. closeArray: closeArray,
  25502. closePath: closePath,
  25503. offset: offset,
  25504. updatable: updatable,
  25505. sideOrientation: sideOrientation,
  25506. instance: instance
  25507. }, scene);
  25508. };
  25509. /**
  25510. * Creates a plane polygonal mesh. By default, this is a disc.
  25511. * Please consider using the same method from the MeshBuilder class instead.
  25512. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  25513. * 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.
  25514. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25515. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25516. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25517. */
  25518. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  25519. if (scene === void 0) { scene = null; }
  25520. var options = {
  25521. radius: radius,
  25522. tessellation: tessellation,
  25523. sideOrientation: sideOrientation,
  25524. updatable: updatable
  25525. };
  25526. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  25527. };
  25528. /**
  25529. * Creates a box mesh.
  25530. * Please consider using the same method from the MeshBuilder class instead.
  25531. * The parameter `size` sets the size (float) of each box side (default 1).
  25532. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25533. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25534. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25535. */
  25536. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  25537. if (scene === void 0) { scene = null; }
  25538. var options = {
  25539. size: size,
  25540. sideOrientation: sideOrientation,
  25541. updatable: updatable
  25542. };
  25543. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  25544. };
  25545. /**
  25546. * Creates a sphere mesh.
  25547. * Please consider using the same method from the MeshBuilder class instead.
  25548. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  25549. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  25550. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25551. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25552. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25553. */
  25554. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  25555. var options = {
  25556. segments: segments,
  25557. diameterX: diameter,
  25558. diameterY: diameter,
  25559. diameterZ: diameter,
  25560. sideOrientation: sideOrientation,
  25561. updatable: updatable
  25562. };
  25563. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  25564. };
  25565. /**
  25566. * Creates a cylinder or a cone mesh.
  25567. * Please consider using the same method from the MeshBuilder class instead.
  25568. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  25569. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  25570. * 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.
  25571. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  25572. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  25573. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25574. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25575. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25576. */
  25577. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  25578. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  25579. if (scene !== undefined) {
  25580. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  25581. updatable = scene;
  25582. }
  25583. scene = subdivisions;
  25584. subdivisions = 1;
  25585. }
  25586. var options = {
  25587. height: height,
  25588. diameterTop: diameterTop,
  25589. diameterBottom: diameterBottom,
  25590. tessellation: tessellation,
  25591. subdivisions: subdivisions,
  25592. sideOrientation: sideOrientation,
  25593. updatable: updatable
  25594. };
  25595. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  25596. };
  25597. // Torus (Code from SharpDX.org)
  25598. /**
  25599. * Creates a torus mesh.
  25600. * Please consider using the same method from the MeshBuilder class instead.
  25601. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  25602. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  25603. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  25604. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25605. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25606. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25607. */
  25608. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  25609. var options = {
  25610. diameter: diameter,
  25611. thickness: thickness,
  25612. tessellation: tessellation,
  25613. sideOrientation: sideOrientation,
  25614. updatable: updatable
  25615. };
  25616. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  25617. };
  25618. /**
  25619. * Creates a torus knot mesh.
  25620. * Please consider using the same method from the MeshBuilder class instead.
  25621. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  25622. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  25623. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  25624. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  25625. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25626. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25627. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25628. */
  25629. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  25630. var options = {
  25631. radius: radius,
  25632. tube: tube,
  25633. radialSegments: radialSegments,
  25634. tubularSegments: tubularSegments,
  25635. p: p,
  25636. q: q,
  25637. sideOrientation: sideOrientation,
  25638. updatable: updatable
  25639. };
  25640. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  25641. };
  25642. /**
  25643. * Creates a line mesh.
  25644. * Please consider using the same method from the MeshBuilder class instead.
  25645. * 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.
  25646. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  25647. * The parameter `points` is an array successive Vector3.
  25648. * 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
  25649. * When updating an instance, remember that only point positions can change, not the number of points.
  25650. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25651. */
  25652. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  25653. if (scene === void 0) { scene = null; }
  25654. if (updatable === void 0) { updatable = false; }
  25655. if (instance === void 0) { instance = null; }
  25656. var options = {
  25657. points: points,
  25658. updatable: updatable,
  25659. instance: instance
  25660. };
  25661. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  25662. };
  25663. /**
  25664. * Creates a dashed line mesh.
  25665. * Please consider using the same method from the MeshBuilder class instead.
  25666. * 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.
  25667. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  25668. * The parameter `points` is an array successive Vector3.
  25669. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  25670. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  25671. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  25672. * 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
  25673. * When updating an instance, remember that only point positions can change, not the number of points.
  25674. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25675. */
  25676. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  25677. if (scene === void 0) { scene = null; }
  25678. var options = {
  25679. points: points,
  25680. dashSize: dashSize,
  25681. gapSize: gapSize,
  25682. dashNb: dashNb,
  25683. updatable: updatable,
  25684. instance: instance
  25685. };
  25686. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  25687. };
  25688. /**
  25689. * Creates a polygon mesh.
  25690. * Please consider using the same method from the MeshBuilder class instead.
  25691. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  25692. * 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.
  25693. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25694. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25695. * Remember you can only change the shape positions, not their number when updating a polygon.
  25696. */
  25697. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  25698. var options = {
  25699. shape: shape,
  25700. holes: holes,
  25701. updatable: updatable,
  25702. sideOrientation: sideOrientation
  25703. };
  25704. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  25705. };
  25706. /**
  25707. * Creates an extruded polygon mesh, with depth in the Y direction.
  25708. * Please consider using the same method from the MeshBuilder class instead.
  25709. */
  25710. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  25711. var options = {
  25712. shape: shape,
  25713. holes: holes,
  25714. depth: depth,
  25715. updatable: updatable,
  25716. sideOrientation: sideOrientation
  25717. };
  25718. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  25719. };
  25720. /**
  25721. * Creates an extruded shape mesh.
  25722. * 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.
  25723. * Please consider using the same method from the MeshBuilder class instead.
  25724. *
  25725. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  25726. * 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
  25727. * extruded along the Z axis.
  25728. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  25729. * 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.
  25730. * The parameter `scale` (float, default 1) is the value to scale the shape.
  25731. * 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
  25732. * 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
  25733. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  25734. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25735. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25736. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25737. */
  25738. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  25739. if (scene === void 0) { scene = null; }
  25740. var options = {
  25741. shape: shape,
  25742. path: path,
  25743. scale: scale,
  25744. rotation: rotation,
  25745. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  25746. sideOrientation: sideOrientation,
  25747. instance: instance,
  25748. updatable: updatable
  25749. };
  25750. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  25751. };
  25752. /**
  25753. * Creates an custom extruded shape mesh.
  25754. * 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.
  25755. * Please consider using the same method from the MeshBuilder class instead.
  25756. *
  25757. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  25758. * 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
  25759. * extruded along the Z axis.
  25760. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  25761. * 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
  25762. * and the distance of this point from the begining of the path :
  25763. * ```javascript
  25764. * var rotationFunction = function(i, distance) {
  25765. * // do things
  25766. * return rotationValue; }
  25767. * ```
  25768. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  25769. * 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
  25770. * and the distance of this point from the begining of the path :
  25771. * ```javascript
  25772. * var scaleFunction = function(i, distance) {
  25773. * // do things
  25774. * return scaleValue;}
  25775. * ```
  25776. * It must returns a float value that will be the scale value applied to the shape on each path point.
  25777. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  25778. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  25779. * 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
  25780. * 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
  25781. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  25782. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25783. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25784. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25785. */
  25786. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  25787. var options = {
  25788. shape: shape,
  25789. path: path,
  25790. scaleFunction: scaleFunction,
  25791. rotationFunction: rotationFunction,
  25792. ribbonCloseArray: ribbonCloseArray,
  25793. ribbonClosePath: ribbonClosePath,
  25794. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  25795. sideOrientation: sideOrientation,
  25796. instance: instance,
  25797. updatable: updatable
  25798. };
  25799. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  25800. };
  25801. /**
  25802. * Creates lathe mesh.
  25803. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  25804. * Please consider using the same method from the MeshBuilder class instead.
  25805. * 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
  25806. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  25807. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  25808. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  25809. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25810. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25811. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25812. */
  25813. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  25814. var options = {
  25815. shape: shape,
  25816. radius: radius,
  25817. tessellation: tessellation,
  25818. sideOrientation: sideOrientation,
  25819. updatable: updatable
  25820. };
  25821. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  25822. };
  25823. /**
  25824. * Creates a plane mesh.
  25825. * Please consider using the same method from the MeshBuilder class instead.
  25826. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  25827. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25828. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25829. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25830. */
  25831. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  25832. var options = {
  25833. size: size,
  25834. width: size,
  25835. height: size,
  25836. sideOrientation: sideOrientation,
  25837. updatable: updatable
  25838. };
  25839. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  25840. };
  25841. /**
  25842. * Creates a ground mesh.
  25843. * Please consider using the same method from the MeshBuilder class instead.
  25844. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  25845. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  25846. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25847. */
  25848. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  25849. var options = {
  25850. width: width,
  25851. height: height,
  25852. subdivisions: subdivisions,
  25853. updatable: updatable
  25854. };
  25855. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  25856. };
  25857. /**
  25858. * Creates a tiled ground mesh.
  25859. * Please consider using the same method from the MeshBuilder class instead.
  25860. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  25861. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  25862. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  25863. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  25864. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  25865. * numbers of subdivisions on the ground width and height of each tile.
  25866. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25867. */
  25868. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  25869. var options = {
  25870. xmin: xmin,
  25871. zmin: zmin,
  25872. xmax: xmax,
  25873. zmax: zmax,
  25874. subdivisions: subdivisions,
  25875. precision: precision,
  25876. updatable: updatable
  25877. };
  25878. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  25879. };
  25880. /**
  25881. * Creates a ground mesh from a height map.
  25882. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  25883. * Please consider using the same method from the MeshBuilder class instead.
  25884. * The parameter `url` sets the URL of the height map image resource.
  25885. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  25886. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  25887. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  25888. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  25889. * 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).
  25890. * This function is passed the newly built mesh :
  25891. * ```javascript
  25892. * function(mesh) { // do things
  25893. * return; }
  25894. * ```
  25895. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25896. */
  25897. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  25898. var options = {
  25899. width: width,
  25900. height: height,
  25901. subdivisions: subdivisions,
  25902. minHeight: minHeight,
  25903. maxHeight: maxHeight,
  25904. updatable: updatable,
  25905. onReady: onReady
  25906. };
  25907. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  25908. };
  25909. /**
  25910. * Creates a tube mesh.
  25911. * 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.
  25912. * Please consider using the same method from the MeshBuilder class instead.
  25913. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  25914. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  25915. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  25916. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  25917. * 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.
  25918. * It must return a radius value (positive float) :
  25919. * ```javascript
  25920. * var radiusFunction = function(i, distance) {
  25921. * // do things
  25922. * return radius; }
  25923. * ```
  25924. * 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
  25925. * 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
  25926. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25927. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25928. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25929. */
  25930. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  25931. var options = {
  25932. path: path,
  25933. radius: radius,
  25934. tessellation: tessellation,
  25935. radiusFunction: radiusFunction,
  25936. arc: 1,
  25937. cap: cap,
  25938. updatable: updatable,
  25939. sideOrientation: sideOrientation,
  25940. instance: instance
  25941. };
  25942. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  25943. };
  25944. /**
  25945. * Creates a polyhedron mesh.
  25946. * Please consider using the same method from the MeshBuilder class instead.
  25947. * 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
  25948. * to choose the wanted type.
  25949. * The parameter `size` (positive float, default 1) sets the polygon size.
  25950. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  25951. * 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`.
  25952. * 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
  25953. * 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)`).
  25954. * 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
  25955. * 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.
  25956. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25957. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25958. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25959. */
  25960. Mesh.CreatePolyhedron = function (name, options, scene) {
  25961. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  25962. };
  25963. /**
  25964. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  25965. * Please consider using the same method from the MeshBuilder class instead.
  25966. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  25967. * 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`).
  25968. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  25969. * 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.
  25970. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25971. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25972. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25973. */
  25974. Mesh.CreateIcoSphere = function (name, options, scene) {
  25975. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  25976. };
  25977. /**
  25978. * Creates a decal mesh.
  25979. * Please consider using the same method from the MeshBuilder class instead.
  25980. * 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.
  25981. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  25982. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  25983. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  25984. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  25985. */
  25986. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  25987. var options = {
  25988. position: position,
  25989. normal: normal,
  25990. size: size,
  25991. angle: angle
  25992. };
  25993. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  25994. };
  25995. // Skeletons
  25996. /**
  25997. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25998. */
  25999. Mesh.prototype.setPositionsForCPUSkinning = function () {
  26000. if (!this._sourcePositions) {
  26001. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26002. if (!source) {
  26003. return this._sourcePositions;
  26004. }
  26005. this._sourcePositions = new Float32Array(source);
  26006. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  26007. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  26008. }
  26009. }
  26010. return this._sourcePositions;
  26011. };
  26012. /**
  26013. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  26014. */
  26015. Mesh.prototype.setNormalsForCPUSkinning = function () {
  26016. if (!this._sourceNormals) {
  26017. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26018. if (!source) {
  26019. return this._sourceNormals;
  26020. }
  26021. this._sourceNormals = new Float32Array(source);
  26022. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  26023. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  26024. }
  26025. }
  26026. return this._sourceNormals;
  26027. };
  26028. /**
  26029. * Updates the vertex buffer by applying transformation from the bones.
  26030. * Returns the Mesh.
  26031. *
  26032. * @param {skeleton} skeleton to apply
  26033. */
  26034. Mesh.prototype.applySkeleton = function (skeleton) {
  26035. if (!this.geometry) {
  26036. return this;
  26037. }
  26038. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  26039. return this;
  26040. }
  26041. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  26042. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26043. return this;
  26044. }
  26045. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26046. return this;
  26047. }
  26048. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26049. return this;
  26050. }
  26051. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26052. return this;
  26053. }
  26054. if (!this._sourcePositions) {
  26055. var submeshes = this.subMeshes.slice();
  26056. this.setPositionsForCPUSkinning();
  26057. this.subMeshes = submeshes;
  26058. }
  26059. if (!this._sourceNormals) {
  26060. this.setNormalsForCPUSkinning();
  26061. }
  26062. // positionsData checks for not being Float32Array will only pass at most once
  26063. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26064. if (!positionsData) {
  26065. return this;
  26066. }
  26067. if (!(positionsData instanceof Float32Array)) {
  26068. positionsData = new Float32Array(positionsData);
  26069. }
  26070. // normalsData checks for not being Float32Array will only pass at most once
  26071. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26072. if (!normalsData) {
  26073. return this;
  26074. }
  26075. if (!(normalsData instanceof Float32Array)) {
  26076. normalsData = new Float32Array(normalsData);
  26077. }
  26078. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  26079. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  26080. if (!matricesWeightsData || !matricesIndicesData) {
  26081. return this;
  26082. }
  26083. var needExtras = this.numBoneInfluencers > 4;
  26084. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  26085. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  26086. var skeletonMatrices = skeleton.getTransformMatrices(this);
  26087. var tempVector3 = BABYLON.Vector3.Zero();
  26088. var finalMatrix = new BABYLON.Matrix();
  26089. var tempMatrix = new BABYLON.Matrix();
  26090. var matWeightIdx = 0;
  26091. var inf;
  26092. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  26093. var weight;
  26094. for (inf = 0; inf < 4; inf++) {
  26095. weight = matricesWeightsData[matWeightIdx + inf];
  26096. if (weight > 0) {
  26097. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  26098. finalMatrix.addToSelf(tempMatrix);
  26099. }
  26100. else
  26101. break;
  26102. }
  26103. if (needExtras) {
  26104. for (inf = 0; inf < 4; inf++) {
  26105. weight = matricesWeightsExtraData[matWeightIdx + inf];
  26106. if (weight > 0) {
  26107. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  26108. finalMatrix.addToSelf(tempMatrix);
  26109. }
  26110. else
  26111. break;
  26112. }
  26113. }
  26114. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  26115. tempVector3.toArray(positionsData, index);
  26116. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  26117. tempVector3.toArray(normalsData, index);
  26118. finalMatrix.reset();
  26119. }
  26120. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  26121. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  26122. return this;
  26123. };
  26124. // Tools
  26125. /**
  26126. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  26127. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  26128. */
  26129. Mesh.MinMax = function (meshes) {
  26130. var minVector = null;
  26131. var maxVector = null;
  26132. meshes.forEach(function (mesh, index, array) {
  26133. var boundingInfo = mesh.getBoundingInfo();
  26134. var boundingBox = boundingInfo.boundingBox;
  26135. if (!minVector || !maxVector) {
  26136. minVector = boundingBox.minimumWorld;
  26137. maxVector = boundingBox.maximumWorld;
  26138. }
  26139. else {
  26140. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  26141. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  26142. }
  26143. });
  26144. if (!minVector || !maxVector) {
  26145. return {
  26146. min: BABYLON.Vector3.Zero(),
  26147. max: BABYLON.Vector3.Zero()
  26148. };
  26149. }
  26150. return {
  26151. min: minVector,
  26152. max: maxVector
  26153. };
  26154. };
  26155. /**
  26156. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  26157. */
  26158. Mesh.Center = function (meshesOrMinMaxVector) {
  26159. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  26160. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  26161. };
  26162. /**
  26163. * Merge the array of meshes into a single mesh for performance reasons.
  26164. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  26165. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  26166. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  26167. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  26168. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  26169. */
  26170. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  26171. if (disposeSource === void 0) { disposeSource = true; }
  26172. var index;
  26173. if (!allow32BitsIndices) {
  26174. var totalVertices = 0;
  26175. // Counting vertices
  26176. for (index = 0; index < meshes.length; index++) {
  26177. if (meshes[index]) {
  26178. totalVertices += meshes[index].getTotalVertices();
  26179. if (totalVertices > 65536) {
  26180. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  26181. return null;
  26182. }
  26183. }
  26184. }
  26185. }
  26186. // Merge
  26187. var vertexData = null;
  26188. var otherVertexData;
  26189. var indiceArray = new Array();
  26190. var source = null;
  26191. for (index = 0; index < meshes.length; index++) {
  26192. if (meshes[index]) {
  26193. meshes[index].computeWorldMatrix(true);
  26194. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  26195. otherVertexData.transform(meshes[index].getWorldMatrix());
  26196. if (vertexData) {
  26197. vertexData.merge(otherVertexData);
  26198. }
  26199. else {
  26200. vertexData = otherVertexData;
  26201. source = meshes[index];
  26202. }
  26203. if (subdivideWithSubMeshes) {
  26204. indiceArray.push(meshes[index].getTotalIndices());
  26205. }
  26206. }
  26207. }
  26208. source = source;
  26209. if (!meshSubclass) {
  26210. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  26211. }
  26212. vertexData.applyToMesh(meshSubclass);
  26213. // Setting properties
  26214. meshSubclass.material = source.material;
  26215. meshSubclass.checkCollisions = source.checkCollisions;
  26216. // Cleaning
  26217. if (disposeSource) {
  26218. for (index = 0; index < meshes.length; index++) {
  26219. if (meshes[index]) {
  26220. meshes[index].dispose();
  26221. }
  26222. }
  26223. }
  26224. // Subdivide
  26225. if (subdivideWithSubMeshes) {
  26226. //-- Suppresions du submesh global
  26227. meshSubclass.releaseSubMeshes();
  26228. index = 0;
  26229. var offset = 0;
  26230. //-- aplique la subdivision en fonction du tableau d'indices
  26231. while (index < indiceArray.length) {
  26232. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  26233. offset += indiceArray[index];
  26234. index++;
  26235. }
  26236. }
  26237. return meshSubclass;
  26238. };
  26239. // Consts
  26240. Mesh._FRONTSIDE = 0;
  26241. Mesh._BACKSIDE = 1;
  26242. Mesh._DOUBLESIDE = 2;
  26243. Mesh._DEFAULTSIDE = 0;
  26244. Mesh._NO_CAP = 0;
  26245. Mesh._CAP_START = 1;
  26246. Mesh._CAP_END = 2;
  26247. Mesh._CAP_ALL = 3;
  26248. return Mesh;
  26249. }(BABYLON.AbstractMesh));
  26250. BABYLON.Mesh = Mesh;
  26251. })(BABYLON || (BABYLON = {}));
  26252. //# sourceMappingURL=babylon.mesh.js.map
  26253. var BABYLON;
  26254. (function (BABYLON) {
  26255. var BaseSubMesh = /** @class */ (function () {
  26256. function BaseSubMesh() {
  26257. }
  26258. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  26259. get: function () {
  26260. return this._materialEffect;
  26261. },
  26262. enumerable: true,
  26263. configurable: true
  26264. });
  26265. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  26266. if (defines === void 0) { defines = null; }
  26267. if (this._materialEffect === effect) {
  26268. if (!effect) {
  26269. this._materialDefines = null;
  26270. }
  26271. return;
  26272. }
  26273. this._materialDefines = defines;
  26274. this._materialEffect = effect;
  26275. };
  26276. return BaseSubMesh;
  26277. }());
  26278. BABYLON.BaseSubMesh = BaseSubMesh;
  26279. var SubMesh = /** @class */ (function (_super) {
  26280. __extends(SubMesh, _super);
  26281. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  26282. if (createBoundingBox === void 0) { createBoundingBox = true; }
  26283. var _this = _super.call(this) || this;
  26284. _this.materialIndex = materialIndex;
  26285. _this.verticesStart = verticesStart;
  26286. _this.verticesCount = verticesCount;
  26287. _this.indexStart = indexStart;
  26288. _this.indexCount = indexCount;
  26289. _this._renderId = 0;
  26290. _this._mesh = mesh;
  26291. _this._renderingMesh = renderingMesh || mesh;
  26292. mesh.subMeshes.push(_this);
  26293. _this._trianglePlanes = [];
  26294. _this._id = mesh.subMeshes.length - 1;
  26295. if (createBoundingBox) {
  26296. _this.refreshBoundingInfo();
  26297. mesh.computeWorldMatrix(true);
  26298. }
  26299. return _this;
  26300. }
  26301. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  26302. if (createBoundingBox === void 0) { createBoundingBox = true; }
  26303. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  26304. };
  26305. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  26306. get: function () {
  26307. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  26308. },
  26309. enumerable: true,
  26310. configurable: true
  26311. });
  26312. /**
  26313. * Returns the submesh BoudingInfo object.
  26314. */
  26315. SubMesh.prototype.getBoundingInfo = function () {
  26316. if (this.IsGlobal) {
  26317. return this._mesh.getBoundingInfo();
  26318. }
  26319. return this._boundingInfo;
  26320. };
  26321. /**
  26322. * Sets the submesh BoundingInfo.
  26323. * Return the SubMesh.
  26324. */
  26325. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  26326. this._boundingInfo = boundingInfo;
  26327. return this;
  26328. };
  26329. /**
  26330. * Returns the mesh of the current submesh.
  26331. */
  26332. SubMesh.prototype.getMesh = function () {
  26333. return this._mesh;
  26334. };
  26335. /**
  26336. * Returns the rendering mesh of the submesh.
  26337. */
  26338. SubMesh.prototype.getRenderingMesh = function () {
  26339. return this._renderingMesh;
  26340. };
  26341. /**
  26342. * Returns the submesh material.
  26343. */
  26344. SubMesh.prototype.getMaterial = function () {
  26345. var rootMaterial = this._renderingMesh.material;
  26346. if (rootMaterial && rootMaterial.getSubMaterial) {
  26347. var multiMaterial = rootMaterial;
  26348. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  26349. if (this._currentMaterial !== effectiveMaterial) {
  26350. this._currentMaterial = effectiveMaterial;
  26351. this._materialDefines = null;
  26352. }
  26353. return effectiveMaterial;
  26354. }
  26355. if (!rootMaterial) {
  26356. return this._mesh.getScene().defaultMaterial;
  26357. }
  26358. return rootMaterial;
  26359. };
  26360. // Methods
  26361. /**
  26362. * Sets a new updated BoundingInfo object to the submesh.
  26363. * Returns the SubMesh.
  26364. */
  26365. SubMesh.prototype.refreshBoundingInfo = function () {
  26366. this._lastColliderWorldVertices = null;
  26367. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  26368. return this;
  26369. }
  26370. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26371. if (!data) {
  26372. this._boundingInfo = this._mesh.getBoundingInfo();
  26373. return this;
  26374. }
  26375. var indices = this._renderingMesh.getIndices();
  26376. var extend;
  26377. //is this the only submesh?
  26378. if (this.indexStart === 0 && this.indexCount === indices.length) {
  26379. var boundingInfo = this._renderingMesh.getBoundingInfo();
  26380. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  26381. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  26382. }
  26383. else {
  26384. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  26385. }
  26386. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26387. return this;
  26388. };
  26389. SubMesh.prototype._checkCollision = function (collider) {
  26390. var boundingInfo = this._renderingMesh.getBoundingInfo();
  26391. return boundingInfo._checkCollision(collider);
  26392. };
  26393. /**
  26394. * Updates the submesh BoundingInfo.
  26395. * Returns the Submesh.
  26396. */
  26397. SubMesh.prototype.updateBoundingInfo = function (world) {
  26398. var boundingInfo = this.getBoundingInfo();
  26399. if (!boundingInfo) {
  26400. this.refreshBoundingInfo();
  26401. boundingInfo = this.getBoundingInfo();
  26402. }
  26403. boundingInfo.update(world);
  26404. return this;
  26405. };
  26406. /**
  26407. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  26408. * Boolean returned.
  26409. */
  26410. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  26411. var boundingInfo = this.getBoundingInfo();
  26412. if (!boundingInfo) {
  26413. return false;
  26414. }
  26415. return boundingInfo.isInFrustum(frustumPlanes);
  26416. };
  26417. /**
  26418. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  26419. * Boolean returned.
  26420. */
  26421. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  26422. var boundingInfo = this.getBoundingInfo();
  26423. if (!boundingInfo) {
  26424. return false;
  26425. }
  26426. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  26427. };
  26428. /**
  26429. * Renders the submesh.
  26430. * Returns it.
  26431. */
  26432. SubMesh.prototype.render = function (enableAlphaMode) {
  26433. this._renderingMesh.render(this, enableAlphaMode);
  26434. return this;
  26435. };
  26436. /**
  26437. * Returns a new Index Buffer.
  26438. * Type returned : WebGLBuffer.
  26439. */
  26440. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  26441. if (!this._linesIndexBuffer) {
  26442. var linesIndices = [];
  26443. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  26444. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  26445. }
  26446. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  26447. this.linesIndexCount = linesIndices.length;
  26448. }
  26449. return this._linesIndexBuffer;
  26450. };
  26451. /**
  26452. * True is the passed Ray intersects the submesh bounding box.
  26453. * Boolean returned.
  26454. */
  26455. SubMesh.prototype.canIntersects = function (ray) {
  26456. var boundingInfo = this.getBoundingInfo();
  26457. if (!boundingInfo) {
  26458. return false;
  26459. }
  26460. return ray.intersectsBox(boundingInfo.boundingBox);
  26461. };
  26462. /**
  26463. * Returns an object IntersectionInfo.
  26464. */
  26465. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  26466. var intersectInfo = null;
  26467. // LineMesh first as it's also a Mesh...
  26468. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  26469. var lineMesh = this._mesh;
  26470. // Line test
  26471. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  26472. var p0 = positions[indices[index]];
  26473. var p1 = positions[indices[index + 1]];
  26474. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  26475. if (length < 0) {
  26476. continue;
  26477. }
  26478. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  26479. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  26480. if (fastCheck) {
  26481. break;
  26482. }
  26483. }
  26484. }
  26485. }
  26486. else {
  26487. // Triangles test
  26488. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  26489. var p0 = positions[indices[index]];
  26490. var p1 = positions[indices[index + 1]];
  26491. var p2 = positions[indices[index + 2]];
  26492. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  26493. if (currentIntersectInfo) {
  26494. if (currentIntersectInfo.distance < 0) {
  26495. continue;
  26496. }
  26497. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  26498. intersectInfo = currentIntersectInfo;
  26499. intersectInfo.faceId = index / 3;
  26500. if (fastCheck) {
  26501. break;
  26502. }
  26503. }
  26504. }
  26505. }
  26506. }
  26507. return intersectInfo;
  26508. };
  26509. SubMesh.prototype._rebuild = function () {
  26510. if (this._linesIndexBuffer) {
  26511. this._linesIndexBuffer = null;
  26512. }
  26513. };
  26514. // Clone
  26515. /**
  26516. * Creates a new Submesh from the passed Mesh.
  26517. */
  26518. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  26519. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  26520. if (!this.IsGlobal) {
  26521. var boundingInfo = this.getBoundingInfo();
  26522. if (!boundingInfo) {
  26523. return result;
  26524. }
  26525. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  26526. }
  26527. return result;
  26528. };
  26529. // Dispose
  26530. /**
  26531. * Disposes the Submesh.
  26532. * Returns nothing.
  26533. */
  26534. SubMesh.prototype.dispose = function () {
  26535. if (this._linesIndexBuffer) {
  26536. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  26537. this._linesIndexBuffer = null;
  26538. }
  26539. // Remove from mesh
  26540. var index = this._mesh.subMeshes.indexOf(this);
  26541. this._mesh.subMeshes.splice(index, 1);
  26542. };
  26543. // Statics
  26544. /**
  26545. * Creates a new Submesh from the passed parameters :
  26546. * - materialIndex (integer) : the index of the main mesh material.
  26547. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  26548. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  26549. * - mesh (Mesh) : the main mesh to create the submesh from.
  26550. * - renderingMesh (optional Mesh) : rendering mesh.
  26551. */
  26552. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  26553. var minVertexIndex = Number.MAX_VALUE;
  26554. var maxVertexIndex = -Number.MAX_VALUE;
  26555. renderingMesh = (renderingMesh || mesh);
  26556. var indices = renderingMesh.getIndices();
  26557. for (var index = startIndex; index < startIndex + indexCount; index++) {
  26558. var vertexIndex = indices[index];
  26559. if (vertexIndex < minVertexIndex)
  26560. minVertexIndex = vertexIndex;
  26561. if (vertexIndex > maxVertexIndex)
  26562. maxVertexIndex = vertexIndex;
  26563. }
  26564. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  26565. };
  26566. return SubMesh;
  26567. }(BaseSubMesh));
  26568. BABYLON.SubMesh = SubMesh;
  26569. })(BABYLON || (BABYLON = {}));
  26570. //# sourceMappingURL=babylon.subMesh.js.map
  26571. var BABYLON;
  26572. (function (BABYLON) {
  26573. var EffectFallbacks = /** @class */ (function () {
  26574. function EffectFallbacks() {
  26575. this._defines = {};
  26576. this._currentRank = 32;
  26577. this._maxRank = -1;
  26578. }
  26579. EffectFallbacks.prototype.unBindMesh = function () {
  26580. this._mesh = null;
  26581. };
  26582. EffectFallbacks.prototype.addFallback = function (rank, define) {
  26583. if (!this._defines[rank]) {
  26584. if (rank < this._currentRank) {
  26585. this._currentRank = rank;
  26586. }
  26587. if (rank > this._maxRank) {
  26588. this._maxRank = rank;
  26589. }
  26590. this._defines[rank] = new Array();
  26591. }
  26592. this._defines[rank].push(define);
  26593. };
  26594. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  26595. this._mesh = mesh;
  26596. if (rank < this._currentRank) {
  26597. this._currentRank = rank;
  26598. }
  26599. if (rank > this._maxRank) {
  26600. this._maxRank = rank;
  26601. }
  26602. };
  26603. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  26604. get: function () {
  26605. return this._currentRank <= this._maxRank;
  26606. },
  26607. enumerable: true,
  26608. configurable: true
  26609. });
  26610. EffectFallbacks.prototype.reduce = function (currentDefines) {
  26611. // First we try to switch to CPU skinning
  26612. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  26613. this._mesh.computeBonesUsingShaders = false;
  26614. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  26615. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  26616. var scene = this._mesh.getScene();
  26617. for (var index = 0; index < scene.meshes.length; index++) {
  26618. var otherMesh = scene.meshes[index];
  26619. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  26620. otherMesh.computeBonesUsingShaders = false;
  26621. }
  26622. }
  26623. }
  26624. else {
  26625. var currentFallbacks = this._defines[this._currentRank];
  26626. if (currentFallbacks) {
  26627. for (var index = 0; index < currentFallbacks.length; index++) {
  26628. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  26629. }
  26630. }
  26631. this._currentRank++;
  26632. }
  26633. return currentDefines;
  26634. };
  26635. return EffectFallbacks;
  26636. }());
  26637. BABYLON.EffectFallbacks = EffectFallbacks;
  26638. var EffectCreationOptions = /** @class */ (function () {
  26639. function EffectCreationOptions() {
  26640. }
  26641. return EffectCreationOptions;
  26642. }());
  26643. BABYLON.EffectCreationOptions = EffectCreationOptions;
  26644. var Effect = /** @class */ (function () {
  26645. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  26646. if (samplers === void 0) { samplers = null; }
  26647. if (defines === void 0) { defines = null; }
  26648. if (fallbacks === void 0) { fallbacks = null; }
  26649. if (onCompiled === void 0) { onCompiled = null; }
  26650. if (onError === void 0) { onError = null; }
  26651. var _this = this;
  26652. this.uniqueId = 0;
  26653. this.onCompileObservable = new BABYLON.Observable();
  26654. this.onErrorObservable = new BABYLON.Observable();
  26655. this.onBindObservable = new BABYLON.Observable();
  26656. this._uniformBuffersNames = {};
  26657. this._isReady = false;
  26658. this._compilationError = "";
  26659. this.name = baseName;
  26660. if (attributesNamesOrOptions.attributes) {
  26661. var options = attributesNamesOrOptions;
  26662. this._engine = uniformsNamesOrEngine;
  26663. this._attributesNames = options.attributes;
  26664. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  26665. this._samplers = options.samplers;
  26666. this.defines = options.defines;
  26667. this.onError = options.onError;
  26668. this.onCompiled = options.onCompiled;
  26669. this._fallbacks = options.fallbacks;
  26670. this._indexParameters = options.indexParameters;
  26671. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  26672. if (options.uniformBuffersNames) {
  26673. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  26674. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  26675. }
  26676. }
  26677. }
  26678. else {
  26679. this._engine = engine;
  26680. this.defines = defines;
  26681. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  26682. this._samplers = samplers;
  26683. this._attributesNames = attributesNamesOrOptions;
  26684. this.onError = onError;
  26685. this.onCompiled = onCompiled;
  26686. this._indexParameters = indexParameters;
  26687. this._fallbacks = fallbacks;
  26688. }
  26689. this.uniqueId = Effect._uniqueIdSeed++;
  26690. var vertexSource;
  26691. var fragmentSource;
  26692. if (baseName.vertexElement) {
  26693. vertexSource = document.getElementById(baseName.vertexElement);
  26694. if (!vertexSource) {
  26695. vertexSource = baseName.vertexElement;
  26696. }
  26697. }
  26698. else {
  26699. vertexSource = baseName.vertex || baseName;
  26700. }
  26701. if (baseName.fragmentElement) {
  26702. fragmentSource = document.getElementById(baseName.fragmentElement);
  26703. if (!fragmentSource) {
  26704. fragmentSource = baseName.fragmentElement;
  26705. }
  26706. }
  26707. else {
  26708. fragmentSource = baseName.fragment || baseName;
  26709. }
  26710. this._loadVertexShader(vertexSource, function (vertexCode) {
  26711. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  26712. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  26713. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  26714. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  26715. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  26716. if (baseName) {
  26717. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  26718. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  26719. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  26720. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  26721. }
  26722. else {
  26723. _this._vertexSourceCode = migratedVertexCode;
  26724. _this._fragmentSourceCode = migratedFragmentCode;
  26725. }
  26726. _this._prepareEffect();
  26727. });
  26728. });
  26729. });
  26730. });
  26731. });
  26732. });
  26733. }
  26734. Object.defineProperty(Effect.prototype, "key", {
  26735. get: function () {
  26736. return this._key;
  26737. },
  26738. enumerable: true,
  26739. configurable: true
  26740. });
  26741. // Properties
  26742. Effect.prototype.isReady = function () {
  26743. return this._isReady;
  26744. };
  26745. Effect.prototype.getEngine = function () {
  26746. return this._engine;
  26747. };
  26748. Effect.prototype.getProgram = function () {
  26749. return this._program;
  26750. };
  26751. Effect.prototype.getAttributesNames = function () {
  26752. return this._attributesNames;
  26753. };
  26754. Effect.prototype.getAttributeLocation = function (index) {
  26755. return this._attributes[index];
  26756. };
  26757. Effect.prototype.getAttributeLocationByName = function (name) {
  26758. var index = this._attributesNames.indexOf(name);
  26759. return this._attributes[index];
  26760. };
  26761. Effect.prototype.getAttributesCount = function () {
  26762. return this._attributes.length;
  26763. };
  26764. Effect.prototype.getUniformIndex = function (uniformName) {
  26765. return this._uniformsNames.indexOf(uniformName);
  26766. };
  26767. Effect.prototype.getUniform = function (uniformName) {
  26768. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  26769. };
  26770. Effect.prototype.getSamplers = function () {
  26771. return this._samplers;
  26772. };
  26773. Effect.prototype.getCompilationError = function () {
  26774. return this._compilationError;
  26775. };
  26776. // Methods
  26777. Effect.prototype.executeWhenCompiled = function (func) {
  26778. if (this.isReady()) {
  26779. func(this);
  26780. return;
  26781. }
  26782. this.onCompileObservable.add(function (effect) {
  26783. func(effect);
  26784. });
  26785. };
  26786. Effect.prototype._loadVertexShader = function (vertex, callback) {
  26787. if (BABYLON.Tools.IsWindowObjectExist()) {
  26788. // DOM element ?
  26789. if (vertex instanceof HTMLElement) {
  26790. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  26791. callback(vertexCode);
  26792. return;
  26793. }
  26794. }
  26795. // Base64 encoded ?
  26796. if (vertex.substr(0, 7) === "base64:") {
  26797. var vertexBinary = window.atob(vertex.substr(7));
  26798. callback(vertexBinary);
  26799. return;
  26800. }
  26801. // Is in local store ?
  26802. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  26803. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  26804. return;
  26805. }
  26806. var vertexShaderUrl;
  26807. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  26808. vertexShaderUrl = vertex;
  26809. }
  26810. else {
  26811. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  26812. }
  26813. // Vertex shader
  26814. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  26815. };
  26816. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  26817. if (BABYLON.Tools.IsWindowObjectExist()) {
  26818. // DOM element ?
  26819. if (fragment instanceof HTMLElement) {
  26820. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  26821. callback(fragmentCode);
  26822. return;
  26823. }
  26824. }
  26825. // Base64 encoded ?
  26826. if (fragment.substr(0, 7) === "base64:") {
  26827. var fragmentBinary = window.atob(fragment.substr(7));
  26828. callback(fragmentBinary);
  26829. return;
  26830. }
  26831. // Is in local store ?
  26832. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  26833. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  26834. return;
  26835. }
  26836. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  26837. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  26838. return;
  26839. }
  26840. var fragmentShaderUrl;
  26841. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  26842. fragmentShaderUrl = fragment;
  26843. }
  26844. else {
  26845. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  26846. }
  26847. // Fragment shader
  26848. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  26849. };
  26850. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  26851. // Rebuild shaders source code
  26852. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  26853. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  26854. vertexCode = prefix + vertexCode;
  26855. fragmentCode = prefix + fragmentCode;
  26856. // Number lines of shaders source code
  26857. var i = 2;
  26858. var regex = /\n/gm;
  26859. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  26860. i = 2;
  26861. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  26862. // Dump shaders name and formatted source code
  26863. if (this.name.vertexElement) {
  26864. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  26865. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  26866. }
  26867. else if (this.name.vertex) {
  26868. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  26869. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  26870. }
  26871. else {
  26872. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  26873. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  26874. }
  26875. };
  26876. ;
  26877. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  26878. var preparedSourceCode = this._processPrecision(sourceCode);
  26879. if (this._engine.webGLVersion == 1) {
  26880. callback(preparedSourceCode);
  26881. return;
  26882. }
  26883. // Already converted
  26884. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  26885. callback(preparedSourceCode.replace("#version 300 es", ""));
  26886. return;
  26887. }
  26888. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  26889. // Remove extensions
  26890. // #extension GL_OES_standard_derivatives : enable
  26891. // #extension GL_EXT_shader_texture_lod : enable
  26892. // #extension GL_EXT_frag_depth : enable
  26893. // #extension GL_EXT_draw_buffers : require
  26894. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  26895. var result = preparedSourceCode.replace(regex, "");
  26896. // Migrate to GLSL v300
  26897. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  26898. result = result.replace(/attribute[ \t]/g, "in ");
  26899. result = result.replace(/[ \t]attribute/g, " in");
  26900. if (isFragment) {
  26901. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  26902. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  26903. result = result.replace(/texture2D\s*\(/g, "texture(");
  26904. result = result.replace(/textureCube\s*\(/g, "texture(");
  26905. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  26906. result = result.replace(/gl_FragColor/g, "glFragColor");
  26907. result = result.replace(/gl_FragData/g, "glFragData");
  26908. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  26909. }
  26910. callback(result);
  26911. };
  26912. Effect.prototype._processIncludes = function (sourceCode, callback) {
  26913. var _this = this;
  26914. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  26915. var match = regex.exec(sourceCode);
  26916. var returnValue = new String(sourceCode);
  26917. while (match != null) {
  26918. var includeFile = match[1];
  26919. // Uniform declaration
  26920. if (includeFile.indexOf("__decl__") !== -1) {
  26921. includeFile = includeFile.replace(/__decl__/, "");
  26922. if (this._engine.supportsUniformBuffers) {
  26923. includeFile = includeFile.replace(/Vertex/, "Ubo");
  26924. includeFile = includeFile.replace(/Fragment/, "Ubo");
  26925. }
  26926. includeFile = includeFile + "Declaration";
  26927. }
  26928. if (Effect.IncludesShadersStore[includeFile]) {
  26929. // Substitution
  26930. var includeContent = Effect.IncludesShadersStore[includeFile];
  26931. if (match[2]) {
  26932. var splits = match[3].split(",");
  26933. for (var index = 0; index < splits.length; index += 2) {
  26934. var source = new RegExp(splits[index], "g");
  26935. var dest = splits[index + 1];
  26936. includeContent = includeContent.replace(source, dest);
  26937. }
  26938. }
  26939. if (match[4]) {
  26940. var indexString = match[5];
  26941. if (indexString.indexOf("..") !== -1) {
  26942. var indexSplits = indexString.split("..");
  26943. var minIndex = parseInt(indexSplits[0]);
  26944. var maxIndex = parseInt(indexSplits[1]);
  26945. var sourceIncludeContent = includeContent.slice(0);
  26946. includeContent = "";
  26947. if (isNaN(maxIndex)) {
  26948. maxIndex = this._indexParameters[indexSplits[1]];
  26949. }
  26950. for (var i = minIndex; i < maxIndex; i++) {
  26951. if (!this._engine.supportsUniformBuffers) {
  26952. // Ubo replacement
  26953. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  26954. return p1 + "{X}";
  26955. });
  26956. }
  26957. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  26958. }
  26959. }
  26960. else {
  26961. if (!this._engine.supportsUniformBuffers) {
  26962. // Ubo replacement
  26963. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  26964. return p1 + "{X}";
  26965. });
  26966. }
  26967. includeContent = includeContent.replace(/\{X\}/g, indexString);
  26968. }
  26969. }
  26970. // Replace
  26971. returnValue = returnValue.replace(match[0], includeContent);
  26972. }
  26973. else {
  26974. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  26975. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  26976. Effect.IncludesShadersStore[includeFile] = fileContent;
  26977. _this._processIncludes(returnValue, callback);
  26978. });
  26979. return;
  26980. }
  26981. match = regex.exec(sourceCode);
  26982. }
  26983. callback(returnValue);
  26984. };
  26985. Effect.prototype._processPrecision = function (source) {
  26986. if (source.indexOf("precision highp float") === -1) {
  26987. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  26988. source = "precision mediump float;\n" + source;
  26989. }
  26990. else {
  26991. source = "precision highp float;\n" + source;
  26992. }
  26993. }
  26994. else {
  26995. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  26996. source = source.replace("precision highp float", "precision mediump float");
  26997. }
  26998. }
  26999. return source;
  27000. };
  27001. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  27002. var _this = this;
  27003. this._isReady = false;
  27004. this._vertexSourceCodeOverride = vertexSourceCode;
  27005. this._fragmentSourceCodeOverride = fragmentSourceCode;
  27006. this.onError = function (effect, error) {
  27007. if (onError) {
  27008. onError(error);
  27009. }
  27010. };
  27011. this.onCompiled = function () {
  27012. var scenes = _this.getEngine().scenes;
  27013. for (var i = 0; i < scenes.length; i++) {
  27014. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27015. }
  27016. if (onCompiled) {
  27017. onCompiled(_this._program);
  27018. }
  27019. };
  27020. this._fallbacks = null;
  27021. this._prepareEffect();
  27022. };
  27023. Effect.prototype._prepareEffect = function () {
  27024. var attributesNames = this._attributesNames;
  27025. var defines = this.defines;
  27026. var fallbacks = this._fallbacks;
  27027. this._valueCache = {};
  27028. var previousProgram = this._program;
  27029. try {
  27030. var engine = this._engine;
  27031. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  27032. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  27033. }
  27034. else {
  27035. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  27036. }
  27037. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  27038. if (engine.supportsUniformBuffers) {
  27039. for (var name in this._uniformBuffersNames) {
  27040. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  27041. }
  27042. }
  27043. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  27044. this._attributes = engine.getAttributes(this._program, attributesNames);
  27045. var index;
  27046. for (index = 0; index < this._samplers.length; index++) {
  27047. var sampler = this.getUniform(this._samplers[index]);
  27048. if (sampler == null) {
  27049. this._samplers.splice(index, 1);
  27050. index--;
  27051. }
  27052. }
  27053. engine.bindSamplers(this);
  27054. this._compilationError = "";
  27055. this._isReady = true;
  27056. if (this.onCompiled) {
  27057. this.onCompiled(this);
  27058. }
  27059. this.onCompileObservable.notifyObservers(this);
  27060. this.onCompileObservable.clear();
  27061. // Unbind mesh reference in fallbacks
  27062. if (this._fallbacks) {
  27063. this._fallbacks.unBindMesh();
  27064. }
  27065. if (previousProgram) {
  27066. this.getEngine()._deleteProgram(previousProgram);
  27067. }
  27068. }
  27069. catch (e) {
  27070. this._compilationError = e.message;
  27071. // Let's go through fallbacks then
  27072. BABYLON.Tools.Error("Unable to compile effect:");
  27073. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  27074. return " " + uniform;
  27075. }));
  27076. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  27077. return " " + attribute;
  27078. }));
  27079. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  27080. BABYLON.Tools.Error("Error: " + this._compilationError);
  27081. if (previousProgram) {
  27082. this._program = previousProgram;
  27083. this._isReady = true;
  27084. if (this.onError) {
  27085. this.onError(this, this._compilationError);
  27086. }
  27087. this.onErrorObservable.notifyObservers(this);
  27088. }
  27089. if (fallbacks && fallbacks.isMoreFallbacks) {
  27090. BABYLON.Tools.Error("Trying next fallback.");
  27091. this.defines = fallbacks.reduce(this.defines);
  27092. this._prepareEffect();
  27093. }
  27094. else {
  27095. if (this.onError) {
  27096. this.onError(this, this._compilationError);
  27097. }
  27098. this.onErrorObservable.notifyObservers(this);
  27099. this.onErrorObservable.clear();
  27100. // Unbind mesh reference in fallbacks
  27101. if (this._fallbacks) {
  27102. this._fallbacks.unBindMesh();
  27103. }
  27104. }
  27105. }
  27106. };
  27107. Object.defineProperty(Effect.prototype, "isSupported", {
  27108. get: function () {
  27109. return this._compilationError === "";
  27110. },
  27111. enumerable: true,
  27112. configurable: true
  27113. });
  27114. Effect.prototype._bindTexture = function (channel, texture) {
  27115. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  27116. };
  27117. Effect.prototype.setTexture = function (channel, texture) {
  27118. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  27119. };
  27120. Effect.prototype.setTextureArray = function (channel, textures) {
  27121. if (this._samplers.indexOf(channel + "Ex") === -1) {
  27122. var initialPos = this._samplers.indexOf(channel);
  27123. for (var index = 1; index < textures.length; index++) {
  27124. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  27125. }
  27126. }
  27127. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  27128. };
  27129. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  27130. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  27131. };
  27132. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  27133. var cache = this._valueCache[uniformName];
  27134. var flag = matrix.updateFlag;
  27135. if (cache !== undefined && cache === flag) {
  27136. return false;
  27137. }
  27138. this._valueCache[uniformName] = flag;
  27139. return true;
  27140. };
  27141. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  27142. var cache = this._valueCache[uniformName];
  27143. if (!cache) {
  27144. cache = [x, y];
  27145. this._valueCache[uniformName] = cache;
  27146. return true;
  27147. }
  27148. var changed = false;
  27149. if (cache[0] !== x) {
  27150. cache[0] = x;
  27151. changed = true;
  27152. }
  27153. if (cache[1] !== y) {
  27154. cache[1] = y;
  27155. changed = true;
  27156. }
  27157. return changed;
  27158. };
  27159. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  27160. var cache = this._valueCache[uniformName];
  27161. if (!cache) {
  27162. cache = [x, y, z];
  27163. this._valueCache[uniformName] = cache;
  27164. return true;
  27165. }
  27166. var changed = false;
  27167. if (cache[0] !== x) {
  27168. cache[0] = x;
  27169. changed = true;
  27170. }
  27171. if (cache[1] !== y) {
  27172. cache[1] = y;
  27173. changed = true;
  27174. }
  27175. if (cache[2] !== z) {
  27176. cache[2] = z;
  27177. changed = true;
  27178. }
  27179. return changed;
  27180. };
  27181. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  27182. var cache = this._valueCache[uniformName];
  27183. if (!cache) {
  27184. cache = [x, y, z, w];
  27185. this._valueCache[uniformName] = cache;
  27186. return true;
  27187. }
  27188. var changed = false;
  27189. if (cache[0] !== x) {
  27190. cache[0] = x;
  27191. changed = true;
  27192. }
  27193. if (cache[1] !== y) {
  27194. cache[1] = y;
  27195. changed = true;
  27196. }
  27197. if (cache[2] !== z) {
  27198. cache[2] = z;
  27199. changed = true;
  27200. }
  27201. if (cache[3] !== w) {
  27202. cache[3] = w;
  27203. changed = true;
  27204. }
  27205. return changed;
  27206. };
  27207. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  27208. var bufferName = this._uniformBuffersNames[name];
  27209. if (Effect._baseCache[bufferName] === buffer) {
  27210. return;
  27211. }
  27212. Effect._baseCache[bufferName] = buffer;
  27213. this._engine.bindUniformBufferBase(buffer, bufferName);
  27214. };
  27215. Effect.prototype.bindUniformBlock = function (blockName, index) {
  27216. this._engine.bindUniformBlock(this._program, blockName, index);
  27217. };
  27218. Effect.prototype.setInt = function (uniformName, value) {
  27219. var cache = this._valueCache[uniformName];
  27220. if (cache !== undefined && cache === value)
  27221. return this;
  27222. this._valueCache[uniformName] = value;
  27223. this._engine.setInt(this.getUniform(uniformName), value);
  27224. return this;
  27225. };
  27226. Effect.prototype.setIntArray = function (uniformName, array) {
  27227. this._valueCache[uniformName] = null;
  27228. this._engine.setIntArray(this.getUniform(uniformName), array);
  27229. return this;
  27230. };
  27231. Effect.prototype.setIntArray2 = function (uniformName, array) {
  27232. this._valueCache[uniformName] = null;
  27233. this._engine.setIntArray2(this.getUniform(uniformName), array);
  27234. return this;
  27235. };
  27236. Effect.prototype.setIntArray3 = function (uniformName, array) {
  27237. this._valueCache[uniformName] = null;
  27238. this._engine.setIntArray3(this.getUniform(uniformName), array);
  27239. return this;
  27240. };
  27241. Effect.prototype.setIntArray4 = function (uniformName, array) {
  27242. this._valueCache[uniformName] = null;
  27243. this._engine.setIntArray4(this.getUniform(uniformName), array);
  27244. return this;
  27245. };
  27246. Effect.prototype.setFloatArray = function (uniformName, array) {
  27247. this._valueCache[uniformName] = null;
  27248. this._engine.setFloatArray(this.getUniform(uniformName), array);
  27249. return this;
  27250. };
  27251. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  27252. this._valueCache[uniformName] = null;
  27253. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  27254. return this;
  27255. };
  27256. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  27257. this._valueCache[uniformName] = null;
  27258. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  27259. return this;
  27260. };
  27261. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  27262. this._valueCache[uniformName] = null;
  27263. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  27264. return this;
  27265. };
  27266. Effect.prototype.setArray = function (uniformName, array) {
  27267. this._valueCache[uniformName] = null;
  27268. this._engine.setArray(this.getUniform(uniformName), array);
  27269. return this;
  27270. };
  27271. Effect.prototype.setArray2 = function (uniformName, array) {
  27272. this._valueCache[uniformName] = null;
  27273. this._engine.setArray2(this.getUniform(uniformName), array);
  27274. return this;
  27275. };
  27276. Effect.prototype.setArray3 = function (uniformName, array) {
  27277. this._valueCache[uniformName] = null;
  27278. this._engine.setArray3(this.getUniform(uniformName), array);
  27279. return this;
  27280. };
  27281. Effect.prototype.setArray4 = function (uniformName, array) {
  27282. this._valueCache[uniformName] = null;
  27283. this._engine.setArray4(this.getUniform(uniformName), array);
  27284. return this;
  27285. };
  27286. Effect.prototype.setMatrices = function (uniformName, matrices) {
  27287. if (!matrices) {
  27288. return this;
  27289. }
  27290. this._valueCache[uniformName] = null;
  27291. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  27292. return this;
  27293. };
  27294. Effect.prototype.setMatrix = function (uniformName, matrix) {
  27295. if (this._cacheMatrix(uniformName, matrix)) {
  27296. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  27297. }
  27298. return this;
  27299. };
  27300. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  27301. this._valueCache[uniformName] = null;
  27302. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  27303. return this;
  27304. };
  27305. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  27306. this._valueCache[uniformName] = null;
  27307. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  27308. return this;
  27309. };
  27310. Effect.prototype.setFloat = function (uniformName, value) {
  27311. var cache = this._valueCache[uniformName];
  27312. if (cache !== undefined && cache === value)
  27313. return this;
  27314. this._valueCache[uniformName] = value;
  27315. this._engine.setFloat(this.getUniform(uniformName), value);
  27316. return this;
  27317. };
  27318. Effect.prototype.setBool = function (uniformName, bool) {
  27319. var cache = this._valueCache[uniformName];
  27320. if (cache !== undefined && cache === bool)
  27321. return this;
  27322. this._valueCache[uniformName] = bool;
  27323. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  27324. return this;
  27325. };
  27326. Effect.prototype.setVector2 = function (uniformName, vector2) {
  27327. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  27328. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  27329. }
  27330. return this;
  27331. };
  27332. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  27333. if (this._cacheFloat2(uniformName, x, y)) {
  27334. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  27335. }
  27336. return this;
  27337. };
  27338. Effect.prototype.setVector3 = function (uniformName, vector3) {
  27339. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  27340. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  27341. }
  27342. return this;
  27343. };
  27344. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  27345. if (this._cacheFloat3(uniformName, x, y, z)) {
  27346. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  27347. }
  27348. return this;
  27349. };
  27350. Effect.prototype.setVector4 = function (uniformName, vector4) {
  27351. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  27352. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  27353. }
  27354. return this;
  27355. };
  27356. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  27357. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  27358. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  27359. }
  27360. return this;
  27361. };
  27362. Effect.prototype.setColor3 = function (uniformName, color3) {
  27363. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  27364. this._engine.setColor3(this.getUniform(uniformName), color3);
  27365. }
  27366. return this;
  27367. };
  27368. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  27369. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  27370. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  27371. }
  27372. return this;
  27373. };
  27374. Effect.ResetCache = function () {
  27375. Effect._baseCache = {};
  27376. };
  27377. Effect._uniqueIdSeed = 0;
  27378. Effect._baseCache = {};
  27379. // Statics
  27380. Effect.ShadersStore = {};
  27381. Effect.IncludesShadersStore = {};
  27382. return Effect;
  27383. }());
  27384. BABYLON.Effect = Effect;
  27385. })(BABYLON || (BABYLON = {}));
  27386. //# sourceMappingURL=babylon.effect.js.map
  27387. var __assign = (this && this.__assign) || Object.assign || function(t) {
  27388. for (var s, i = 1, n = arguments.length; i < n; i++) {
  27389. s = arguments[i];
  27390. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  27391. t[p] = s[p];
  27392. }
  27393. return t;
  27394. };
  27395. var BABYLON;
  27396. (function (BABYLON) {
  27397. var MaterialDefines = /** @class */ (function () {
  27398. function MaterialDefines() {
  27399. this._isDirty = true;
  27400. this._areLightsDirty = true;
  27401. this._areAttributesDirty = true;
  27402. this._areTexturesDirty = true;
  27403. this._areFresnelDirty = true;
  27404. this._areMiscDirty = true;
  27405. this._areImageProcessingDirty = true;
  27406. this._normals = false;
  27407. this._uvs = false;
  27408. this._needNormals = false;
  27409. this._needUVs = false;
  27410. }
  27411. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  27412. get: function () {
  27413. return this._isDirty;
  27414. },
  27415. enumerable: true,
  27416. configurable: true
  27417. });
  27418. MaterialDefines.prototype.markAsProcessed = function () {
  27419. this._isDirty = false;
  27420. this._areAttributesDirty = false;
  27421. this._areTexturesDirty = false;
  27422. this._areFresnelDirty = false;
  27423. this._areLightsDirty = false;
  27424. this._areMiscDirty = false;
  27425. this._areImageProcessingDirty = false;
  27426. };
  27427. MaterialDefines.prototype.markAsUnprocessed = function () {
  27428. this._isDirty = true;
  27429. };
  27430. MaterialDefines.prototype.markAllAsDirty = function () {
  27431. this._areTexturesDirty = true;
  27432. this._areAttributesDirty = true;
  27433. this._areLightsDirty = true;
  27434. this._areFresnelDirty = true;
  27435. this._areMiscDirty = true;
  27436. this._areImageProcessingDirty = true;
  27437. this._isDirty = true;
  27438. };
  27439. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  27440. this._areImageProcessingDirty = true;
  27441. this._isDirty = true;
  27442. };
  27443. MaterialDefines.prototype.markAsLightDirty = function () {
  27444. this._areLightsDirty = true;
  27445. this._isDirty = true;
  27446. };
  27447. MaterialDefines.prototype.markAsAttributesDirty = function () {
  27448. this._areAttributesDirty = true;
  27449. this._isDirty = true;
  27450. };
  27451. MaterialDefines.prototype.markAsTexturesDirty = function () {
  27452. this._areTexturesDirty = true;
  27453. this._isDirty = true;
  27454. };
  27455. MaterialDefines.prototype.markAsFresnelDirty = function () {
  27456. this._areFresnelDirty = true;
  27457. this._isDirty = true;
  27458. };
  27459. MaterialDefines.prototype.markAsMiscDirty = function () {
  27460. this._areMiscDirty = true;
  27461. this._isDirty = true;
  27462. };
  27463. MaterialDefines.prototype.rebuild = function () {
  27464. if (this._keys) {
  27465. delete this._keys;
  27466. }
  27467. this._keys = [];
  27468. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  27469. var key = _a[_i];
  27470. if (key[0] === "_") {
  27471. continue;
  27472. }
  27473. this._keys.push(key);
  27474. }
  27475. };
  27476. MaterialDefines.prototype.isEqual = function (other) {
  27477. if (this._keys.length !== other._keys.length) {
  27478. return false;
  27479. }
  27480. for (var index = 0; index < this._keys.length; index++) {
  27481. var prop = this._keys[index];
  27482. if (this[prop] !== other[prop]) {
  27483. return false;
  27484. }
  27485. }
  27486. return true;
  27487. };
  27488. MaterialDefines.prototype.cloneTo = function (other) {
  27489. if (this._keys.length !== other._keys.length) {
  27490. other._keys = this._keys.slice(0);
  27491. }
  27492. for (var index = 0; index < this._keys.length; index++) {
  27493. var prop = this._keys[index];
  27494. other[prop] = this[prop];
  27495. }
  27496. };
  27497. MaterialDefines.prototype.reset = function () {
  27498. for (var index = 0; index < this._keys.length; index++) {
  27499. var prop = this._keys[index];
  27500. if (typeof (this[prop]) === "number") {
  27501. this[prop] = 0;
  27502. }
  27503. else {
  27504. this[prop] = false;
  27505. }
  27506. }
  27507. };
  27508. MaterialDefines.prototype.toString = function () {
  27509. var result = "";
  27510. for (var index = 0; index < this._keys.length; index++) {
  27511. var prop = this._keys[index];
  27512. var value = this[prop];
  27513. if (typeof (value) === "number") {
  27514. result += "#define " + prop + " " + this[prop] + "\n";
  27515. }
  27516. else if (value) {
  27517. result += "#define " + prop + "\n";
  27518. }
  27519. }
  27520. return result;
  27521. };
  27522. return MaterialDefines;
  27523. }());
  27524. BABYLON.MaterialDefines = MaterialDefines;
  27525. var Material = /** @class */ (function () {
  27526. function Material(name, scene, doNotAdd) {
  27527. this.checkReadyOnEveryCall = false;
  27528. this.checkReadyOnlyOnce = false;
  27529. this.state = "";
  27530. this.alpha = 1.0;
  27531. this._backFaceCulling = true;
  27532. this.doNotSerialize = false;
  27533. this.storeEffectOnSubMeshes = false;
  27534. /**
  27535. * An event triggered when the material is disposed.
  27536. * @type {BABYLON.Observable}
  27537. */
  27538. this.onDisposeObservable = new BABYLON.Observable();
  27539. /**
  27540. * An event triggered when the material is bound.
  27541. * @type {BABYLON.Observable}
  27542. */
  27543. this.onBindObservable = new BABYLON.Observable();
  27544. /**
  27545. * An event triggered when the material is unbound.
  27546. * @type {BABYLON.Observable}
  27547. */
  27548. this.onUnBindObservable = new BABYLON.Observable();
  27549. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  27550. this._needDepthPrePass = false;
  27551. this.disableDepthWrite = false;
  27552. this.forceDepthWrite = false;
  27553. this.separateCullingPass = false;
  27554. this._fogEnabled = true;
  27555. this.pointSize = 1.0;
  27556. this.zOffset = 0;
  27557. this._wasPreviouslyReady = false;
  27558. this._fillMode = Material.TriangleFillMode;
  27559. this.name = name;
  27560. this.id = name || BABYLON.Tools.RandomId();
  27561. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  27562. if (this._scene.useRightHandedSystem) {
  27563. this.sideOrientation = Material.ClockWiseSideOrientation;
  27564. }
  27565. else {
  27566. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  27567. }
  27568. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  27569. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  27570. if (!doNotAdd) {
  27571. this._scene.materials.push(this);
  27572. }
  27573. }
  27574. Object.defineProperty(Material, "TriangleFillMode", {
  27575. get: function () {
  27576. return Material._TriangleFillMode;
  27577. },
  27578. enumerable: true,
  27579. configurable: true
  27580. });
  27581. Object.defineProperty(Material, "WireFrameFillMode", {
  27582. get: function () {
  27583. return Material._WireFrameFillMode;
  27584. },
  27585. enumerable: true,
  27586. configurable: true
  27587. });
  27588. Object.defineProperty(Material, "PointFillMode", {
  27589. get: function () {
  27590. return Material._PointFillMode;
  27591. },
  27592. enumerable: true,
  27593. configurable: true
  27594. });
  27595. Object.defineProperty(Material, "PointListDrawMode", {
  27596. get: function () {
  27597. return Material._PointListDrawMode;
  27598. },
  27599. enumerable: true,
  27600. configurable: true
  27601. });
  27602. Object.defineProperty(Material, "LineListDrawMode", {
  27603. get: function () {
  27604. return Material._LineListDrawMode;
  27605. },
  27606. enumerable: true,
  27607. configurable: true
  27608. });
  27609. Object.defineProperty(Material, "LineLoopDrawMode", {
  27610. get: function () {
  27611. return Material._LineLoopDrawMode;
  27612. },
  27613. enumerable: true,
  27614. configurable: true
  27615. });
  27616. Object.defineProperty(Material, "LineStripDrawMode", {
  27617. get: function () {
  27618. return Material._LineStripDrawMode;
  27619. },
  27620. enumerable: true,
  27621. configurable: true
  27622. });
  27623. Object.defineProperty(Material, "TriangleStripDrawMode", {
  27624. get: function () {
  27625. return Material._TriangleStripDrawMode;
  27626. },
  27627. enumerable: true,
  27628. configurable: true
  27629. });
  27630. Object.defineProperty(Material, "TriangleFanDrawMode", {
  27631. get: function () {
  27632. return Material._TriangleFanDrawMode;
  27633. },
  27634. enumerable: true,
  27635. configurable: true
  27636. });
  27637. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  27638. get: function () {
  27639. return Material._ClockWiseSideOrientation;
  27640. },
  27641. enumerable: true,
  27642. configurable: true
  27643. });
  27644. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  27645. get: function () {
  27646. return Material._CounterClockWiseSideOrientation;
  27647. },
  27648. enumerable: true,
  27649. configurable: true
  27650. });
  27651. Object.defineProperty(Material, "TextureDirtyFlag", {
  27652. get: function () {
  27653. return Material._TextureDirtyFlag;
  27654. },
  27655. enumerable: true,
  27656. configurable: true
  27657. });
  27658. Object.defineProperty(Material, "LightDirtyFlag", {
  27659. get: function () {
  27660. return Material._LightDirtyFlag;
  27661. },
  27662. enumerable: true,
  27663. configurable: true
  27664. });
  27665. Object.defineProperty(Material, "FresnelDirtyFlag", {
  27666. get: function () {
  27667. return Material._FresnelDirtyFlag;
  27668. },
  27669. enumerable: true,
  27670. configurable: true
  27671. });
  27672. Object.defineProperty(Material, "AttributesDirtyFlag", {
  27673. get: function () {
  27674. return Material._AttributesDirtyFlag;
  27675. },
  27676. enumerable: true,
  27677. configurable: true
  27678. });
  27679. Object.defineProperty(Material, "MiscDirtyFlag", {
  27680. get: function () {
  27681. return Material._MiscDirtyFlag;
  27682. },
  27683. enumerable: true,
  27684. configurable: true
  27685. });
  27686. Object.defineProperty(Material.prototype, "backFaceCulling", {
  27687. get: function () {
  27688. return this._backFaceCulling;
  27689. },
  27690. set: function (value) {
  27691. if (this._backFaceCulling === value) {
  27692. return;
  27693. }
  27694. this._backFaceCulling = value;
  27695. this.markAsDirty(Material.TextureDirtyFlag);
  27696. },
  27697. enumerable: true,
  27698. configurable: true
  27699. });
  27700. Object.defineProperty(Material.prototype, "onDispose", {
  27701. set: function (callback) {
  27702. if (this._onDisposeObserver) {
  27703. this.onDisposeObservable.remove(this._onDisposeObserver);
  27704. }
  27705. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27706. },
  27707. enumerable: true,
  27708. configurable: true
  27709. });
  27710. Object.defineProperty(Material.prototype, "onBind", {
  27711. set: function (callback) {
  27712. if (this._onBindObserver) {
  27713. this.onBindObservable.remove(this._onBindObserver);
  27714. }
  27715. this._onBindObserver = this.onBindObservable.add(callback);
  27716. },
  27717. enumerable: true,
  27718. configurable: true
  27719. });
  27720. Object.defineProperty(Material.prototype, "alphaMode", {
  27721. get: function () {
  27722. return this._alphaMode;
  27723. },
  27724. set: function (value) {
  27725. if (this._alphaMode === value) {
  27726. return;
  27727. }
  27728. this._alphaMode = value;
  27729. this.markAsDirty(Material.TextureDirtyFlag);
  27730. },
  27731. enumerable: true,
  27732. configurable: true
  27733. });
  27734. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  27735. get: function () {
  27736. return this._needDepthPrePass;
  27737. },
  27738. set: function (value) {
  27739. if (this._needDepthPrePass === value) {
  27740. return;
  27741. }
  27742. this._needDepthPrePass = value;
  27743. if (this._needDepthPrePass) {
  27744. this.checkReadyOnEveryCall = true;
  27745. }
  27746. },
  27747. enumerable: true,
  27748. configurable: true
  27749. });
  27750. Object.defineProperty(Material.prototype, "fogEnabled", {
  27751. get: function () {
  27752. return this._fogEnabled;
  27753. },
  27754. set: function (value) {
  27755. if (this._fogEnabled === value) {
  27756. return;
  27757. }
  27758. this._fogEnabled = value;
  27759. this.markAsDirty(Material.MiscDirtyFlag);
  27760. },
  27761. enumerable: true,
  27762. configurable: true
  27763. });
  27764. Object.defineProperty(Material.prototype, "wireframe", {
  27765. get: function () {
  27766. return this._fillMode === Material.WireFrameFillMode;
  27767. },
  27768. set: function (value) {
  27769. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  27770. },
  27771. enumerable: true,
  27772. configurable: true
  27773. });
  27774. Object.defineProperty(Material.prototype, "pointsCloud", {
  27775. get: function () {
  27776. return this._fillMode === Material.PointFillMode;
  27777. },
  27778. set: function (value) {
  27779. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  27780. },
  27781. enumerable: true,
  27782. configurable: true
  27783. });
  27784. Object.defineProperty(Material.prototype, "fillMode", {
  27785. get: function () {
  27786. return this._fillMode;
  27787. },
  27788. set: function (value) {
  27789. if (this._fillMode === value) {
  27790. return;
  27791. }
  27792. this._fillMode = value;
  27793. this.markAsDirty(Material.MiscDirtyFlag);
  27794. },
  27795. enumerable: true,
  27796. configurable: true
  27797. });
  27798. /**
  27799. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27800. * subclasses should override adding information pertainent to themselves
  27801. */
  27802. Material.prototype.toString = function (fullDetails) {
  27803. var ret = "Name: " + this.name;
  27804. if (fullDetails) {
  27805. }
  27806. return ret;
  27807. };
  27808. /**
  27809. * Child classes can use it to update shaders
  27810. */
  27811. Material.prototype.getClassName = function () {
  27812. return "Material";
  27813. };
  27814. Object.defineProperty(Material.prototype, "isFrozen", {
  27815. get: function () {
  27816. return this.checkReadyOnlyOnce;
  27817. },
  27818. enumerable: true,
  27819. configurable: true
  27820. });
  27821. Material.prototype.freeze = function () {
  27822. this.checkReadyOnlyOnce = true;
  27823. };
  27824. Material.prototype.unfreeze = function () {
  27825. this.checkReadyOnlyOnce = false;
  27826. };
  27827. Material.prototype.isReady = function (mesh, useInstances) {
  27828. return true;
  27829. };
  27830. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  27831. return false;
  27832. };
  27833. Material.prototype.getEffect = function () {
  27834. return this._effect;
  27835. };
  27836. Material.prototype.getScene = function () {
  27837. return this._scene;
  27838. };
  27839. Material.prototype.needAlphaBlending = function () {
  27840. return (this.alpha < 1.0);
  27841. };
  27842. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  27843. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  27844. };
  27845. Material.prototype.needAlphaTesting = function () {
  27846. return false;
  27847. };
  27848. Material.prototype.getAlphaTestTexture = function () {
  27849. return null;
  27850. };
  27851. Material.prototype.markDirty = function () {
  27852. this._wasPreviouslyReady = false;
  27853. };
  27854. Material.prototype._preBind = function (effect, overrideOrientation) {
  27855. if (overrideOrientation === void 0) { overrideOrientation = null; }
  27856. var engine = this._scene.getEngine();
  27857. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  27858. var reverse = orientation === Material.ClockWiseSideOrientation;
  27859. engine.enableEffect(effect ? effect : this._effect);
  27860. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  27861. return reverse;
  27862. };
  27863. Material.prototype.bind = function (world, mesh) {
  27864. };
  27865. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  27866. };
  27867. Material.prototype.bindOnlyWorldMatrix = function (world) {
  27868. };
  27869. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  27870. sceneUbo.bindToEffect(effect, "Scene");
  27871. };
  27872. Material.prototype.bindView = function (effect) {
  27873. if (!this._useUBO) {
  27874. effect.setMatrix("view", this.getScene().getViewMatrix());
  27875. }
  27876. else {
  27877. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  27878. }
  27879. };
  27880. Material.prototype.bindViewProjection = function (effect) {
  27881. if (!this._useUBO) {
  27882. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  27883. }
  27884. else {
  27885. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  27886. }
  27887. };
  27888. Material.prototype._afterBind = function (mesh) {
  27889. this._scene._cachedMaterial = this;
  27890. if (mesh) {
  27891. this._scene._cachedVisibility = mesh.visibility;
  27892. }
  27893. else {
  27894. this._scene._cachedVisibility = 1;
  27895. }
  27896. if (mesh) {
  27897. this.onBindObservable.notifyObservers(mesh);
  27898. }
  27899. if (this.disableDepthWrite) {
  27900. var engine = this._scene.getEngine();
  27901. this._cachedDepthWriteState = engine.getDepthWrite();
  27902. engine.setDepthWrite(false);
  27903. }
  27904. };
  27905. Material.prototype.unbind = function () {
  27906. this.onUnBindObservable.notifyObservers(this);
  27907. if (this.disableDepthWrite) {
  27908. var engine = this._scene.getEngine();
  27909. engine.setDepthWrite(this._cachedDepthWriteState);
  27910. }
  27911. };
  27912. Material.prototype.getActiveTextures = function () {
  27913. return [];
  27914. };
  27915. Material.prototype.hasTexture = function (texture) {
  27916. return false;
  27917. };
  27918. Material.prototype.clone = function (name) {
  27919. return null;
  27920. };
  27921. Material.prototype.getBindedMeshes = function () {
  27922. var result = new Array();
  27923. for (var index = 0; index < this._scene.meshes.length; index++) {
  27924. var mesh = this._scene.meshes[index];
  27925. if (mesh.material === this) {
  27926. result.push(mesh);
  27927. }
  27928. }
  27929. return result;
  27930. };
  27931. /**
  27932. * Force shader compilation including textures ready check
  27933. */
  27934. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  27935. var _this = this;
  27936. var localOptions = __assign({ alphaTest: null, clipPlane: false }, options);
  27937. var subMesh = new BABYLON.BaseSubMesh();
  27938. var scene = this.getScene();
  27939. var engine = scene.getEngine();
  27940. var checkReady = function () {
  27941. if (!_this._scene || !_this._scene.getEngine()) {
  27942. return;
  27943. }
  27944. if (subMesh._materialDefines) {
  27945. subMesh._materialDefines._renderId = -1;
  27946. }
  27947. var alphaTestState = engine.getAlphaTesting();
  27948. var clipPlaneState = scene.clipPlane;
  27949. engine.setAlphaTesting(localOptions.alphaTest || (!_this.needAlphaBlendingForMesh(mesh) && _this.needAlphaTesting()));
  27950. if (localOptions.clipPlane) {
  27951. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  27952. }
  27953. if (_this.storeEffectOnSubMeshes) {
  27954. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  27955. if (onCompiled) {
  27956. onCompiled(_this);
  27957. }
  27958. }
  27959. else {
  27960. setTimeout(checkReady, 16);
  27961. }
  27962. }
  27963. else {
  27964. if (_this.isReady(mesh)) {
  27965. if (onCompiled) {
  27966. onCompiled(_this);
  27967. }
  27968. }
  27969. else {
  27970. setTimeout(checkReady, 16);
  27971. }
  27972. }
  27973. engine.setAlphaTesting(alphaTestState);
  27974. if (options && options.clipPlane) {
  27975. scene.clipPlane = clipPlaneState;
  27976. }
  27977. };
  27978. checkReady();
  27979. };
  27980. Material.prototype.markAsDirty = function (flag) {
  27981. if (flag & Material.TextureDirtyFlag) {
  27982. this._markAllSubMeshesAsTexturesDirty();
  27983. }
  27984. if (flag & Material.LightDirtyFlag) {
  27985. this._markAllSubMeshesAsLightsDirty();
  27986. }
  27987. if (flag & Material.FresnelDirtyFlag) {
  27988. this._markAllSubMeshesAsFresnelDirty();
  27989. }
  27990. if (flag & Material.AttributesDirtyFlag) {
  27991. this._markAllSubMeshesAsAttributesDirty();
  27992. }
  27993. if (flag & Material.MiscDirtyFlag) {
  27994. this._markAllSubMeshesAsMiscDirty();
  27995. }
  27996. this.getScene().resetCachedMaterial();
  27997. };
  27998. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  27999. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  28000. var mesh = _a[_i];
  28001. if (!mesh.subMeshes) {
  28002. continue;
  28003. }
  28004. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  28005. var subMesh = _c[_b];
  28006. if (subMesh.getMaterial() !== this) {
  28007. continue;
  28008. }
  28009. if (!subMesh._materialDefines) {
  28010. continue;
  28011. }
  28012. func(subMesh._materialDefines);
  28013. }
  28014. }
  28015. };
  28016. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  28017. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  28018. };
  28019. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  28020. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  28021. };
  28022. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  28023. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  28024. };
  28025. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  28026. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  28027. };
  28028. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  28029. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  28030. };
  28031. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  28032. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  28033. };
  28034. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  28035. // Animations
  28036. this.getScene().stopAnimation(this);
  28037. // Remove from scene
  28038. var index = this._scene.materials.indexOf(this);
  28039. if (index >= 0) {
  28040. this._scene.materials.splice(index, 1);
  28041. }
  28042. // Remove from meshes
  28043. for (index = 0; index < this._scene.meshes.length; index++) {
  28044. var mesh = this._scene.meshes[index];
  28045. if (mesh.material === this) {
  28046. mesh.material = null;
  28047. if (mesh.geometry) {
  28048. var geometry = (mesh.geometry);
  28049. if (this.storeEffectOnSubMeshes) {
  28050. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  28051. var subMesh = _a[_i];
  28052. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  28053. if (forceDisposeEffect && subMesh._materialEffect) {
  28054. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  28055. }
  28056. }
  28057. }
  28058. else {
  28059. geometry._releaseVertexArrayObject(this._effect);
  28060. }
  28061. }
  28062. }
  28063. }
  28064. this._uniformBuffer.dispose();
  28065. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  28066. if (forceDisposeEffect && this._effect) {
  28067. if (!this.storeEffectOnSubMeshes) {
  28068. this._scene.getEngine()._releaseEffect(this._effect);
  28069. }
  28070. this._effect = null;
  28071. }
  28072. // Callback
  28073. this.onDisposeObservable.notifyObservers(this);
  28074. this.onDisposeObservable.clear();
  28075. this.onBindObservable.clear();
  28076. this.onUnBindObservable.clear();
  28077. };
  28078. Material.prototype.serialize = function () {
  28079. return BABYLON.SerializationHelper.Serialize(this);
  28080. };
  28081. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  28082. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  28083. multiMaterial.id = parsedMultiMaterial.id;
  28084. if (BABYLON.Tags) {
  28085. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  28086. }
  28087. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  28088. var subMatId = parsedMultiMaterial.materials[matIndex];
  28089. if (subMatId) {
  28090. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  28091. }
  28092. else {
  28093. multiMaterial.subMaterials.push(null);
  28094. }
  28095. }
  28096. return multiMaterial;
  28097. };
  28098. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  28099. if (!parsedMaterial.customType) {
  28100. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  28101. }
  28102. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  28103. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  28104. if (!BABYLON.LegacyPBRMaterial) {
  28105. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  28106. return;
  28107. }
  28108. }
  28109. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  28110. return materialType.Parse(parsedMaterial, scene, rootUrl);
  28111. ;
  28112. };
  28113. // Triangle views
  28114. Material._TriangleFillMode = 0;
  28115. Material._WireFrameFillMode = 1;
  28116. Material._PointFillMode = 2;
  28117. // Draw modes
  28118. Material._PointListDrawMode = 3;
  28119. Material._LineListDrawMode = 4;
  28120. Material._LineLoopDrawMode = 5;
  28121. Material._LineStripDrawMode = 6;
  28122. Material._TriangleStripDrawMode = 7;
  28123. Material._TriangleFanDrawMode = 8;
  28124. Material._ClockWiseSideOrientation = 0;
  28125. Material._CounterClockWiseSideOrientation = 1;
  28126. Material._TextureDirtyFlag = 1;
  28127. Material._LightDirtyFlag = 2;
  28128. Material._FresnelDirtyFlag = 4;
  28129. Material._AttributesDirtyFlag = 8;
  28130. Material._MiscDirtyFlag = 16;
  28131. __decorate([
  28132. BABYLON.serialize()
  28133. ], Material.prototype, "id", void 0);
  28134. __decorate([
  28135. BABYLON.serialize()
  28136. ], Material.prototype, "name", void 0);
  28137. __decorate([
  28138. BABYLON.serialize()
  28139. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  28140. __decorate([
  28141. BABYLON.serialize()
  28142. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  28143. __decorate([
  28144. BABYLON.serialize()
  28145. ], Material.prototype, "state", void 0);
  28146. __decorate([
  28147. BABYLON.serialize()
  28148. ], Material.prototype, "alpha", void 0);
  28149. __decorate([
  28150. BABYLON.serialize("backFaceCulling")
  28151. ], Material.prototype, "_backFaceCulling", void 0);
  28152. __decorate([
  28153. BABYLON.serialize()
  28154. ], Material.prototype, "sideOrientation", void 0);
  28155. __decorate([
  28156. BABYLON.serialize("alphaMode")
  28157. ], Material.prototype, "_alphaMode", void 0);
  28158. __decorate([
  28159. BABYLON.serialize()
  28160. ], Material.prototype, "_needDepthPrePass", void 0);
  28161. __decorate([
  28162. BABYLON.serialize()
  28163. ], Material.prototype, "disableDepthWrite", void 0);
  28164. __decorate([
  28165. BABYLON.serialize()
  28166. ], Material.prototype, "forceDepthWrite", void 0);
  28167. __decorate([
  28168. BABYLON.serialize()
  28169. ], Material.prototype, "separateCullingPass", void 0);
  28170. __decorate([
  28171. BABYLON.serialize("fogEnabled")
  28172. ], Material.prototype, "_fogEnabled", void 0);
  28173. __decorate([
  28174. BABYLON.serialize()
  28175. ], Material.prototype, "pointSize", void 0);
  28176. __decorate([
  28177. BABYLON.serialize()
  28178. ], Material.prototype, "zOffset", void 0);
  28179. __decorate([
  28180. BABYLON.serialize()
  28181. ], Material.prototype, "wireframe", null);
  28182. __decorate([
  28183. BABYLON.serialize()
  28184. ], Material.prototype, "pointsCloud", null);
  28185. __decorate([
  28186. BABYLON.serialize()
  28187. ], Material.prototype, "fillMode", null);
  28188. return Material;
  28189. }());
  28190. BABYLON.Material = Material;
  28191. })(BABYLON || (BABYLON = {}));
  28192. //# sourceMappingURL=babylon.material.js.map
  28193. var BABYLON;
  28194. (function (BABYLON) {
  28195. var UniformBuffer = /** @class */ (function () {
  28196. /**
  28197. * Uniform buffer objects.
  28198. *
  28199. * Handles blocks of uniform on the GPU.
  28200. *
  28201. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  28202. *
  28203. * For more information, please refer to :
  28204. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  28205. */
  28206. function UniformBuffer(engine, data, dynamic) {
  28207. this._engine = engine;
  28208. this._noUBO = !engine.supportsUniformBuffers;
  28209. this._dynamic = dynamic;
  28210. this._data = data || [];
  28211. this._uniformLocations = {};
  28212. this._uniformSizes = {};
  28213. this._uniformLocationPointer = 0;
  28214. this._needSync = false;
  28215. if (this._noUBO) {
  28216. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  28217. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  28218. this.updateFloat = this._updateFloatForEffect;
  28219. this.updateFloat2 = this._updateFloat2ForEffect;
  28220. this.updateFloat3 = this._updateFloat3ForEffect;
  28221. this.updateFloat4 = this._updateFloat4ForEffect;
  28222. this.updateMatrix = this._updateMatrixForEffect;
  28223. this.updateVector3 = this._updateVector3ForEffect;
  28224. this.updateVector4 = this._updateVector4ForEffect;
  28225. this.updateColor3 = this._updateColor3ForEffect;
  28226. this.updateColor4 = this._updateColor4ForEffect;
  28227. }
  28228. else {
  28229. this._engine._uniformBuffers.push(this);
  28230. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  28231. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  28232. this.updateFloat = this._updateFloatForUniform;
  28233. this.updateFloat2 = this._updateFloat2ForUniform;
  28234. this.updateFloat3 = this._updateFloat3ForUniform;
  28235. this.updateFloat4 = this._updateFloat4ForUniform;
  28236. this.updateMatrix = this._updateMatrixForUniform;
  28237. this.updateVector3 = this._updateVector3ForUniform;
  28238. this.updateVector4 = this._updateVector4ForUniform;
  28239. this.updateColor3 = this._updateColor3ForUniform;
  28240. this.updateColor4 = this._updateColor4ForUniform;
  28241. }
  28242. }
  28243. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  28244. // Properties
  28245. /**
  28246. * Indicates if the buffer is using the WebGL2 UBO implementation,
  28247. * or just falling back on setUniformXXX calls.
  28248. */
  28249. get: function () {
  28250. return !this._noUBO;
  28251. },
  28252. enumerable: true,
  28253. configurable: true
  28254. });
  28255. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  28256. /**
  28257. * Indicates if the WebGL underlying uniform buffer is in sync
  28258. * with the javascript cache data.
  28259. */
  28260. get: function () {
  28261. return !this._needSync;
  28262. },
  28263. enumerable: true,
  28264. configurable: true
  28265. });
  28266. /**
  28267. * Indicates if the WebGL underlying uniform buffer is dynamic.
  28268. * Also, a dynamic UniformBuffer will disable cache verification and always
  28269. * update the underlying WebGL uniform buffer to the GPU.
  28270. */
  28271. UniformBuffer.prototype.isDynamic = function () {
  28272. return this._dynamic !== undefined;
  28273. };
  28274. /**
  28275. * The data cache on JS side.
  28276. */
  28277. UniformBuffer.prototype.getData = function () {
  28278. return this._bufferData;
  28279. };
  28280. /**
  28281. * The underlying WebGL Uniform buffer.
  28282. */
  28283. UniformBuffer.prototype.getBuffer = function () {
  28284. return this._buffer;
  28285. };
  28286. /**
  28287. * std140 layout specifies how to align data within an UBO structure.
  28288. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  28289. * for specs.
  28290. */
  28291. UniformBuffer.prototype._fillAlignment = function (size) {
  28292. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  28293. // and 4x4 matrices
  28294. // TODO : change if other types are used
  28295. var alignment;
  28296. if (size <= 2) {
  28297. alignment = size;
  28298. }
  28299. else {
  28300. alignment = 4;
  28301. }
  28302. if ((this._uniformLocationPointer % alignment) !== 0) {
  28303. var oldPointer = this._uniformLocationPointer;
  28304. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  28305. var diff = this._uniformLocationPointer - oldPointer;
  28306. for (var i = 0; i < diff; i++) {
  28307. this._data.push(0);
  28308. }
  28309. }
  28310. };
  28311. /**
  28312. * Adds an uniform in the buffer.
  28313. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  28314. * for the layout to be correct !
  28315. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28316. * @param {number|number[]} size Data size, or data directly.
  28317. */
  28318. UniformBuffer.prototype.addUniform = function (name, size) {
  28319. if (this._noUBO) {
  28320. return;
  28321. }
  28322. if (this._uniformLocations[name] !== undefined) {
  28323. // Already existing uniform
  28324. return;
  28325. }
  28326. // This function must be called in the order of the shader layout !
  28327. // size can be the size of the uniform, or data directly
  28328. var data;
  28329. if (size instanceof Array) {
  28330. data = size;
  28331. size = data.length;
  28332. }
  28333. else {
  28334. size = size;
  28335. data = [];
  28336. // Fill with zeros
  28337. for (var i = 0; i < size; i++) {
  28338. data.push(0);
  28339. }
  28340. }
  28341. this._fillAlignment(size);
  28342. this._uniformSizes[name] = size;
  28343. this._uniformLocations[name] = this._uniformLocationPointer;
  28344. this._uniformLocationPointer += size;
  28345. for (var i = 0; i < size; i++) {
  28346. this._data.push(data[i]);
  28347. }
  28348. this._needSync = true;
  28349. };
  28350. /**
  28351. * Wrapper for addUniform.
  28352. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28353. * @param {Matrix} mat A 4x4 matrix.
  28354. */
  28355. UniformBuffer.prototype.addMatrix = function (name, mat) {
  28356. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  28357. };
  28358. /**
  28359. * Wrapper for addUniform.
  28360. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28361. * @param {number} x
  28362. * @param {number} y
  28363. */
  28364. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  28365. var temp = [x, y];
  28366. this.addUniform(name, temp);
  28367. };
  28368. /**
  28369. * Wrapper for addUniform.
  28370. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28371. * @param {number} x
  28372. * @param {number} y
  28373. * @param {number} z
  28374. */
  28375. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  28376. var temp = [x, y, z];
  28377. this.addUniform(name, temp);
  28378. };
  28379. /**
  28380. * Wrapper for addUniform.
  28381. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28382. * @param {Color3} color
  28383. */
  28384. UniformBuffer.prototype.addColor3 = function (name, color) {
  28385. var temp = new Array();
  28386. color.toArray(temp);
  28387. this.addUniform(name, temp);
  28388. };
  28389. /**
  28390. * Wrapper for addUniform.
  28391. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28392. * @param {Color3} color
  28393. * @param {number} alpha
  28394. */
  28395. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  28396. var temp = new Array();
  28397. color.toArray(temp);
  28398. temp.push(alpha);
  28399. this.addUniform(name, temp);
  28400. };
  28401. /**
  28402. * Wrapper for addUniform.
  28403. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28404. * @param {Vector3} vector
  28405. */
  28406. UniformBuffer.prototype.addVector3 = function (name, vector) {
  28407. var temp = new Array();
  28408. vector.toArray(temp);
  28409. this.addUniform(name, temp);
  28410. };
  28411. /**
  28412. * Wrapper for addUniform.
  28413. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28414. */
  28415. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  28416. this.addUniform(name, 12);
  28417. };
  28418. /**
  28419. * Wrapper for addUniform.
  28420. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28421. */
  28422. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  28423. this.addUniform(name, 8);
  28424. };
  28425. /**
  28426. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  28427. */
  28428. UniformBuffer.prototype.create = function () {
  28429. if (this._noUBO) {
  28430. return;
  28431. }
  28432. if (this._buffer) {
  28433. return; // nothing to do
  28434. }
  28435. // See spec, alignment must be filled as a vec4
  28436. this._fillAlignment(4);
  28437. this._bufferData = new Float32Array(this._data);
  28438. this._rebuild();
  28439. this._needSync = true;
  28440. };
  28441. UniformBuffer.prototype._rebuild = function () {
  28442. if (this._noUBO) {
  28443. return;
  28444. }
  28445. if (this._dynamic) {
  28446. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  28447. }
  28448. else {
  28449. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  28450. }
  28451. };
  28452. /**
  28453. * Updates the WebGL Uniform Buffer on the GPU.
  28454. * If the `dynamic` flag is set to true, no cache comparison is done.
  28455. * Otherwise, the buffer will be updated only if the cache differs.
  28456. */
  28457. UniformBuffer.prototype.update = function () {
  28458. if (!this._buffer) {
  28459. this.create();
  28460. return;
  28461. }
  28462. if (!this._dynamic && !this._needSync) {
  28463. return;
  28464. }
  28465. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  28466. this._needSync = false;
  28467. };
  28468. /**
  28469. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  28470. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  28471. * @param {number[]|Float32Array} data Flattened data
  28472. * @param {number} size Size of the data.
  28473. */
  28474. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  28475. var location = this._uniformLocations[uniformName];
  28476. if (location === undefined) {
  28477. if (this._buffer) {
  28478. // Cannot add an uniform if the buffer is already created
  28479. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  28480. return;
  28481. }
  28482. this.addUniform(uniformName, size);
  28483. location = this._uniformLocations[uniformName];
  28484. }
  28485. if (!this._buffer) {
  28486. this.create();
  28487. }
  28488. if (!this._dynamic) {
  28489. // Cache for static uniform buffers
  28490. var changed = false;
  28491. for (var i = 0; i < size; i++) {
  28492. if (this._bufferData[location + i] !== data[i]) {
  28493. changed = true;
  28494. this._bufferData[location + i] = data[i];
  28495. }
  28496. }
  28497. this._needSync = this._needSync || changed;
  28498. }
  28499. else {
  28500. // No cache for dynamic
  28501. for (var i = 0; i < size; i++) {
  28502. this._bufferData[location + i] = data[i];
  28503. }
  28504. }
  28505. };
  28506. // Update methods
  28507. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  28508. // To match std140, matrix must be realigned
  28509. for (var i = 0; i < 3; i++) {
  28510. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  28511. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  28512. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  28513. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  28514. }
  28515. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  28516. };
  28517. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  28518. this._currentEffect.setMatrix3x3(name, matrix);
  28519. };
  28520. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  28521. this._currentEffect.setMatrix2x2(name, matrix);
  28522. };
  28523. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  28524. // To match std140, matrix must be realigned
  28525. for (var i = 0; i < 2; i++) {
  28526. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  28527. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  28528. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  28529. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  28530. }
  28531. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  28532. };
  28533. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  28534. this._currentEffect.setFloat(name, x);
  28535. };
  28536. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  28537. UniformBuffer._tempBuffer[0] = x;
  28538. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  28539. };
  28540. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  28541. if (suffix === void 0) { suffix = ""; }
  28542. this._currentEffect.setFloat2(name + suffix, x, y);
  28543. };
  28544. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  28545. if (suffix === void 0) { suffix = ""; }
  28546. UniformBuffer._tempBuffer[0] = x;
  28547. UniformBuffer._tempBuffer[1] = y;
  28548. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  28549. };
  28550. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  28551. if (suffix === void 0) { suffix = ""; }
  28552. this._currentEffect.setFloat3(name + suffix, x, y, z);
  28553. };
  28554. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  28555. if (suffix === void 0) { suffix = ""; }
  28556. UniformBuffer._tempBuffer[0] = x;
  28557. UniformBuffer._tempBuffer[1] = y;
  28558. UniformBuffer._tempBuffer[2] = z;
  28559. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28560. };
  28561. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  28562. if (suffix === void 0) { suffix = ""; }
  28563. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  28564. };
  28565. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  28566. if (suffix === void 0) { suffix = ""; }
  28567. UniformBuffer._tempBuffer[0] = x;
  28568. UniformBuffer._tempBuffer[1] = y;
  28569. UniformBuffer._tempBuffer[2] = z;
  28570. UniformBuffer._tempBuffer[3] = w;
  28571. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28572. };
  28573. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  28574. this._currentEffect.setMatrix(name, mat);
  28575. };
  28576. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  28577. this.updateUniform(name, mat.toArray(), 16);
  28578. };
  28579. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  28580. this._currentEffect.setVector3(name, vector);
  28581. };
  28582. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  28583. vector.toArray(UniformBuffer._tempBuffer);
  28584. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28585. };
  28586. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  28587. this._currentEffect.setVector4(name, vector);
  28588. };
  28589. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  28590. vector.toArray(UniformBuffer._tempBuffer);
  28591. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28592. };
  28593. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  28594. if (suffix === void 0) { suffix = ""; }
  28595. this._currentEffect.setColor3(name + suffix, color);
  28596. };
  28597. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  28598. if (suffix === void 0) { suffix = ""; }
  28599. color.toArray(UniformBuffer._tempBuffer);
  28600. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28601. };
  28602. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  28603. if (suffix === void 0) { suffix = ""; }
  28604. this._currentEffect.setColor4(name + suffix, color, alpha);
  28605. };
  28606. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  28607. if (suffix === void 0) { suffix = ""; }
  28608. color.toArray(UniformBuffer._tempBuffer);
  28609. UniformBuffer._tempBuffer[3] = alpha;
  28610. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28611. };
  28612. /**
  28613. * Sets a sampler uniform on the effect.
  28614. * @param {string} name Name of the sampler.
  28615. * @param {Texture} texture
  28616. */
  28617. UniformBuffer.prototype.setTexture = function (name, texture) {
  28618. this._currentEffect.setTexture(name, texture);
  28619. };
  28620. /**
  28621. * Directly updates the value of the uniform in the cache AND on the GPU.
  28622. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  28623. * @param {number[]|Float32Array} data Flattened data
  28624. */
  28625. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  28626. this.updateUniform(uniformName, data, data.length);
  28627. this.update();
  28628. };
  28629. /**
  28630. * Binds this uniform buffer to an effect.
  28631. * @param {Effect} effect
  28632. * @param {string} name Name of the uniform block in the shader.
  28633. */
  28634. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  28635. this._currentEffect = effect;
  28636. if (this._noUBO || !this._buffer) {
  28637. return;
  28638. }
  28639. effect.bindUniformBuffer(this._buffer, name);
  28640. };
  28641. /**
  28642. * Disposes the uniform buffer.
  28643. */
  28644. UniformBuffer.prototype.dispose = function () {
  28645. if (this._noUBO) {
  28646. return;
  28647. }
  28648. var index = this._engine._uniformBuffers.indexOf(this);
  28649. if (index !== -1) {
  28650. this._engine._uniformBuffers.splice(index, 1);
  28651. }
  28652. if (!this._buffer) {
  28653. return;
  28654. }
  28655. if (this._engine._releaseBuffer(this._buffer)) {
  28656. this._buffer = null;
  28657. }
  28658. };
  28659. // Pool for avoiding memory leaks
  28660. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  28661. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  28662. return UniformBuffer;
  28663. }());
  28664. BABYLON.UniformBuffer = UniformBuffer;
  28665. })(BABYLON || (BABYLON = {}));
  28666. //# sourceMappingURL=babylon.uniformBuffer.js.map
  28667. var BABYLON;
  28668. (function (BABYLON) {
  28669. var VertexData = /** @class */ (function () {
  28670. function VertexData() {
  28671. }
  28672. VertexData.prototype.set = function (data, kind) {
  28673. switch (kind) {
  28674. case BABYLON.VertexBuffer.PositionKind:
  28675. this.positions = data;
  28676. break;
  28677. case BABYLON.VertexBuffer.NormalKind:
  28678. this.normals = data;
  28679. break;
  28680. case BABYLON.VertexBuffer.TangentKind:
  28681. this.tangents = data;
  28682. break;
  28683. case BABYLON.VertexBuffer.UVKind:
  28684. this.uvs = data;
  28685. break;
  28686. case BABYLON.VertexBuffer.UV2Kind:
  28687. this.uvs2 = data;
  28688. break;
  28689. case BABYLON.VertexBuffer.UV3Kind:
  28690. this.uvs3 = data;
  28691. break;
  28692. case BABYLON.VertexBuffer.UV4Kind:
  28693. this.uvs4 = data;
  28694. break;
  28695. case BABYLON.VertexBuffer.UV5Kind:
  28696. this.uvs5 = data;
  28697. break;
  28698. case BABYLON.VertexBuffer.UV6Kind:
  28699. this.uvs6 = data;
  28700. break;
  28701. case BABYLON.VertexBuffer.ColorKind:
  28702. this.colors = data;
  28703. break;
  28704. case BABYLON.VertexBuffer.MatricesIndicesKind:
  28705. this.matricesIndices = data;
  28706. break;
  28707. case BABYLON.VertexBuffer.MatricesWeightsKind:
  28708. this.matricesWeights = data;
  28709. break;
  28710. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  28711. this.matricesIndicesExtra = data;
  28712. break;
  28713. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  28714. this.matricesWeightsExtra = data;
  28715. break;
  28716. }
  28717. };
  28718. /**
  28719. * Associates the vertexData to the passed Mesh.
  28720. * Sets it as updatable or not (default `false`).
  28721. * Returns the VertexData.
  28722. */
  28723. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  28724. this._applyTo(mesh, updatable);
  28725. return this;
  28726. };
  28727. /**
  28728. * Associates the vertexData to the passed Geometry.
  28729. * Sets it as updatable or not (default `false`).
  28730. * Returns the VertexData.
  28731. */
  28732. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  28733. this._applyTo(geometry, updatable);
  28734. return this;
  28735. };
  28736. /**
  28737. * Updates the associated mesh.
  28738. * Returns the VertexData.
  28739. */
  28740. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  28741. this._update(mesh);
  28742. return this;
  28743. };
  28744. /**
  28745. * Updates the associated geometry.
  28746. * Returns the VertexData.
  28747. */
  28748. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  28749. this._update(geometry);
  28750. return this;
  28751. };
  28752. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  28753. if (updatable === void 0) { updatable = false; }
  28754. if (this.positions) {
  28755. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  28756. }
  28757. if (this.normals) {
  28758. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  28759. }
  28760. if (this.tangents) {
  28761. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  28762. }
  28763. if (this.uvs) {
  28764. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  28765. }
  28766. if (this.uvs2) {
  28767. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  28768. }
  28769. if (this.uvs3) {
  28770. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  28771. }
  28772. if (this.uvs4) {
  28773. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  28774. }
  28775. if (this.uvs5) {
  28776. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  28777. }
  28778. if (this.uvs6) {
  28779. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  28780. }
  28781. if (this.colors) {
  28782. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  28783. }
  28784. if (this.matricesIndices) {
  28785. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  28786. }
  28787. if (this.matricesWeights) {
  28788. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  28789. }
  28790. if (this.matricesIndicesExtra) {
  28791. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  28792. }
  28793. if (this.matricesWeightsExtra) {
  28794. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  28795. }
  28796. if (this.indices) {
  28797. meshOrGeometry.setIndices(this.indices, null, updatable);
  28798. }
  28799. return this;
  28800. };
  28801. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  28802. if (this.positions) {
  28803. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  28804. }
  28805. if (this.normals) {
  28806. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  28807. }
  28808. if (this.tangents) {
  28809. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  28810. }
  28811. if (this.uvs) {
  28812. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  28813. }
  28814. if (this.uvs2) {
  28815. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  28816. }
  28817. if (this.uvs3) {
  28818. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  28819. }
  28820. if (this.uvs4) {
  28821. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  28822. }
  28823. if (this.uvs5) {
  28824. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  28825. }
  28826. if (this.uvs6) {
  28827. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  28828. }
  28829. if (this.colors) {
  28830. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  28831. }
  28832. if (this.matricesIndices) {
  28833. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  28834. }
  28835. if (this.matricesWeights) {
  28836. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  28837. }
  28838. if (this.matricesIndicesExtra) {
  28839. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  28840. }
  28841. if (this.matricesWeightsExtra) {
  28842. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  28843. }
  28844. if (this.indices) {
  28845. meshOrGeometry.setIndices(this.indices, null);
  28846. }
  28847. return this;
  28848. };
  28849. /**
  28850. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  28851. * Returns the VertexData.
  28852. */
  28853. VertexData.prototype.transform = function (matrix) {
  28854. var transformed = BABYLON.Vector3.Zero();
  28855. var index;
  28856. if (this.positions) {
  28857. var position = BABYLON.Vector3.Zero();
  28858. for (index = 0; index < this.positions.length; index += 3) {
  28859. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  28860. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  28861. this.positions[index] = transformed.x;
  28862. this.positions[index + 1] = transformed.y;
  28863. this.positions[index + 2] = transformed.z;
  28864. }
  28865. }
  28866. if (this.normals) {
  28867. var normal = BABYLON.Vector3.Zero();
  28868. for (index = 0; index < this.normals.length; index += 3) {
  28869. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  28870. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  28871. this.normals[index] = transformed.x;
  28872. this.normals[index + 1] = transformed.y;
  28873. this.normals[index + 2] = transformed.z;
  28874. }
  28875. }
  28876. if (this.tangents) {
  28877. var tangent = BABYLON.Vector4.Zero();
  28878. var tangentTransformed = BABYLON.Vector4.Zero();
  28879. for (index = 0; index < this.tangents.length; index += 4) {
  28880. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  28881. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  28882. this.tangents[index] = tangentTransformed.x;
  28883. this.tangents[index + 1] = tangentTransformed.y;
  28884. this.tangents[index + 2] = tangentTransformed.z;
  28885. this.tangents[index + 3] = tangentTransformed.w;
  28886. }
  28887. }
  28888. return this;
  28889. };
  28890. /**
  28891. * Merges the passed VertexData into the current one.
  28892. * Returns the modified VertexData.
  28893. */
  28894. VertexData.prototype.merge = function (other, options) {
  28895. options = options || {};
  28896. if (other.indices) {
  28897. if (!this.indices) {
  28898. this.indices = [];
  28899. }
  28900. var offset = this.positions ? this.positions.length / 3 : 0;
  28901. for (var index = 0; index < other.indices.length; index++) {
  28902. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  28903. this.indices.push(other.indices[index] + offset);
  28904. }
  28905. }
  28906. this.positions = this._mergeElement(this.positions, other.positions);
  28907. if (!this.positions) {
  28908. return this;
  28909. }
  28910. var count = this.positions.length / 3;
  28911. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  28912. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  28913. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  28914. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  28915. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  28916. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  28917. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  28918. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  28919. this.colors = this._mergeElement(this.colors, other.colors, count * 4, 1);
  28920. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  28921. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  28922. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  28923. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  28924. return this;
  28925. };
  28926. VertexData.prototype._mergeElement = function (source, other, length, defaultValue) {
  28927. if (length === void 0) { length = 0; }
  28928. if (defaultValue === void 0) { defaultValue = 0; }
  28929. if (!other && !source) {
  28930. return null;
  28931. }
  28932. if (!other) {
  28933. var padding = new Float32Array(source.length);
  28934. padding.fill(defaultValue);
  28935. return this._mergeElement(source, padding, length);
  28936. }
  28937. if (!source) {
  28938. if (length === 0 || length === other.length) {
  28939. return other;
  28940. }
  28941. var padding = new Float32Array(length - other.length);
  28942. padding.fill(defaultValue);
  28943. return this._mergeElement(padding, other, length);
  28944. }
  28945. var len = other.length + source.length;
  28946. var isSrcTypedArray = source instanceof Float32Array;
  28947. var isOthTypedArray = other instanceof Float32Array;
  28948. // use non-loop method when the source is Float32Array
  28949. if (isSrcTypedArray) {
  28950. var ret32 = new Float32Array(len);
  28951. ret32.set(source);
  28952. ret32.set(other, source.length);
  28953. return ret32;
  28954. // source is number[], when other is also use concat
  28955. }
  28956. else if (!isOthTypedArray) {
  28957. return source.concat(other);
  28958. // source is a number[], but other is a Float32Array, loop required
  28959. }
  28960. else {
  28961. var ret = source.slice(0); // copy source to a separate array
  28962. for (var i = 0, len = other.length; i < len; i++) {
  28963. ret.push(other[i]);
  28964. }
  28965. return ret;
  28966. }
  28967. };
  28968. /**
  28969. * Serializes the VertexData.
  28970. * Returns a serialized object.
  28971. */
  28972. VertexData.prototype.serialize = function () {
  28973. var serializationObject = this.serialize();
  28974. if (this.positions) {
  28975. serializationObject.positions = this.positions;
  28976. }
  28977. if (this.normals) {
  28978. serializationObject.normals = this.normals;
  28979. }
  28980. if (this.tangents) {
  28981. serializationObject.tangents = this.tangents;
  28982. }
  28983. if (this.uvs) {
  28984. serializationObject.uvs = this.uvs;
  28985. }
  28986. if (this.uvs2) {
  28987. serializationObject.uvs2 = this.uvs2;
  28988. }
  28989. if (this.uvs3) {
  28990. serializationObject.uvs3 = this.uvs3;
  28991. }
  28992. if (this.uvs4) {
  28993. serializationObject.uvs4 = this.uvs4;
  28994. }
  28995. if (this.uvs5) {
  28996. serializationObject.uvs5 = this.uvs5;
  28997. }
  28998. if (this.uvs6) {
  28999. serializationObject.uvs6 = this.uvs6;
  29000. }
  29001. if (this.colors) {
  29002. serializationObject.colors = this.colors;
  29003. }
  29004. if (this.matricesIndices) {
  29005. serializationObject.matricesIndices = this.matricesIndices;
  29006. serializationObject.matricesIndices._isExpanded = true;
  29007. }
  29008. if (this.matricesWeights) {
  29009. serializationObject.matricesWeights = this.matricesWeights;
  29010. }
  29011. if (this.matricesIndicesExtra) {
  29012. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  29013. serializationObject.matricesIndicesExtra._isExpanded = true;
  29014. }
  29015. if (this.matricesWeightsExtra) {
  29016. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  29017. }
  29018. serializationObject.indices = this.indices;
  29019. return serializationObject;
  29020. };
  29021. // Statics
  29022. /**
  29023. * Returns the object VertexData associated to the passed mesh.
  29024. */
  29025. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  29026. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  29027. };
  29028. /**
  29029. * Returns the object VertexData associated to the passed geometry.
  29030. */
  29031. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  29032. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  29033. };
  29034. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  29035. var result = new VertexData();
  29036. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29037. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  29038. }
  29039. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29040. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  29041. }
  29042. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  29043. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  29044. }
  29045. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29046. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  29047. }
  29048. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29049. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  29050. }
  29051. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29052. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  29053. }
  29054. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29055. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  29056. }
  29057. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29058. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  29059. }
  29060. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29061. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  29062. }
  29063. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29064. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  29065. }
  29066. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29067. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  29068. }
  29069. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29070. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  29071. }
  29072. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  29073. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  29074. }
  29075. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  29076. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  29077. }
  29078. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  29079. return result;
  29080. };
  29081. /**
  29082. * Creates the vertexData of the Ribbon.
  29083. */
  29084. VertexData.CreateRibbon = function (options) {
  29085. var pathArray = options.pathArray;
  29086. var closeArray = options.closeArray || false;
  29087. var closePath = options.closePath || false;
  29088. var invertUV = options.invertUV || false;
  29089. var defaultOffset = Math.floor(pathArray[0].length / 2);
  29090. var offset = options.offset || defaultOffset;
  29091. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  29092. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29093. var customUV = options.uvs;
  29094. var customColors = options.colors;
  29095. var positions = [];
  29096. var indices = [];
  29097. var normals = [];
  29098. var uvs = [];
  29099. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  29100. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  29101. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  29102. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  29103. var minlg; // minimal length among all paths from pathArray
  29104. var lg = []; // array of path lengths : nb of vertex per path
  29105. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  29106. var p; // path iterator
  29107. var i; // point iterator
  29108. var j; // point iterator
  29109. // if single path in pathArray
  29110. if (pathArray.length < 2) {
  29111. var ar1 = [];
  29112. var ar2 = [];
  29113. for (i = 0; i < pathArray[0].length - offset; i++) {
  29114. ar1.push(pathArray[0][i]);
  29115. ar2.push(pathArray[0][i + offset]);
  29116. }
  29117. pathArray = [ar1, ar2];
  29118. }
  29119. // positions and horizontal distances (u)
  29120. var idc = 0;
  29121. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  29122. var path;
  29123. var l;
  29124. minlg = pathArray[0].length;
  29125. var vectlg;
  29126. var dist;
  29127. for (p = 0; p < pathArray.length; p++) {
  29128. uTotalDistance[p] = 0;
  29129. us[p] = [0];
  29130. path = pathArray[p];
  29131. l = path.length;
  29132. minlg = (minlg < l) ? minlg : l;
  29133. j = 0;
  29134. while (j < l) {
  29135. positions.push(path[j].x, path[j].y, path[j].z);
  29136. if (j > 0) {
  29137. vectlg = path[j].subtract(path[j - 1]).length();
  29138. dist = vectlg + uTotalDistance[p];
  29139. us[p].push(dist);
  29140. uTotalDistance[p] = dist;
  29141. }
  29142. j++;
  29143. }
  29144. if (closePath) {
  29145. j--;
  29146. positions.push(path[0].x, path[0].y, path[0].z);
  29147. vectlg = path[j].subtract(path[0]).length();
  29148. dist = vectlg + uTotalDistance[p];
  29149. us[p].push(dist);
  29150. uTotalDistance[p] = dist;
  29151. }
  29152. lg[p] = l + closePathCorr;
  29153. idx[p] = idc;
  29154. idc += (l + closePathCorr);
  29155. }
  29156. // vertical distances (v)
  29157. var path1;
  29158. var path2;
  29159. var vertex1 = null;
  29160. var vertex2 = null;
  29161. for (i = 0; i < minlg + closePathCorr; i++) {
  29162. vTotalDistance[i] = 0;
  29163. vs[i] = [0];
  29164. for (p = 0; p < pathArray.length - 1; p++) {
  29165. path1 = pathArray[p];
  29166. path2 = pathArray[p + 1];
  29167. if (i === minlg) {
  29168. vertex1 = path1[0];
  29169. vertex2 = path2[0];
  29170. }
  29171. else {
  29172. vertex1 = path1[i];
  29173. vertex2 = path2[i];
  29174. }
  29175. vectlg = vertex2.subtract(vertex1).length();
  29176. dist = vectlg + vTotalDistance[i];
  29177. vs[i].push(dist);
  29178. vTotalDistance[i] = dist;
  29179. }
  29180. if (closeArray && vertex2 && vertex1) {
  29181. path1 = pathArray[p];
  29182. path2 = pathArray[0];
  29183. if (i === minlg) {
  29184. vertex2 = path2[0];
  29185. }
  29186. vectlg = vertex2.subtract(vertex1).length();
  29187. dist = vectlg + vTotalDistance[i];
  29188. vTotalDistance[i] = dist;
  29189. }
  29190. }
  29191. // uvs
  29192. var u;
  29193. var v;
  29194. if (customUV) {
  29195. for (p = 0; p < customUV.length; p++) {
  29196. uvs.push(customUV[p].x, customUV[p].y);
  29197. }
  29198. }
  29199. else {
  29200. for (p = 0; p < pathArray.length; p++) {
  29201. for (i = 0; i < minlg + closePathCorr; i++) {
  29202. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  29203. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  29204. if (invertUV) {
  29205. uvs.push(v, u);
  29206. }
  29207. else {
  29208. uvs.push(u, v);
  29209. }
  29210. }
  29211. }
  29212. }
  29213. // indices
  29214. p = 0; // path index
  29215. var pi = 0; // positions array index
  29216. var l1 = lg[p] - 1; // path1 length
  29217. var l2 = lg[p + 1] - 1; // path2 length
  29218. var min = (l1 < l2) ? l1 : l2; // current path stop index
  29219. var shft = idx[1] - idx[0]; // shift
  29220. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  29221. while (pi <= min && p < path1nb) {
  29222. // 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
  29223. indices.push(pi, pi + shft, pi + 1);
  29224. indices.push(pi + shft + 1, pi + 1, pi + shft);
  29225. pi += 1;
  29226. if (pi === min) {
  29227. p++;
  29228. if (p === lg.length - 1) {
  29229. shft = idx[0] - idx[p];
  29230. l1 = lg[p] - 1;
  29231. l2 = lg[0] - 1;
  29232. }
  29233. else {
  29234. shft = idx[p + 1] - idx[p];
  29235. l1 = lg[p] - 1;
  29236. l2 = lg[p + 1] - 1;
  29237. }
  29238. pi = idx[p];
  29239. min = (l1 < l2) ? l1 + pi : l2 + pi;
  29240. }
  29241. }
  29242. // normals
  29243. VertexData.ComputeNormals(positions, indices, normals);
  29244. if (closePath) {
  29245. var indexFirst = 0;
  29246. var indexLast = 0;
  29247. for (p = 0; p < pathArray.length; p++) {
  29248. indexFirst = idx[p] * 3;
  29249. if (p + 1 < pathArray.length) {
  29250. indexLast = (idx[p + 1] - 1) * 3;
  29251. }
  29252. else {
  29253. indexLast = normals.length - 3;
  29254. }
  29255. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  29256. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  29257. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  29258. normals[indexLast] = normals[indexFirst];
  29259. normals[indexLast + 1] = normals[indexFirst + 1];
  29260. normals[indexLast + 2] = normals[indexFirst + 2];
  29261. }
  29262. }
  29263. // sides
  29264. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29265. // Colors
  29266. var colors = null;
  29267. if (customColors) {
  29268. colors = new Float32Array(customColors.length * 4);
  29269. for (var c = 0; c < customColors.length; c++) {
  29270. colors[c * 4] = customColors[c].r;
  29271. colors[c * 4 + 1] = customColors[c].g;
  29272. colors[c * 4 + 2] = customColors[c].b;
  29273. colors[c * 4 + 3] = customColors[c].a;
  29274. }
  29275. }
  29276. // Result
  29277. var vertexData = new VertexData();
  29278. var positions32 = new Float32Array(positions);
  29279. var normals32 = new Float32Array(normals);
  29280. var uvs32 = new Float32Array(uvs);
  29281. vertexData.indices = indices;
  29282. vertexData.positions = positions32;
  29283. vertexData.normals = normals32;
  29284. vertexData.uvs = uvs32;
  29285. if (colors) {
  29286. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  29287. }
  29288. if (closePath) {
  29289. vertexData._idx = idx;
  29290. }
  29291. return vertexData;
  29292. };
  29293. /**
  29294. * Creates the VertexData of the Box.
  29295. */
  29296. VertexData.CreateBox = function (options) {
  29297. var normalsSource = [
  29298. new BABYLON.Vector3(0, 0, 1),
  29299. new BABYLON.Vector3(0, 0, -1),
  29300. new BABYLON.Vector3(1, 0, 0),
  29301. new BABYLON.Vector3(-1, 0, 0),
  29302. new BABYLON.Vector3(0, 1, 0),
  29303. new BABYLON.Vector3(0, -1, 0)
  29304. ];
  29305. var indices = [];
  29306. var positions = [];
  29307. var normals = [];
  29308. var uvs = [];
  29309. var width = options.width || options.size || 1;
  29310. var height = options.height || options.size || 1;
  29311. var depth = options.depth || options.size || 1;
  29312. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29313. var faceUV = options.faceUV || new Array(6);
  29314. var faceColors = options.faceColors;
  29315. var colors = [];
  29316. // default face colors and UV if undefined
  29317. for (var f = 0; f < 6; f++) {
  29318. if (faceUV[f] === undefined) {
  29319. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29320. }
  29321. if (faceColors && faceColors[f] === undefined) {
  29322. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29323. }
  29324. }
  29325. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  29326. // Create each face in turn.
  29327. for (var index = 0; index < normalsSource.length; index++) {
  29328. var normal = normalsSource[index];
  29329. // Get two vectors perpendicular to the face normal and to each other.
  29330. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  29331. var side2 = BABYLON.Vector3.Cross(normal, side1);
  29332. // Six indices (two triangles) per face.
  29333. var verticesLength = positions.length / 3;
  29334. indices.push(verticesLength);
  29335. indices.push(verticesLength + 1);
  29336. indices.push(verticesLength + 2);
  29337. indices.push(verticesLength);
  29338. indices.push(verticesLength + 2);
  29339. indices.push(verticesLength + 3);
  29340. // Four vertices per face.
  29341. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  29342. positions.push(vertex.x, vertex.y, vertex.z);
  29343. normals.push(normal.x, normal.y, normal.z);
  29344. uvs.push(faceUV[index].z, faceUV[index].w);
  29345. if (faceColors) {
  29346. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29347. }
  29348. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  29349. positions.push(vertex.x, vertex.y, vertex.z);
  29350. normals.push(normal.x, normal.y, normal.z);
  29351. uvs.push(faceUV[index].x, faceUV[index].w);
  29352. if (faceColors) {
  29353. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29354. }
  29355. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  29356. positions.push(vertex.x, vertex.y, vertex.z);
  29357. normals.push(normal.x, normal.y, normal.z);
  29358. uvs.push(faceUV[index].x, faceUV[index].y);
  29359. if (faceColors) {
  29360. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29361. }
  29362. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  29363. positions.push(vertex.x, vertex.y, vertex.z);
  29364. normals.push(normal.x, normal.y, normal.z);
  29365. uvs.push(faceUV[index].z, faceUV[index].y);
  29366. if (faceColors) {
  29367. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29368. }
  29369. }
  29370. // sides
  29371. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29372. // Result
  29373. var vertexData = new VertexData();
  29374. vertexData.indices = indices;
  29375. vertexData.positions = positions;
  29376. vertexData.normals = normals;
  29377. vertexData.uvs = uvs;
  29378. if (faceColors) {
  29379. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  29380. vertexData.colors = totalColors;
  29381. }
  29382. return vertexData;
  29383. };
  29384. /**
  29385. * Creates the VertexData of the Sphere.
  29386. */
  29387. VertexData.CreateSphere = function (options) {
  29388. var segments = options.segments || 32;
  29389. var diameterX = options.diameterX || options.diameter || 1;
  29390. var diameterY = options.diameterY || options.diameter || 1;
  29391. var diameterZ = options.diameterZ || options.diameter || 1;
  29392. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29393. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  29394. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29395. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  29396. var totalZRotationSteps = 2 + segments;
  29397. var totalYRotationSteps = 2 * totalZRotationSteps;
  29398. var indices = [];
  29399. var positions = [];
  29400. var normals = [];
  29401. var uvs = [];
  29402. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  29403. var normalizedZ = zRotationStep / totalZRotationSteps;
  29404. var angleZ = normalizedZ * Math.PI * slice;
  29405. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  29406. var normalizedY = yRotationStep / totalYRotationSteps;
  29407. var angleY = normalizedY * Math.PI * 2 * arc;
  29408. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  29409. var rotationY = BABYLON.Matrix.RotationY(angleY);
  29410. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  29411. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  29412. var vertex = complete.multiply(radius);
  29413. var normal = complete.divide(radius).normalize();
  29414. positions.push(vertex.x, vertex.y, vertex.z);
  29415. normals.push(normal.x, normal.y, normal.z);
  29416. uvs.push(normalizedY, normalizedZ);
  29417. }
  29418. if (zRotationStep > 0) {
  29419. var verticesCount = positions.length / 3;
  29420. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  29421. indices.push((firstIndex));
  29422. indices.push((firstIndex + 1));
  29423. indices.push(firstIndex + totalYRotationSteps + 1);
  29424. indices.push((firstIndex + totalYRotationSteps + 1));
  29425. indices.push((firstIndex + 1));
  29426. indices.push((firstIndex + totalYRotationSteps + 2));
  29427. }
  29428. }
  29429. }
  29430. // Sides
  29431. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29432. // Result
  29433. var vertexData = new VertexData();
  29434. vertexData.indices = indices;
  29435. vertexData.positions = positions;
  29436. vertexData.normals = normals;
  29437. vertexData.uvs = uvs;
  29438. return vertexData;
  29439. };
  29440. /**
  29441. * Creates the VertexData of the Cylinder or Cone.
  29442. */
  29443. VertexData.CreateCylinder = function (options) {
  29444. var height = options.height || 2;
  29445. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  29446. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  29447. var tessellation = options.tessellation || 24;
  29448. var subdivisions = options.subdivisions || 1;
  29449. var hasRings = options.hasRings ? true : false;
  29450. var enclose = options.enclose ? true : false;
  29451. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29452. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29453. var faceUV = options.faceUV || new Array(3);
  29454. var faceColors = options.faceColors;
  29455. // default face colors and UV if undefined
  29456. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  29457. var ringNb = (hasRings) ? subdivisions : 1;
  29458. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  29459. var f;
  29460. for (f = 0; f < surfaceNb; f++) {
  29461. if (faceColors && faceColors[f] === undefined) {
  29462. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29463. }
  29464. }
  29465. for (f = 0; f < surfaceNb; f++) {
  29466. if (faceUV && faceUV[f] === undefined) {
  29467. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29468. }
  29469. }
  29470. var indices = new Array();
  29471. var positions = new Array();
  29472. var normals = new Array();
  29473. var uvs = new Array();
  29474. var colors = new Array();
  29475. var angle_step = Math.PI * 2 * arc / tessellation;
  29476. var angle;
  29477. var h;
  29478. var radius;
  29479. var tan = (diameterBottom - diameterTop) / 2 / height;
  29480. var ringVertex = BABYLON.Vector3.Zero();
  29481. var ringNormal = BABYLON.Vector3.Zero();
  29482. var ringFirstVertex = BABYLON.Vector3.Zero();
  29483. var ringFirstNormal = BABYLON.Vector3.Zero();
  29484. var quadNormal = BABYLON.Vector3.Zero();
  29485. var Y = BABYLON.Axis.Y;
  29486. // positions, normals, uvs
  29487. var i;
  29488. var j;
  29489. var r;
  29490. var ringIdx = 1;
  29491. var s = 1; // surface index
  29492. var cs = 0;
  29493. var v = 0;
  29494. for (i = 0; i <= subdivisions; i++) {
  29495. h = i / subdivisions;
  29496. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  29497. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  29498. for (r = 0; r < ringIdx; r++) {
  29499. if (hasRings) {
  29500. s += r;
  29501. }
  29502. if (enclose) {
  29503. s += 2 * r;
  29504. }
  29505. for (j = 0; j <= tessellation; j++) {
  29506. angle = j * angle_step;
  29507. // position
  29508. ringVertex.x = Math.cos(-angle) * radius;
  29509. ringVertex.y = -height / 2 + h * height;
  29510. ringVertex.z = Math.sin(-angle) * radius;
  29511. // normal
  29512. if (diameterTop === 0 && i === subdivisions) {
  29513. // if no top cap, reuse former normals
  29514. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  29515. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  29516. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  29517. }
  29518. else {
  29519. ringNormal.x = ringVertex.x;
  29520. ringNormal.z = ringVertex.z;
  29521. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  29522. ringNormal.normalize();
  29523. }
  29524. // keep first ring vertex values for enclose
  29525. if (j === 0) {
  29526. ringFirstVertex.copyFrom(ringVertex);
  29527. ringFirstNormal.copyFrom(ringNormal);
  29528. }
  29529. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29530. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  29531. if (hasRings) {
  29532. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  29533. }
  29534. else {
  29535. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  29536. }
  29537. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  29538. if (faceColors) {
  29539. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  29540. }
  29541. }
  29542. // if enclose, add four vertices and their dedicated normals
  29543. if (arc !== 1 && enclose) {
  29544. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29545. positions.push(0, ringVertex.y, 0);
  29546. positions.push(0, ringVertex.y, 0);
  29547. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  29548. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  29549. quadNormal.normalize();
  29550. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29551. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  29552. quadNormal.normalize();
  29553. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29554. if (hasRings) {
  29555. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  29556. }
  29557. else {
  29558. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  29559. }
  29560. uvs.push(faceUV[s + 1].x, v);
  29561. uvs.push(faceUV[s + 1].z, v);
  29562. if (hasRings) {
  29563. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  29564. }
  29565. else {
  29566. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  29567. }
  29568. uvs.push(faceUV[s + 2].x, v);
  29569. uvs.push(faceUV[s + 2].z, v);
  29570. if (faceColors) {
  29571. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29572. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29573. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29574. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29575. }
  29576. }
  29577. if (cs !== s) {
  29578. cs = s;
  29579. }
  29580. }
  29581. }
  29582. // indices
  29583. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  29584. var s;
  29585. i = 0;
  29586. for (s = 0; s < subdivisions; s++) {
  29587. var i0 = 0;
  29588. var i1 = 0;
  29589. var i2 = 0;
  29590. var i3 = 0;
  29591. for (j = 0; j < tessellation; j++) {
  29592. i0 = i * (e + 1) + j;
  29593. i1 = (i + 1) * (e + 1) + j;
  29594. i2 = i * (e + 1) + (j + 1);
  29595. i3 = (i + 1) * (e + 1) + (j + 1);
  29596. indices.push(i0, i1, i2);
  29597. indices.push(i3, i2, i1);
  29598. }
  29599. if (arc !== 1 && enclose) {
  29600. indices.push(i0 + 2, i1 + 2, i2 + 2);
  29601. indices.push(i3 + 2, i2 + 2, i1 + 2);
  29602. indices.push(i0 + 4, i1 + 4, i2 + 4);
  29603. indices.push(i3 + 4, i2 + 4, i1 + 4);
  29604. }
  29605. i = (hasRings) ? (i + 2) : (i + 1);
  29606. }
  29607. // Caps
  29608. var createCylinderCap = function (isTop) {
  29609. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  29610. if (radius === 0) {
  29611. return;
  29612. }
  29613. // Cap positions, normals & uvs
  29614. var angle;
  29615. var circleVector;
  29616. var i;
  29617. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  29618. var c = null;
  29619. if (faceColors) {
  29620. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  29621. }
  29622. // cap center
  29623. var vbase = positions.length / 3;
  29624. var offset = isTop ? height / 2 : -height / 2;
  29625. var center = new BABYLON.Vector3(0, offset, 0);
  29626. positions.push(center.x, center.y, center.z);
  29627. normals.push(0, isTop ? 1 : -1, 0);
  29628. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  29629. if (c) {
  29630. colors.push(c.r, c.g, c.b, c.a);
  29631. }
  29632. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  29633. for (i = 0; i <= tessellation; i++) {
  29634. angle = Math.PI * 2 * i * arc / tessellation;
  29635. var cos = Math.cos(-angle);
  29636. var sin = Math.sin(-angle);
  29637. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  29638. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  29639. positions.push(circleVector.x, circleVector.y, circleVector.z);
  29640. normals.push(0, isTop ? 1 : -1, 0);
  29641. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  29642. if (c) {
  29643. colors.push(c.r, c.g, c.b, c.a);
  29644. }
  29645. }
  29646. // Cap indices
  29647. for (i = 0; i < tessellation; i++) {
  29648. if (!isTop) {
  29649. indices.push(vbase);
  29650. indices.push(vbase + (i + 1));
  29651. indices.push(vbase + (i + 2));
  29652. }
  29653. else {
  29654. indices.push(vbase);
  29655. indices.push(vbase + (i + 2));
  29656. indices.push(vbase + (i + 1));
  29657. }
  29658. }
  29659. };
  29660. // add caps to geometry
  29661. createCylinderCap(false);
  29662. createCylinderCap(true);
  29663. // Sides
  29664. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29665. var vertexData = new VertexData();
  29666. vertexData.indices = indices;
  29667. vertexData.positions = positions;
  29668. vertexData.normals = normals;
  29669. vertexData.uvs = uvs;
  29670. if (faceColors) {
  29671. vertexData.colors = colors;
  29672. }
  29673. return vertexData;
  29674. };
  29675. /**
  29676. * Creates the VertexData of the Torus.
  29677. */
  29678. VertexData.CreateTorus = function (options) {
  29679. var indices = [];
  29680. var positions = [];
  29681. var normals = [];
  29682. var uvs = [];
  29683. var diameter = options.diameter || 1;
  29684. var thickness = options.thickness || 0.5;
  29685. var tessellation = options.tessellation || 16;
  29686. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29687. var stride = tessellation + 1;
  29688. for (var i = 0; i <= tessellation; i++) {
  29689. var u = i / tessellation;
  29690. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  29691. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  29692. for (var j = 0; j <= tessellation; j++) {
  29693. var v = 1 - j / tessellation;
  29694. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  29695. var dx = Math.cos(innerAngle);
  29696. var dy = Math.sin(innerAngle);
  29697. // Create a vertex.
  29698. var normal = new BABYLON.Vector3(dx, dy, 0);
  29699. var position = normal.scale(thickness / 2);
  29700. var textureCoordinate = new BABYLON.Vector2(u, v);
  29701. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  29702. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  29703. positions.push(position.x, position.y, position.z);
  29704. normals.push(normal.x, normal.y, normal.z);
  29705. uvs.push(textureCoordinate.x, textureCoordinate.y);
  29706. // And create indices for two triangles.
  29707. var nextI = (i + 1) % stride;
  29708. var nextJ = (j + 1) % stride;
  29709. indices.push(i * stride + j);
  29710. indices.push(i * stride + nextJ);
  29711. indices.push(nextI * stride + j);
  29712. indices.push(i * stride + nextJ);
  29713. indices.push(nextI * stride + nextJ);
  29714. indices.push(nextI * stride + j);
  29715. }
  29716. }
  29717. // Sides
  29718. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29719. // Result
  29720. var vertexData = new VertexData();
  29721. vertexData.indices = indices;
  29722. vertexData.positions = positions;
  29723. vertexData.normals = normals;
  29724. vertexData.uvs = uvs;
  29725. return vertexData;
  29726. };
  29727. /**
  29728. * Creates the VertexData of the LineSystem.
  29729. */
  29730. VertexData.CreateLineSystem = function (options) {
  29731. var indices = [];
  29732. var positions = [];
  29733. var lines = options.lines;
  29734. var colors = options.colors;
  29735. var vertexColors = [];
  29736. var idx = 0;
  29737. for (var l = 0; l < lines.length; l++) {
  29738. var points = lines[l];
  29739. for (var index = 0; index < points.length; index++) {
  29740. positions.push(points[index].x, points[index].y, points[index].z);
  29741. if (colors) {
  29742. var color = colors[l];
  29743. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  29744. }
  29745. if (index > 0) {
  29746. indices.push(idx - 1);
  29747. indices.push(idx);
  29748. }
  29749. idx++;
  29750. }
  29751. }
  29752. var vertexData = new VertexData();
  29753. vertexData.indices = indices;
  29754. vertexData.positions = positions;
  29755. if (colors) {
  29756. vertexData.colors = vertexColors;
  29757. }
  29758. return vertexData;
  29759. };
  29760. /**
  29761. * Create the VertexData of the DashedLines.
  29762. */
  29763. VertexData.CreateDashedLines = function (options) {
  29764. var dashSize = options.dashSize || 3;
  29765. var gapSize = options.gapSize || 1;
  29766. var dashNb = options.dashNb || 200;
  29767. var points = options.points;
  29768. var positions = new Array();
  29769. var indices = new Array();
  29770. var curvect = BABYLON.Vector3.Zero();
  29771. var lg = 0;
  29772. var nb = 0;
  29773. var shft = 0;
  29774. var dashshft = 0;
  29775. var curshft = 0;
  29776. var idx = 0;
  29777. var i = 0;
  29778. for (i = 0; i < points.length - 1; i++) {
  29779. points[i + 1].subtractToRef(points[i], curvect);
  29780. lg += curvect.length();
  29781. }
  29782. shft = lg / dashNb;
  29783. dashshft = dashSize * shft / (dashSize + gapSize);
  29784. for (i = 0; i < points.length - 1; i++) {
  29785. points[i + 1].subtractToRef(points[i], curvect);
  29786. nb = Math.floor(curvect.length() / shft);
  29787. curvect.normalize();
  29788. for (var j = 0; j < nb; j++) {
  29789. curshft = shft * j;
  29790. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  29791. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  29792. indices.push(idx, idx + 1);
  29793. idx += 2;
  29794. }
  29795. }
  29796. // Result
  29797. var vertexData = new VertexData();
  29798. vertexData.positions = positions;
  29799. vertexData.indices = indices;
  29800. return vertexData;
  29801. };
  29802. /**
  29803. * Creates the VertexData of the Ground.
  29804. */
  29805. VertexData.CreateGround = function (options) {
  29806. var indices = [];
  29807. var positions = [];
  29808. var normals = [];
  29809. var uvs = [];
  29810. var row, col;
  29811. var width = options.width || 1;
  29812. var height = options.height || 1;
  29813. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  29814. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  29815. for (row = 0; row <= subdivisionsY; row++) {
  29816. for (col = 0; col <= subdivisionsX; col++) {
  29817. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  29818. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29819. positions.push(position.x, position.y, position.z);
  29820. normals.push(normal.x, normal.y, normal.z);
  29821. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  29822. }
  29823. }
  29824. for (row = 0; row < subdivisionsY; row++) {
  29825. for (col = 0; col < subdivisionsX; col++) {
  29826. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  29827. indices.push(col + 1 + row * (subdivisionsX + 1));
  29828. indices.push(col + row * (subdivisionsX + 1));
  29829. indices.push(col + (row + 1) * (subdivisionsX + 1));
  29830. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  29831. indices.push(col + row * (subdivisionsX + 1));
  29832. }
  29833. }
  29834. // Result
  29835. var vertexData = new VertexData();
  29836. vertexData.indices = indices;
  29837. vertexData.positions = positions;
  29838. vertexData.normals = normals;
  29839. vertexData.uvs = uvs;
  29840. return vertexData;
  29841. };
  29842. /**
  29843. * Creates the VertexData of the TiledGround.
  29844. */
  29845. VertexData.CreateTiledGround = function (options) {
  29846. var xmin = options.xmin || -1.0;
  29847. var zmin = options.zmin || -1.0;
  29848. var xmax = options.xmax || 1.0;
  29849. var zmax = options.zmax || 1.0;
  29850. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  29851. var precision = options.precision || { w: 1, h: 1 };
  29852. var indices = new Array();
  29853. var positions = new Array();
  29854. var normals = new Array();
  29855. var uvs = new Array();
  29856. var row, col, tileRow, tileCol;
  29857. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  29858. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  29859. precision.w = (precision.w < 1) ? 1 : precision.w;
  29860. precision.h = (precision.h < 1) ? 1 : precision.h;
  29861. var tileSize = {
  29862. 'w': (xmax - xmin) / subdivisions.w,
  29863. 'h': (zmax - zmin) / subdivisions.h
  29864. };
  29865. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  29866. // Indices
  29867. var base = positions.length / 3;
  29868. var rowLength = precision.w + 1;
  29869. for (row = 0; row < precision.h; row++) {
  29870. for (col = 0; col < precision.w; col++) {
  29871. var square = [
  29872. base + col + row * rowLength,
  29873. base + (col + 1) + row * rowLength,
  29874. base + (col + 1) + (row + 1) * rowLength,
  29875. base + col + (row + 1) * rowLength
  29876. ];
  29877. indices.push(square[1]);
  29878. indices.push(square[2]);
  29879. indices.push(square[3]);
  29880. indices.push(square[0]);
  29881. indices.push(square[1]);
  29882. indices.push(square[3]);
  29883. }
  29884. }
  29885. // Position, normals and uvs
  29886. var position = BABYLON.Vector3.Zero();
  29887. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29888. for (row = 0; row <= precision.h; row++) {
  29889. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  29890. for (col = 0; col <= precision.w; col++) {
  29891. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  29892. position.y = 0;
  29893. positions.push(position.x, position.y, position.z);
  29894. normals.push(normal.x, normal.y, normal.z);
  29895. uvs.push(col / precision.w, row / precision.h);
  29896. }
  29897. }
  29898. }
  29899. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  29900. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  29901. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  29902. }
  29903. }
  29904. // Result
  29905. var vertexData = new VertexData();
  29906. vertexData.indices = indices;
  29907. vertexData.positions = positions;
  29908. vertexData.normals = normals;
  29909. vertexData.uvs = uvs;
  29910. return vertexData;
  29911. };
  29912. /**
  29913. * Creates the VertexData of the Ground designed from a heightmap.
  29914. */
  29915. VertexData.CreateGroundFromHeightMap = function (options) {
  29916. var indices = [];
  29917. var positions = [];
  29918. var normals = [];
  29919. var uvs = [];
  29920. var row, col;
  29921. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  29922. // Vertices
  29923. for (row = 0; row <= options.subdivisions; row++) {
  29924. for (col = 0; col <= options.subdivisions; col++) {
  29925. 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));
  29926. // Compute height
  29927. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  29928. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  29929. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  29930. var r = options.buffer[pos] / 255.0;
  29931. var g = options.buffer[pos + 1] / 255.0;
  29932. var b = options.buffer[pos + 2] / 255.0;
  29933. var gradient = r * filter.r + g * filter.g + b * filter.b;
  29934. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  29935. // Add vertex
  29936. positions.push(position.x, position.y, position.z);
  29937. normals.push(0, 0, 0);
  29938. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  29939. }
  29940. }
  29941. // Indices
  29942. for (row = 0; row < options.subdivisions; row++) {
  29943. for (col = 0; col < options.subdivisions; col++) {
  29944. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29945. indices.push(col + 1 + row * (options.subdivisions + 1));
  29946. indices.push(col + row * (options.subdivisions + 1));
  29947. indices.push(col + (row + 1) * (options.subdivisions + 1));
  29948. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29949. indices.push(col + row * (options.subdivisions + 1));
  29950. }
  29951. }
  29952. // Normals
  29953. VertexData.ComputeNormals(positions, indices, normals);
  29954. // Result
  29955. var vertexData = new VertexData();
  29956. vertexData.indices = indices;
  29957. vertexData.positions = positions;
  29958. vertexData.normals = normals;
  29959. vertexData.uvs = uvs;
  29960. return vertexData;
  29961. };
  29962. /**
  29963. * Creates the VertexData of the Plane.
  29964. */
  29965. VertexData.CreatePlane = function (options) {
  29966. var indices = [];
  29967. var positions = [];
  29968. var normals = [];
  29969. var uvs = [];
  29970. var width = options.width || options.size || 1;
  29971. var height = options.height || options.size || 1;
  29972. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29973. // Vertices
  29974. var halfWidth = width / 2.0;
  29975. var halfHeight = height / 2.0;
  29976. positions.push(-halfWidth, -halfHeight, 0);
  29977. normals.push(0, 0, -1.0);
  29978. uvs.push(0.0, 0.0);
  29979. positions.push(halfWidth, -halfHeight, 0);
  29980. normals.push(0, 0, -1.0);
  29981. uvs.push(1.0, 0.0);
  29982. positions.push(halfWidth, halfHeight, 0);
  29983. normals.push(0, 0, -1.0);
  29984. uvs.push(1.0, 1.0);
  29985. positions.push(-halfWidth, halfHeight, 0);
  29986. normals.push(0, 0, -1.0);
  29987. uvs.push(0.0, 1.0);
  29988. // Indices
  29989. indices.push(0);
  29990. indices.push(1);
  29991. indices.push(2);
  29992. indices.push(0);
  29993. indices.push(2);
  29994. indices.push(3);
  29995. // Sides
  29996. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29997. // Result
  29998. var vertexData = new VertexData();
  29999. vertexData.indices = indices;
  30000. vertexData.positions = positions;
  30001. vertexData.normals = normals;
  30002. vertexData.uvs = uvs;
  30003. return vertexData;
  30004. };
  30005. /**
  30006. * Creates the VertexData of the Disc or regular Polygon.
  30007. */
  30008. VertexData.CreateDisc = function (options) {
  30009. var positions = new Array();
  30010. var indices = new Array();
  30011. var normals = new Array();
  30012. var uvs = new Array();
  30013. var radius = options.radius || 0.5;
  30014. var tessellation = options.tessellation || 64;
  30015. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30016. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30017. // positions and uvs
  30018. positions.push(0, 0, 0); // disc center first
  30019. uvs.push(0.5, 0.5);
  30020. var theta = Math.PI * 2 * arc;
  30021. var step = theta / tessellation;
  30022. for (var a = 0; a < theta; a += step) {
  30023. var x = Math.cos(a);
  30024. var y = Math.sin(a);
  30025. var u = (x + 1) / 2;
  30026. var v = (1 - y) / 2;
  30027. positions.push(radius * x, radius * y, 0);
  30028. uvs.push(u, v);
  30029. }
  30030. if (arc === 1) {
  30031. positions.push(positions[3], positions[4], positions[5]); // close the circle
  30032. uvs.push(uvs[2], uvs[3]);
  30033. }
  30034. //indices
  30035. var vertexNb = positions.length / 3;
  30036. for (var i = 1; i < vertexNb - 1; i++) {
  30037. indices.push(i + 1, 0, i);
  30038. }
  30039. // result
  30040. VertexData.ComputeNormals(positions, indices, normals);
  30041. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30042. var vertexData = new VertexData();
  30043. vertexData.indices = indices;
  30044. vertexData.positions = positions;
  30045. vertexData.normals = normals;
  30046. vertexData.uvs = uvs;
  30047. return vertexData;
  30048. };
  30049. /**
  30050. * Re-creates the VertexData of the Polygon for sideOrientation.
  30051. */
  30052. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  30053. var faceUV = fUV || new Array(3);
  30054. var faceColors = fColors;
  30055. var colors = [];
  30056. // default face colors and UV if undefined
  30057. for (var f = 0; f < 3; f++) {
  30058. if (faceUV[f] === undefined) {
  30059. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30060. }
  30061. if (faceColors && faceColors[f] === undefined) {
  30062. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30063. }
  30064. }
  30065. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30066. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30067. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30068. var indices = polygon.getIndices();
  30069. // set face colours and textures
  30070. var idx = 0;
  30071. var face = 0;
  30072. for (var index = 0; index < normals.length; index += 3) {
  30073. //Edge Face no. 1
  30074. if (Math.abs(normals[index + 1]) < 0.001) {
  30075. face = 1;
  30076. }
  30077. //Top Face no. 0
  30078. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  30079. face = 0;
  30080. }
  30081. //Bottom Face no. 2
  30082. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  30083. face = 2;
  30084. }
  30085. idx = index / 3;
  30086. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  30087. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  30088. if (faceColors) {
  30089. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  30090. }
  30091. }
  30092. // sides
  30093. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  30094. // Result
  30095. var vertexData = new VertexData();
  30096. vertexData.indices = indices;
  30097. vertexData.positions = positions;
  30098. vertexData.normals = normals;
  30099. vertexData.uvs = uvs;
  30100. if (faceColors) {
  30101. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30102. vertexData.colors = totalColors;
  30103. }
  30104. return vertexData;
  30105. };
  30106. /**
  30107. * Creates the VertexData of the IcoSphere.
  30108. */
  30109. VertexData.CreateIcoSphere = function (options) {
  30110. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30111. var radius = options.radius || 1;
  30112. var flat = (options.flat === undefined) ? true : options.flat;
  30113. var subdivisions = options.subdivisions || 4;
  30114. var radiusX = options.radiusX || radius;
  30115. var radiusY = options.radiusY || radius;
  30116. var radiusZ = options.radiusZ || radius;
  30117. var t = (1 + Math.sqrt(5)) / 2;
  30118. // 12 vertex x,y,z
  30119. var ico_vertices = [
  30120. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  30121. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  30122. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  30123. ];
  30124. // index of 3 vertex makes a face of icopshere
  30125. var ico_indices = [
  30126. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  30127. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  30128. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  30129. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  30130. ];
  30131. // vertex for uv have aliased position, not for UV
  30132. var vertices_unalias_id = [
  30133. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  30134. // vertex alias
  30135. 0,
  30136. 2,
  30137. 3,
  30138. 3,
  30139. 3,
  30140. 4,
  30141. 7,
  30142. 8,
  30143. 9,
  30144. 9,
  30145. 10,
  30146. 11 // 23: B + 12
  30147. ];
  30148. // uv as integer step (not pixels !)
  30149. var ico_vertexuv = [
  30150. 5, 1, 3, 1, 6, 4, 0, 0,
  30151. 5, 3, 4, 2, 2, 2, 4, 0,
  30152. 2, 0, 1, 1, 6, 0, 6, 2,
  30153. // vertex alias (for same vertex on different faces)
  30154. 0, 4,
  30155. 3, 3,
  30156. 4, 4,
  30157. 3, 1,
  30158. 4, 2,
  30159. 4, 4,
  30160. 0, 2,
  30161. 1, 1,
  30162. 2, 2,
  30163. 3, 3,
  30164. 1, 3,
  30165. 2, 4 // 23: B + 12
  30166. ];
  30167. // Vertices[0, 1, ...9, A, B] : position on UV plane
  30168. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  30169. // First island of uv mapping
  30170. // v = 4h 3+ 2
  30171. // v = 3h 9+ 4
  30172. // v = 2h 9+ 5 B
  30173. // v = 1h 9 1 0
  30174. // v = 0h 3 8 7 A
  30175. // u = 0 1 2 3 4 5 6 *a
  30176. // Second island of uv mapping
  30177. // v = 4h 0+ B+ 4+
  30178. // v = 3h A+ 2+
  30179. // v = 2h 7+ 6 3+
  30180. // v = 1h 8+ 3+
  30181. // v = 0h
  30182. // u = 0 1 2 3 4 5 6 *a
  30183. // Face layout on texture UV mapping
  30184. // ============
  30185. // \ 4 /\ 16 / ======
  30186. // \ / \ / /\ 11 /
  30187. // \/ 7 \/ / \ /
  30188. // ======= / 10 \/
  30189. // /\ 17 /\ =======
  30190. // / \ / \ \ 15 /\
  30191. // / 8 \/ 12 \ \ / \
  30192. // ============ \/ 6 \
  30193. // \ 18 /\ ============
  30194. // \ / \ \ 5 /\ 0 /
  30195. // \/ 13 \ \ / \ /
  30196. // ======= \/ 1 \/
  30197. // =============
  30198. // /\ 19 /\ 2 /\
  30199. // / \ / \ / \
  30200. // / 14 \/ 9 \/ 3 \
  30201. // ===================
  30202. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  30203. var ustep = 138 / 1024;
  30204. var vstep = 239 / 1024;
  30205. var uoffset = 60 / 1024;
  30206. var voffset = 26 / 1024;
  30207. // Second island should have margin, not to touch the first island
  30208. // avoid any borderline artefact in pixel rounding
  30209. var island_u_offset = -40 / 1024;
  30210. var island_v_offset = +20 / 1024;
  30211. // face is either island 0 or 1 :
  30212. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  30213. var island = [
  30214. 0, 0, 0, 0, 1,
  30215. 0, 0, 1, 1, 0,
  30216. 0, 0, 1, 1, 0,
  30217. 0, 1, 1, 1, 0 // 15 - 19
  30218. ];
  30219. var indices = new Array();
  30220. var positions = new Array();
  30221. var normals = new Array();
  30222. var uvs = new Array();
  30223. var current_indice = 0;
  30224. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  30225. var face_vertex_pos = new Array(3);
  30226. var face_vertex_uv = new Array(3);
  30227. var v012;
  30228. for (v012 = 0; v012 < 3; v012++) {
  30229. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  30230. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  30231. }
  30232. // create all with normals
  30233. for (var face = 0; face < 20; face++) {
  30234. // 3 vertex per face
  30235. for (v012 = 0; v012 < 3; v012++) {
  30236. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  30237. var v_id = ico_indices[3 * face + v012];
  30238. // vertex have 3D position (x,y,z)
  30239. 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]);
  30240. // Normalize to get normal, then scale to radius
  30241. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  30242. // uv Coordinates from vertex ID
  30243. 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);
  30244. }
  30245. // Subdivide the face (interpolate pos, norm, uv)
  30246. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  30247. // - norm is linear interpolation of vertex corner normal
  30248. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  30249. // - uv is linear interpolation
  30250. //
  30251. // Topology is as below for sub-divide by 2
  30252. // vertex shown as v0,v1,v2
  30253. // interp index is i1 to progress in range [v0,v1[
  30254. // interp index is i2 to progress in range [v0,v2[
  30255. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  30256. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30257. //
  30258. //
  30259. // i2 v2
  30260. // ^ ^
  30261. // / / \
  30262. // / / \
  30263. // / / \
  30264. // / / (0,1) \
  30265. // / #---------\
  30266. // / / \ (0,0)'/ \
  30267. // / / \ / \
  30268. // / / \ / \
  30269. // / / (0,0) \ / (1,0) \
  30270. // / #---------#---------\
  30271. // v0 v1
  30272. //
  30273. // --------------------> i1
  30274. //
  30275. // interp of (i1,i2):
  30276. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  30277. // along i1 : lerp(x0,x1, i1/(S-i2))
  30278. //
  30279. // centroid of triangle is needed to get help normal computation
  30280. // (c1,c2) are used for centroid location
  30281. var interp_vertex = function (i1, i2, c1, c2) {
  30282. // vertex is interpolated from
  30283. // - face_vertex_pos[0..2]
  30284. // - face_vertex_uv[0..2]
  30285. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  30286. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  30287. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  30288. pos_interp.normalize();
  30289. var vertex_normal;
  30290. if (flat) {
  30291. // in flat mode, recalculate normal as face centroid normal
  30292. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  30293. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  30294. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  30295. }
  30296. else {
  30297. // in smooth mode, recalculate normal from each single vertex position
  30298. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  30299. }
  30300. // Vertex normal need correction due to X,Y,Z radius scaling
  30301. vertex_normal.x /= radiusX;
  30302. vertex_normal.y /= radiusY;
  30303. vertex_normal.z /= radiusZ;
  30304. vertex_normal.normalize();
  30305. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  30306. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  30307. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  30308. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  30309. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  30310. uvs.push(uv_interp.x, uv_interp.y);
  30311. // push each vertex has member of a face
  30312. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  30313. indices.push(current_indice);
  30314. current_indice++;
  30315. };
  30316. for (var i2 = 0; i2 < subdivisions; i2++) {
  30317. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  30318. // face : (i1,i2) for /\ :
  30319. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  30320. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30321. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30322. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30323. if (i1 + i2 + 1 < subdivisions) {
  30324. // face : (i1,i2)' for \/ :
  30325. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30326. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30327. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30328. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30329. }
  30330. }
  30331. }
  30332. }
  30333. // Sides
  30334. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30335. // Result
  30336. var vertexData = new VertexData();
  30337. vertexData.indices = indices;
  30338. vertexData.positions = positions;
  30339. vertexData.normals = normals;
  30340. vertexData.uvs = uvs;
  30341. return vertexData;
  30342. };
  30343. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  30344. /**
  30345. * Creates the VertexData of the Polyhedron.
  30346. */
  30347. VertexData.CreatePolyhedron = function (options) {
  30348. // provided polyhedron types :
  30349. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  30350. // 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)
  30351. var polyhedra = [];
  30352. 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]] };
  30353. 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]] };
  30354. polyhedra[2] = {
  30355. 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]],
  30356. 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]]
  30357. };
  30358. polyhedra[3] = {
  30359. 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]],
  30360. 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]]
  30361. };
  30362. polyhedra[4] = {
  30363. 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]],
  30364. 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]]
  30365. };
  30366. 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]] };
  30367. 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]] };
  30368. 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]] };
  30369. 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]] };
  30370. 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]] };
  30371. 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]] };
  30372. 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]] };
  30373. 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]] };
  30374. 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]] };
  30375. polyhedra[14] = {
  30376. 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]],
  30377. 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]]
  30378. };
  30379. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  30380. var size = options.size;
  30381. var sizeX = options.sizeX || size || 1;
  30382. var sizeY = options.sizeY || size || 1;
  30383. var sizeZ = options.sizeZ || size || 1;
  30384. var data = options.custom || polyhedra[type];
  30385. var nbfaces = data.face.length;
  30386. var faceUV = options.faceUV || new Array(nbfaces);
  30387. var faceColors = options.faceColors;
  30388. var flat = (options.flat === undefined) ? true : options.flat;
  30389. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30390. var positions = new Array();
  30391. var indices = new Array();
  30392. var normals = new Array();
  30393. var uvs = new Array();
  30394. var colors = new Array();
  30395. var index = 0;
  30396. var faceIdx = 0; // face cursor in the array "indexes"
  30397. var indexes = new Array();
  30398. var i = 0;
  30399. var f = 0;
  30400. var u, v, ang, x, y, tmp;
  30401. // default face colors and UV if undefined
  30402. if (flat) {
  30403. for (f = 0; f < nbfaces; f++) {
  30404. if (faceColors && faceColors[f] === undefined) {
  30405. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30406. }
  30407. if (faceUV && faceUV[f] === undefined) {
  30408. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30409. }
  30410. }
  30411. }
  30412. if (!flat) {
  30413. for (i = 0; i < data.vertex.length; i++) {
  30414. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  30415. uvs.push(0, 0);
  30416. }
  30417. for (f = 0; f < nbfaces; f++) {
  30418. for (i = 0; i < data.face[f].length - 2; i++) {
  30419. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  30420. }
  30421. }
  30422. }
  30423. else {
  30424. for (f = 0; f < nbfaces; f++) {
  30425. var fl = data.face[f].length; // number of vertices of the current face
  30426. ang = 2 * Math.PI / fl;
  30427. x = 0.5 * Math.tan(ang / 2);
  30428. y = 0.5;
  30429. // positions, uvs, colors
  30430. for (i = 0; i < fl; i++) {
  30431. // positions
  30432. 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);
  30433. indexes.push(index);
  30434. index++;
  30435. // uvs
  30436. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  30437. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  30438. uvs.push(u, v);
  30439. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  30440. y = x * Math.sin(ang) + y * Math.cos(ang);
  30441. x = tmp;
  30442. // colors
  30443. if (faceColors) {
  30444. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  30445. }
  30446. }
  30447. // indices from indexes
  30448. for (i = 0; i < fl - 2; i++) {
  30449. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  30450. }
  30451. faceIdx += fl;
  30452. }
  30453. }
  30454. VertexData.ComputeNormals(positions, indices, normals);
  30455. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30456. var vertexData = new VertexData();
  30457. vertexData.positions = positions;
  30458. vertexData.indices = indices;
  30459. vertexData.normals = normals;
  30460. vertexData.uvs = uvs;
  30461. if (faceColors && flat) {
  30462. vertexData.colors = colors;
  30463. }
  30464. return vertexData;
  30465. };
  30466. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  30467. /**
  30468. * Creates the VertexData of the Torus Knot.
  30469. */
  30470. VertexData.CreateTorusKnot = function (options) {
  30471. var indices = new Array();
  30472. var positions = new Array();
  30473. var normals = new Array();
  30474. var uvs = new Array();
  30475. var radius = options.radius || 2;
  30476. var tube = options.tube || 0.5;
  30477. var radialSegments = options.radialSegments || 32;
  30478. var tubularSegments = options.tubularSegments || 32;
  30479. var p = options.p || 2;
  30480. var q = options.q || 3;
  30481. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30482. // Helper
  30483. var getPos = function (angle) {
  30484. var cu = Math.cos(angle);
  30485. var su = Math.sin(angle);
  30486. var quOverP = q / p * angle;
  30487. var cs = Math.cos(quOverP);
  30488. var tx = radius * (2 + cs) * 0.5 * cu;
  30489. var ty = radius * (2 + cs) * su * 0.5;
  30490. var tz = radius * Math.sin(quOverP) * 0.5;
  30491. return new BABYLON.Vector3(tx, ty, tz);
  30492. };
  30493. // Vertices
  30494. var i;
  30495. var j;
  30496. for (i = 0; i <= radialSegments; i++) {
  30497. var modI = i % radialSegments;
  30498. var u = modI / radialSegments * 2 * p * Math.PI;
  30499. var p1 = getPos(u);
  30500. var p2 = getPos(u + 0.01);
  30501. var tang = p2.subtract(p1);
  30502. var n = p2.add(p1);
  30503. var bitan = BABYLON.Vector3.Cross(tang, n);
  30504. n = BABYLON.Vector3.Cross(bitan, tang);
  30505. bitan.normalize();
  30506. n.normalize();
  30507. for (j = 0; j < tubularSegments; j++) {
  30508. var modJ = j % tubularSegments;
  30509. var v = modJ / tubularSegments * 2 * Math.PI;
  30510. var cx = -tube * Math.cos(v);
  30511. var cy = tube * Math.sin(v);
  30512. positions.push(p1.x + cx * n.x + cy * bitan.x);
  30513. positions.push(p1.y + cx * n.y + cy * bitan.y);
  30514. positions.push(p1.z + cx * n.z + cy * bitan.z);
  30515. uvs.push(i / radialSegments);
  30516. uvs.push(j / tubularSegments);
  30517. }
  30518. }
  30519. for (i = 0; i < radialSegments; i++) {
  30520. for (j = 0; j < tubularSegments; j++) {
  30521. var jNext = (j + 1) % tubularSegments;
  30522. var a = i * tubularSegments + j;
  30523. var b = (i + 1) * tubularSegments + j;
  30524. var c = (i + 1) * tubularSegments + jNext;
  30525. var d = i * tubularSegments + jNext;
  30526. indices.push(d);
  30527. indices.push(b);
  30528. indices.push(a);
  30529. indices.push(d);
  30530. indices.push(c);
  30531. indices.push(b);
  30532. }
  30533. }
  30534. // Normals
  30535. VertexData.ComputeNormals(positions, indices, normals);
  30536. // Sides
  30537. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30538. // Result
  30539. var vertexData = new VertexData();
  30540. vertexData.indices = indices;
  30541. vertexData.positions = positions;
  30542. vertexData.normals = normals;
  30543. vertexData.uvs = uvs;
  30544. return vertexData;
  30545. };
  30546. // Tools
  30547. /**
  30548. * @param {any} - positions (number[] or Float32Array)
  30549. * @param {any} - indices (number[] or Uint16Array)
  30550. * @param {any} - normals (number[] or Float32Array)
  30551. * options (optional) :
  30552. * facetPositions : optional array of facet positions (vector3)
  30553. * facetNormals : optional array of facet normals (vector3)
  30554. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  30555. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  30556. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  30557. * bbSize : optional bounding box size data, required for facetPartitioning computation
  30558. * bInfo : optional bounding info, required for facetPartitioning computation
  30559. * useRightHandedSystem: optional boolean to for right handed system computation
  30560. * depthSort : optional boolean to enable the facet depth sort computation
  30561. * distanceTo : optional Vector3 to compute the facet depth from this location
  30562. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  30563. */
  30564. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  30565. // temporary scalar variables
  30566. var index = 0; // facet index
  30567. var p1p2x = 0.0; // p1p2 vector x coordinate
  30568. var p1p2y = 0.0; // p1p2 vector y coordinate
  30569. var p1p2z = 0.0; // p1p2 vector z coordinate
  30570. var p3p2x = 0.0; // p3p2 vector x coordinate
  30571. var p3p2y = 0.0; // p3p2 vector y coordinate
  30572. var p3p2z = 0.0; // p3p2 vector z coordinate
  30573. var faceNormalx = 0.0; // facet normal x coordinate
  30574. var faceNormaly = 0.0; // facet normal y coordinate
  30575. var faceNormalz = 0.0; // facet normal z coordinate
  30576. var length = 0.0; // facet normal length before normalization
  30577. var v1x = 0; // vector1 x index in the positions array
  30578. var v1y = 0; // vector1 y index in the positions array
  30579. var v1z = 0; // vector1 z index in the positions array
  30580. var v2x = 0; // vector2 x index in the positions array
  30581. var v2y = 0; // vector2 y index in the positions array
  30582. var v2z = 0; // vector2 z index in the positions array
  30583. var v3x = 0; // vector3 x index in the positions array
  30584. var v3y = 0; // vector3 y index in the positions array
  30585. var v3z = 0; // vector3 z index in the positions array
  30586. var computeFacetNormals = false;
  30587. var computeFacetPositions = false;
  30588. var computeFacetPartitioning = false;
  30589. var computeDepthSort = false;
  30590. var faceNormalSign = 1;
  30591. var ratio = 0;
  30592. var distanceTo = null;
  30593. if (options) {
  30594. computeFacetNormals = (options.facetNormals) ? true : false;
  30595. computeFacetPositions = (options.facetPositions) ? true : false;
  30596. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  30597. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  30598. ratio = options.ratio || 0;
  30599. computeDepthSort = (options.depthSort) ? true : false;
  30600. distanceTo = (options.distanceTo);
  30601. if (computeDepthSort) {
  30602. if (distanceTo === undefined) {
  30603. distanceTo = BABYLON.Vector3.Zero();
  30604. }
  30605. var depthSortedFacets = options.depthSortedFacets;
  30606. }
  30607. }
  30608. // facetPartitioning reinit if needed
  30609. var xSubRatio = 0;
  30610. var ySubRatio = 0;
  30611. var zSubRatio = 0;
  30612. var subSq = 0;
  30613. if (computeFacetPartitioning && options && options.bbSize) {
  30614. var ox = 0; // X partitioning index for facet position
  30615. var oy = 0; // Y partinioning index for facet position
  30616. var oz = 0; // Z partinioning index for facet position
  30617. var b1x = 0; // X partitioning index for facet v1 vertex
  30618. var b1y = 0; // Y partitioning index for facet v1 vertex
  30619. var b1z = 0; // z partitioning index for facet v1 vertex
  30620. var b2x = 0; // X partitioning index for facet v2 vertex
  30621. var b2y = 0; // Y partitioning index for facet v2 vertex
  30622. var b2z = 0; // Z partitioning index for facet v2 vertex
  30623. var b3x = 0; // X partitioning index for facet v3 vertex
  30624. var b3y = 0; // Y partitioning index for facet v3 vertex
  30625. var b3z = 0; // Z partitioning index for facet v3 vertex
  30626. var block_idx_o = 0; // facet barycenter block index
  30627. var block_idx_v1 = 0; // v1 vertex block index
  30628. var block_idx_v2 = 0; // v2 vertex block index
  30629. var block_idx_v3 = 0; // v3 vertex block index
  30630. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  30631. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  30632. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  30633. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  30634. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  30635. subSq = options.subDiv.max * options.subDiv.max;
  30636. options.facetPartitioning.length = 0;
  30637. }
  30638. // reset the normals
  30639. for (index = 0; index < positions.length; index++) {
  30640. normals[index] = 0.0;
  30641. }
  30642. // Loop : 1 indice triplet = 1 facet
  30643. var nbFaces = (indices.length / 3) | 0;
  30644. for (index = 0; index < nbFaces; index++) {
  30645. // get the indexes of the coordinates of each vertex of the facet
  30646. v1x = indices[index * 3] * 3;
  30647. v1y = v1x + 1;
  30648. v1z = v1x + 2;
  30649. v2x = indices[index * 3 + 1] * 3;
  30650. v2y = v2x + 1;
  30651. v2z = v2x + 2;
  30652. v3x = indices[index * 3 + 2] * 3;
  30653. v3y = v3x + 1;
  30654. v3z = v3x + 2;
  30655. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  30656. p1p2y = positions[v1y] - positions[v2y];
  30657. p1p2z = positions[v1z] - positions[v2z];
  30658. p3p2x = positions[v3x] - positions[v2x];
  30659. p3p2y = positions[v3y] - positions[v2y];
  30660. p3p2z = positions[v3z] - positions[v2z];
  30661. // compute the face normal with the cross product
  30662. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  30663. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  30664. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  30665. // normalize this normal and store it in the array facetData
  30666. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30667. length = (length === 0) ? 1.0 : length;
  30668. faceNormalx /= length;
  30669. faceNormaly /= length;
  30670. faceNormalz /= length;
  30671. if (computeFacetNormals && options) {
  30672. options.facetNormals[index].x = faceNormalx;
  30673. options.facetNormals[index].y = faceNormaly;
  30674. options.facetNormals[index].z = faceNormalz;
  30675. }
  30676. if (computeFacetPositions && options) {
  30677. // compute and the facet barycenter coordinates in the array facetPositions
  30678. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  30679. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  30680. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  30681. }
  30682. if (computeFacetPartitioning && options) {
  30683. // store the facet indexes in arrays in the main facetPartitioning array :
  30684. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  30685. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  30686. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  30687. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  30688. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30689. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30690. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30691. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30692. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30693. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30694. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30695. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30696. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30697. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  30698. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  30699. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  30700. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  30701. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  30702. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  30703. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  30704. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  30705. // push each facet index in each block containing the vertex
  30706. options.facetPartitioning[block_idx_v1].push(index);
  30707. if (block_idx_v2 != block_idx_v1) {
  30708. options.facetPartitioning[block_idx_v2].push(index);
  30709. }
  30710. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  30711. options.facetPartitioning[block_idx_v3].push(index);
  30712. }
  30713. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  30714. options.facetPartitioning[block_idx_o].push(index);
  30715. }
  30716. }
  30717. if (computeDepthSort && options && options.facetPositions) {
  30718. var dsf = depthSortedFacets[index];
  30719. dsf.ind = index * 3;
  30720. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  30721. }
  30722. // compute the normals anyway
  30723. normals[v1x] += faceNormalx; // accumulate all the normals per face
  30724. normals[v1y] += faceNormaly;
  30725. normals[v1z] += faceNormalz;
  30726. normals[v2x] += faceNormalx;
  30727. normals[v2y] += faceNormaly;
  30728. normals[v2z] += faceNormalz;
  30729. normals[v3x] += faceNormalx;
  30730. normals[v3y] += faceNormaly;
  30731. normals[v3z] += faceNormalz;
  30732. }
  30733. // last normalization of each normal
  30734. for (index = 0; index < normals.length / 3; index++) {
  30735. faceNormalx = normals[index * 3];
  30736. faceNormaly = normals[index * 3 + 1];
  30737. faceNormalz = normals[index * 3 + 2];
  30738. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30739. length = (length === 0) ? 1.0 : length;
  30740. faceNormalx /= length;
  30741. faceNormaly /= length;
  30742. faceNormalz /= length;
  30743. normals[index * 3] = faceNormalx;
  30744. normals[index * 3 + 1] = faceNormaly;
  30745. normals[index * 3 + 2] = faceNormalz;
  30746. }
  30747. };
  30748. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  30749. var li = indices.length;
  30750. var ln = normals.length;
  30751. var i;
  30752. var n;
  30753. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30754. switch (sideOrientation) {
  30755. case BABYLON.Mesh.FRONTSIDE:
  30756. // nothing changed
  30757. break;
  30758. case BABYLON.Mesh.BACKSIDE:
  30759. var tmp;
  30760. // indices
  30761. for (i = 0; i < li; i += 3) {
  30762. tmp = indices[i];
  30763. indices[i] = indices[i + 2];
  30764. indices[i + 2] = tmp;
  30765. }
  30766. // normals
  30767. for (n = 0; n < ln; n++) {
  30768. normals[n] = -normals[n];
  30769. }
  30770. break;
  30771. case BABYLON.Mesh.DOUBLESIDE:
  30772. // positions
  30773. var lp = positions.length;
  30774. var l = lp / 3;
  30775. for (var p = 0; p < lp; p++) {
  30776. positions[lp + p] = positions[p];
  30777. }
  30778. // indices
  30779. for (i = 0; i < li; i += 3) {
  30780. indices[i + li] = indices[i + 2] + l;
  30781. indices[i + 1 + li] = indices[i + 1] + l;
  30782. indices[i + 2 + li] = indices[i] + l;
  30783. }
  30784. // normals
  30785. for (n = 0; n < ln; n++) {
  30786. normals[ln + n] = -normals[n];
  30787. }
  30788. // uvs
  30789. var lu = uvs.length;
  30790. var u = 0;
  30791. for (u = 0; u < lu; u++) {
  30792. uvs[u + lu] = uvs[u];
  30793. }
  30794. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  30795. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  30796. u = 0;
  30797. for (i = 0; i < lu / 2; i++) {
  30798. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  30799. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  30800. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  30801. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  30802. u += 2;
  30803. }
  30804. break;
  30805. }
  30806. };
  30807. /**
  30808. * Creates a new VertexData from the imported parameters.
  30809. */
  30810. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  30811. var vertexData = new VertexData();
  30812. // positions
  30813. var positions = parsedVertexData.positions;
  30814. if (positions) {
  30815. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  30816. }
  30817. // normals
  30818. var normals = parsedVertexData.normals;
  30819. if (normals) {
  30820. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  30821. }
  30822. // tangents
  30823. var tangents = parsedVertexData.tangents;
  30824. if (tangents) {
  30825. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  30826. }
  30827. // uvs
  30828. var uvs = parsedVertexData.uvs;
  30829. if (uvs) {
  30830. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  30831. }
  30832. // uv2s
  30833. var uv2s = parsedVertexData.uv2s;
  30834. if (uv2s) {
  30835. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  30836. }
  30837. // uv3s
  30838. var uv3s = parsedVertexData.uv3s;
  30839. if (uv3s) {
  30840. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  30841. }
  30842. // uv4s
  30843. var uv4s = parsedVertexData.uv4s;
  30844. if (uv4s) {
  30845. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  30846. }
  30847. // uv5s
  30848. var uv5s = parsedVertexData.uv5s;
  30849. if (uv5s) {
  30850. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  30851. }
  30852. // uv6s
  30853. var uv6s = parsedVertexData.uv6s;
  30854. if (uv6s) {
  30855. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  30856. }
  30857. // colors
  30858. var colors = parsedVertexData.colors;
  30859. if (colors) {
  30860. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  30861. }
  30862. // matricesIndices
  30863. var matricesIndices = parsedVertexData.matricesIndices;
  30864. if (matricesIndices) {
  30865. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  30866. }
  30867. // matricesWeights
  30868. var matricesWeights = parsedVertexData.matricesWeights;
  30869. if (matricesWeights) {
  30870. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  30871. }
  30872. // indices
  30873. var indices = parsedVertexData.indices;
  30874. if (indices) {
  30875. vertexData.indices = indices;
  30876. }
  30877. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  30878. };
  30879. return VertexData;
  30880. }());
  30881. BABYLON.VertexData = VertexData;
  30882. })(BABYLON || (BABYLON = {}));
  30883. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  30884. var BABYLON;
  30885. (function (BABYLON) {
  30886. var Geometry = /** @class */ (function () {
  30887. function Geometry(id, scene, vertexData, updatable, mesh) {
  30888. if (updatable === void 0) { updatable = false; }
  30889. if (mesh === void 0) { mesh = null; }
  30890. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30891. this._totalVertices = 0;
  30892. this._isDisposed = false;
  30893. this._indexBufferIsUpdatable = false;
  30894. this.id = id;
  30895. this._engine = scene.getEngine();
  30896. this._meshes = [];
  30897. this._scene = scene;
  30898. //Init vertex buffer cache
  30899. this._vertexBuffers = {};
  30900. this._indices = [];
  30901. this._updatable = updatable;
  30902. // vertexData
  30903. if (vertexData) {
  30904. this.setAllVerticesData(vertexData, updatable);
  30905. }
  30906. else {
  30907. this._totalVertices = 0;
  30908. this._indices = [];
  30909. }
  30910. if (this._engine.getCaps().vertexArrayObject) {
  30911. this._vertexArrayObjects = {};
  30912. }
  30913. // applyToMesh
  30914. if (mesh) {
  30915. if (mesh.getClassName() === "LinesMesh") {
  30916. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  30917. this.updateExtend();
  30918. }
  30919. this.applyToMesh(mesh);
  30920. mesh.computeWorldMatrix(true);
  30921. }
  30922. }
  30923. Object.defineProperty(Geometry.prototype, "boundingBias", {
  30924. /**
  30925. * 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
  30926. * @returns The Bias Vector
  30927. */
  30928. get: function () {
  30929. return this._boundingBias;
  30930. },
  30931. set: function (value) {
  30932. if (this._boundingBias && this._boundingBias.equals(value)) {
  30933. return;
  30934. }
  30935. this._boundingBias = value.clone();
  30936. this.updateBoundingInfo(true, null);
  30937. },
  30938. enumerable: true,
  30939. configurable: true
  30940. });
  30941. Geometry.CreateGeometryForMesh = function (mesh) {
  30942. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  30943. geometry.applyToMesh(mesh);
  30944. return geometry;
  30945. };
  30946. Object.defineProperty(Geometry.prototype, "extend", {
  30947. get: function () {
  30948. return this._extend;
  30949. },
  30950. enumerable: true,
  30951. configurable: true
  30952. });
  30953. Geometry.prototype.getScene = function () {
  30954. return this._scene;
  30955. };
  30956. Geometry.prototype.getEngine = function () {
  30957. return this._engine;
  30958. };
  30959. Geometry.prototype.isReady = function () {
  30960. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  30961. };
  30962. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  30963. get: function () {
  30964. for (var index = 0; index < this._meshes.length; index++) {
  30965. if (!this._meshes[index].doNotSerialize) {
  30966. return false;
  30967. }
  30968. }
  30969. return true;
  30970. },
  30971. enumerable: true,
  30972. configurable: true
  30973. });
  30974. Geometry.prototype._rebuild = function () {
  30975. if (this._vertexArrayObjects) {
  30976. this._vertexArrayObjects = {};
  30977. }
  30978. // Index buffer
  30979. if (this._meshes.length !== 0 && this._indices) {
  30980. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  30981. }
  30982. // Vertex buffers
  30983. for (var key in this._vertexBuffers) {
  30984. var vertexBuffer = this._vertexBuffers[key];
  30985. vertexBuffer._rebuild();
  30986. }
  30987. };
  30988. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  30989. vertexData.applyToGeometry(this, updatable);
  30990. this.notifyUpdate();
  30991. };
  30992. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  30993. if (updatable === void 0) { updatable = false; }
  30994. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  30995. this.setVerticesBuffer(buffer);
  30996. };
  30997. Geometry.prototype.removeVerticesData = function (kind) {
  30998. if (this._vertexBuffers[kind]) {
  30999. this._vertexBuffers[kind].dispose();
  31000. delete this._vertexBuffers[kind];
  31001. }
  31002. };
  31003. Geometry.prototype.setVerticesBuffer = function (buffer) {
  31004. var kind = buffer.getKind();
  31005. if (this._vertexBuffers[kind]) {
  31006. this._vertexBuffers[kind].dispose();
  31007. }
  31008. this._vertexBuffers[kind] = buffer;
  31009. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31010. var data = buffer.getData();
  31011. var stride = buffer.getStrideSize();
  31012. this._totalVertices = data.length / stride;
  31013. this.updateExtend(data, stride);
  31014. this._resetPointsArrayCache();
  31015. var meshes = this._meshes;
  31016. var numOfMeshes = meshes.length;
  31017. for (var index = 0; index < numOfMeshes; index++) {
  31018. var mesh = meshes[index];
  31019. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31020. mesh._createGlobalSubMesh(false);
  31021. mesh.computeWorldMatrix(true);
  31022. }
  31023. }
  31024. this.notifyUpdate(kind);
  31025. if (this._vertexArrayObjects) {
  31026. this._disposeVertexArrayObjects();
  31027. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  31028. }
  31029. };
  31030. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  31031. var vertexBuffer = this.getVertexBuffer(kind);
  31032. if (!vertexBuffer) {
  31033. return;
  31034. }
  31035. vertexBuffer.updateDirectly(data, offset);
  31036. this.notifyUpdate(kind);
  31037. };
  31038. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  31039. if (updateExtends === void 0) { updateExtends = false; }
  31040. var vertexBuffer = this.getVertexBuffer(kind);
  31041. if (!vertexBuffer) {
  31042. return;
  31043. }
  31044. vertexBuffer.update(data);
  31045. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31046. var stride = vertexBuffer.getStrideSize();
  31047. this._totalVertices = data.length / stride;
  31048. this.updateBoundingInfo(updateExtends, data);
  31049. }
  31050. this.notifyUpdate(kind);
  31051. };
  31052. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  31053. if (updateExtends) {
  31054. this.updateExtend(data);
  31055. }
  31056. var meshes = this._meshes;
  31057. var numOfMeshes = meshes.length;
  31058. this._resetPointsArrayCache();
  31059. for (var index = 0; index < numOfMeshes; index++) {
  31060. var mesh = meshes[index];
  31061. if (updateExtends) {
  31062. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31063. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  31064. var subMesh = mesh.subMeshes[subIndex];
  31065. subMesh.refreshBoundingInfo();
  31066. }
  31067. }
  31068. }
  31069. };
  31070. Geometry.prototype._bind = function (effect, indexToBind) {
  31071. if (!effect) {
  31072. return;
  31073. }
  31074. if (indexToBind === undefined) {
  31075. indexToBind = this._indexBuffer;
  31076. }
  31077. var vbs = this.getVertexBuffers();
  31078. if (!vbs) {
  31079. return;
  31080. }
  31081. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  31082. this._engine.bindBuffers(vbs, indexToBind, effect);
  31083. return;
  31084. }
  31085. // Using VAO
  31086. if (!this._vertexArrayObjects[effect.key]) {
  31087. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  31088. }
  31089. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  31090. };
  31091. Geometry.prototype.getTotalVertices = function () {
  31092. if (!this.isReady()) {
  31093. return 0;
  31094. }
  31095. return this._totalVertices;
  31096. };
  31097. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31098. var vertexBuffer = this.getVertexBuffer(kind);
  31099. if (!vertexBuffer) {
  31100. return null;
  31101. }
  31102. var orig = vertexBuffer.getData();
  31103. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  31104. return orig;
  31105. }
  31106. else {
  31107. var len = orig.length;
  31108. var copy = [];
  31109. for (var i = 0; i < len; i++) {
  31110. copy.push(orig[i]);
  31111. }
  31112. return copy;
  31113. }
  31114. };
  31115. /**
  31116. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31117. * Possible `kind` values :
  31118. * - BABYLON.VertexBuffer.PositionKind
  31119. * - BABYLON.VertexBuffer.UVKind
  31120. * - BABYLON.VertexBuffer.UV2Kind
  31121. * - BABYLON.VertexBuffer.UV3Kind
  31122. * - BABYLON.VertexBuffer.UV4Kind
  31123. * - BABYLON.VertexBuffer.UV5Kind
  31124. * - BABYLON.VertexBuffer.UV6Kind
  31125. * - BABYLON.VertexBuffer.ColorKind
  31126. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31127. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31128. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31129. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31130. */
  31131. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  31132. var vb = this._vertexBuffers[kind];
  31133. if (!vb) {
  31134. return false;
  31135. }
  31136. return vb.isUpdatable();
  31137. };
  31138. Geometry.prototype.getVertexBuffer = function (kind) {
  31139. if (!this.isReady()) {
  31140. return null;
  31141. }
  31142. return this._vertexBuffers[kind];
  31143. };
  31144. Geometry.prototype.getVertexBuffers = function () {
  31145. if (!this.isReady()) {
  31146. return null;
  31147. }
  31148. return this._vertexBuffers;
  31149. };
  31150. Geometry.prototype.isVerticesDataPresent = function (kind) {
  31151. if (!this._vertexBuffers) {
  31152. if (this._delayInfo) {
  31153. return this._delayInfo.indexOf(kind) !== -1;
  31154. }
  31155. return false;
  31156. }
  31157. return this._vertexBuffers[kind] !== undefined;
  31158. };
  31159. Geometry.prototype.getVerticesDataKinds = function () {
  31160. var result = [];
  31161. var kind;
  31162. if (!this._vertexBuffers && this._delayInfo) {
  31163. for (kind in this._delayInfo) {
  31164. result.push(kind);
  31165. }
  31166. }
  31167. else {
  31168. for (kind in this._vertexBuffers) {
  31169. result.push(kind);
  31170. }
  31171. }
  31172. return result;
  31173. };
  31174. Geometry.prototype.updateIndices = function (indices, offset) {
  31175. if (!this._indexBuffer) {
  31176. return;
  31177. }
  31178. if (!this._indexBufferIsUpdatable) {
  31179. this.setIndices(indices, null, true);
  31180. }
  31181. else {
  31182. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  31183. }
  31184. };
  31185. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  31186. if (totalVertices === void 0) { totalVertices = null; }
  31187. if (updatable === void 0) { updatable = false; }
  31188. if (this._indexBuffer) {
  31189. this._engine._releaseBuffer(this._indexBuffer);
  31190. }
  31191. this._disposeVertexArrayObjects();
  31192. this._indices = indices;
  31193. this._indexBufferIsUpdatable = updatable;
  31194. if (this._meshes.length !== 0 && this._indices) {
  31195. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  31196. }
  31197. if (totalVertices != undefined) {
  31198. this._totalVertices = totalVertices;
  31199. }
  31200. var meshes = this._meshes;
  31201. var numOfMeshes = meshes.length;
  31202. for (var index = 0; index < numOfMeshes; index++) {
  31203. meshes[index]._createGlobalSubMesh(true);
  31204. }
  31205. this.notifyUpdate();
  31206. };
  31207. Geometry.prototype.getTotalIndices = function () {
  31208. if (!this.isReady()) {
  31209. return 0;
  31210. }
  31211. return this._indices.length;
  31212. };
  31213. Geometry.prototype.getIndices = function (copyWhenShared) {
  31214. if (!this.isReady()) {
  31215. return null;
  31216. }
  31217. var orig = this._indices;
  31218. if (!copyWhenShared || this._meshes.length === 1) {
  31219. return orig;
  31220. }
  31221. else {
  31222. var len = orig.length;
  31223. var copy = [];
  31224. for (var i = 0; i < len; i++) {
  31225. copy.push(orig[i]);
  31226. }
  31227. return copy;
  31228. }
  31229. };
  31230. Geometry.prototype.getIndexBuffer = function () {
  31231. if (!this.isReady()) {
  31232. return null;
  31233. }
  31234. return this._indexBuffer;
  31235. };
  31236. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  31237. if (effect === void 0) { effect = null; }
  31238. if (!effect || !this._vertexArrayObjects) {
  31239. return;
  31240. }
  31241. if (this._vertexArrayObjects[effect.key]) {
  31242. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  31243. delete this._vertexArrayObjects[effect.key];
  31244. }
  31245. };
  31246. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  31247. var meshes = this._meshes;
  31248. var index = meshes.indexOf(mesh);
  31249. if (index === -1) {
  31250. return;
  31251. }
  31252. meshes.splice(index, 1);
  31253. mesh._geometry = null;
  31254. if (meshes.length === 0 && shouldDispose) {
  31255. this.dispose();
  31256. }
  31257. };
  31258. Geometry.prototype.applyToMesh = function (mesh) {
  31259. if (mesh._geometry === this) {
  31260. return;
  31261. }
  31262. var previousGeometry = mesh._geometry;
  31263. if (previousGeometry) {
  31264. previousGeometry.releaseForMesh(mesh);
  31265. }
  31266. var meshes = this._meshes;
  31267. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  31268. mesh._geometry = this;
  31269. this._scene.pushGeometry(this);
  31270. meshes.push(mesh);
  31271. if (this.isReady()) {
  31272. this._applyToMesh(mesh);
  31273. }
  31274. else {
  31275. mesh._boundingInfo = this._boundingInfo;
  31276. }
  31277. };
  31278. Geometry.prototype.updateExtend = function (data, stride) {
  31279. if (data === void 0) { data = null; }
  31280. if (!data) {
  31281. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  31282. }
  31283. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  31284. };
  31285. Geometry.prototype._applyToMesh = function (mesh) {
  31286. var numOfMeshes = this._meshes.length;
  31287. // vertexBuffers
  31288. for (var kind in this._vertexBuffers) {
  31289. if (numOfMeshes === 1) {
  31290. this._vertexBuffers[kind].create();
  31291. }
  31292. var buffer = this._vertexBuffers[kind].getBuffer();
  31293. if (buffer)
  31294. buffer.references = numOfMeshes;
  31295. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31296. if (!this._extend) {
  31297. this.updateExtend(this._vertexBuffers[kind].getData());
  31298. }
  31299. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31300. mesh._createGlobalSubMesh(false);
  31301. //bounding info was just created again, world matrix should be applied again.
  31302. mesh._updateBoundingInfo();
  31303. }
  31304. }
  31305. // indexBuffer
  31306. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  31307. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31308. }
  31309. if (this._indexBuffer) {
  31310. this._indexBuffer.references = numOfMeshes;
  31311. }
  31312. };
  31313. Geometry.prototype.notifyUpdate = function (kind) {
  31314. if (this.onGeometryUpdated) {
  31315. this.onGeometryUpdated(this, kind);
  31316. }
  31317. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  31318. var mesh = _a[_i];
  31319. mesh._markSubMeshesAsAttributesDirty();
  31320. }
  31321. };
  31322. Geometry.prototype.load = function (scene, onLoaded) {
  31323. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31324. return;
  31325. }
  31326. if (this.isReady()) {
  31327. if (onLoaded) {
  31328. onLoaded();
  31329. }
  31330. return;
  31331. }
  31332. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31333. this._queueLoad(scene, onLoaded);
  31334. };
  31335. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  31336. var _this = this;
  31337. if (!this.delayLoadingFile) {
  31338. return;
  31339. }
  31340. scene._addPendingData(this);
  31341. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  31342. if (!_this._delayLoadingFunction) {
  31343. return;
  31344. }
  31345. _this._delayLoadingFunction(JSON.parse(data), _this);
  31346. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31347. _this._delayInfo = [];
  31348. scene._removePendingData(_this);
  31349. var meshes = _this._meshes;
  31350. var numOfMeshes = meshes.length;
  31351. for (var index = 0; index < numOfMeshes; index++) {
  31352. _this._applyToMesh(meshes[index]);
  31353. }
  31354. if (onLoaded) {
  31355. onLoaded();
  31356. }
  31357. }, function () { }, scene.database);
  31358. };
  31359. /**
  31360. * Invert the geometry to move from a right handed system to a left handed one.
  31361. */
  31362. Geometry.prototype.toLeftHanded = function () {
  31363. // Flip faces
  31364. var tIndices = this.getIndices(false);
  31365. if (tIndices != null && tIndices.length > 0) {
  31366. for (var i = 0; i < tIndices.length; i += 3) {
  31367. var tTemp = tIndices[i + 0];
  31368. tIndices[i + 0] = tIndices[i + 2];
  31369. tIndices[i + 2] = tTemp;
  31370. }
  31371. this.setIndices(tIndices);
  31372. }
  31373. // Negate position.z
  31374. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  31375. if (tPositions != null && tPositions.length > 0) {
  31376. for (var i = 0; i < tPositions.length; i += 3) {
  31377. tPositions[i + 2] = -tPositions[i + 2];
  31378. }
  31379. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  31380. }
  31381. // Negate normal.z
  31382. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  31383. if (tNormals != null && tNormals.length > 0) {
  31384. for (var i = 0; i < tNormals.length; i += 3) {
  31385. tNormals[i + 2] = -tNormals[i + 2];
  31386. }
  31387. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  31388. }
  31389. };
  31390. // Cache
  31391. Geometry.prototype._resetPointsArrayCache = function () {
  31392. this._positions = null;
  31393. };
  31394. Geometry.prototype._generatePointsArray = function () {
  31395. if (this._positions)
  31396. return true;
  31397. this._positions = [];
  31398. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31399. if (!data) {
  31400. return false;
  31401. }
  31402. for (var index = 0; index < data.length; index += 3) {
  31403. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  31404. }
  31405. return true;
  31406. };
  31407. Geometry.prototype.isDisposed = function () {
  31408. return this._isDisposed;
  31409. };
  31410. Geometry.prototype._disposeVertexArrayObjects = function () {
  31411. if (this._vertexArrayObjects) {
  31412. for (var kind in this._vertexArrayObjects) {
  31413. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  31414. }
  31415. this._vertexArrayObjects = {};
  31416. }
  31417. };
  31418. Geometry.prototype.dispose = function () {
  31419. var meshes = this._meshes;
  31420. var numOfMeshes = meshes.length;
  31421. var index;
  31422. for (index = 0; index < numOfMeshes; index++) {
  31423. this.releaseForMesh(meshes[index]);
  31424. }
  31425. this._meshes = [];
  31426. this._disposeVertexArrayObjects();
  31427. for (var kind in this._vertexBuffers) {
  31428. this._vertexBuffers[kind].dispose();
  31429. }
  31430. this._vertexBuffers = {};
  31431. this._totalVertices = 0;
  31432. if (this._indexBuffer) {
  31433. this._engine._releaseBuffer(this._indexBuffer);
  31434. }
  31435. this._indexBuffer = null;
  31436. this._indices = [];
  31437. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31438. this.delayLoadingFile = null;
  31439. this._delayLoadingFunction = null;
  31440. this._delayInfo = [];
  31441. this._boundingInfo = null;
  31442. this._scene.removeGeometry(this);
  31443. this._isDisposed = true;
  31444. };
  31445. Geometry.prototype.copy = function (id) {
  31446. var vertexData = new BABYLON.VertexData();
  31447. vertexData.indices = [];
  31448. var indices = this.getIndices();
  31449. if (indices) {
  31450. for (var index = 0; index < indices.length; index++) {
  31451. vertexData.indices.push(indices[index]);
  31452. }
  31453. }
  31454. var updatable = false;
  31455. var stopChecking = false;
  31456. var kind;
  31457. for (kind in this._vertexBuffers) {
  31458. // using slice() to make a copy of the array and not just reference it
  31459. var data = this.getVerticesData(kind);
  31460. if (data instanceof Float32Array) {
  31461. vertexData.set(new Float32Array(data), kind);
  31462. }
  31463. else {
  31464. vertexData.set(data.slice(0), kind);
  31465. }
  31466. if (!stopChecking) {
  31467. var vb = this.getVertexBuffer(kind);
  31468. if (vb) {
  31469. updatable = vb.isUpdatable();
  31470. stopChecking = !updatable;
  31471. }
  31472. }
  31473. }
  31474. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  31475. geometry.delayLoadState = this.delayLoadState;
  31476. geometry.delayLoadingFile = this.delayLoadingFile;
  31477. geometry._delayLoadingFunction = this._delayLoadingFunction;
  31478. for (kind in this._delayInfo) {
  31479. geometry._delayInfo = geometry._delayInfo || [];
  31480. geometry._delayInfo.push(kind);
  31481. }
  31482. // Bounding info
  31483. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31484. return geometry;
  31485. };
  31486. Geometry.prototype.serialize = function () {
  31487. var serializationObject = {};
  31488. serializationObject.id = this.id;
  31489. serializationObject.updatable = this._updatable;
  31490. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  31491. serializationObject.tags = BABYLON.Tags.GetTags(this);
  31492. }
  31493. return serializationObject;
  31494. };
  31495. Geometry.prototype.toNumberArray = function (origin) {
  31496. if (Array.isArray(origin)) {
  31497. return origin;
  31498. }
  31499. else {
  31500. return Array.prototype.slice.call(origin);
  31501. }
  31502. };
  31503. Geometry.prototype.serializeVerticeData = function () {
  31504. var serializationObject = this.serialize();
  31505. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31506. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  31507. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  31508. serializationObject.positions._updatable = true;
  31509. }
  31510. }
  31511. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31512. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  31513. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  31514. serializationObject.normals._updatable = true;
  31515. }
  31516. }
  31517. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31518. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  31519. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  31520. serializationObject.uvs._updatable = true;
  31521. }
  31522. }
  31523. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31524. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  31525. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  31526. serializationObject.uv2s._updatable = true;
  31527. }
  31528. }
  31529. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  31530. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  31531. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  31532. serializationObject.uv3s._updatable = true;
  31533. }
  31534. }
  31535. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  31536. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  31537. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  31538. serializationObject.uv4s._updatable = true;
  31539. }
  31540. }
  31541. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  31542. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  31543. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  31544. serializationObject.uv5s._updatable = true;
  31545. }
  31546. }
  31547. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  31548. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  31549. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  31550. serializationObject.uv6s._updatable = true;
  31551. }
  31552. }
  31553. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  31554. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  31555. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  31556. serializationObject.colors._updatable = true;
  31557. }
  31558. }
  31559. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31560. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  31561. serializationObject.matricesIndices._isExpanded = true;
  31562. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31563. serializationObject.matricesIndices._updatable = true;
  31564. }
  31565. }
  31566. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31567. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  31568. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31569. serializationObject.matricesWeights._updatable = true;
  31570. }
  31571. }
  31572. serializationObject.indices = this.toNumberArray(this.getIndices());
  31573. return serializationObject;
  31574. };
  31575. // Statics
  31576. Geometry.ExtractFromMesh = function (mesh, id) {
  31577. var geometry = mesh._geometry;
  31578. if (!geometry) {
  31579. return null;
  31580. }
  31581. return geometry.copy(id);
  31582. };
  31583. /**
  31584. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  31585. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  31586. * Be aware Math.random() could cause collisions, but:
  31587. * "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"
  31588. */
  31589. Geometry.RandomId = function () {
  31590. return BABYLON.Tools.RandomId();
  31591. };
  31592. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  31593. var scene = mesh.getScene();
  31594. // Geometry
  31595. var geometryId = parsedGeometry.geometryId;
  31596. if (geometryId) {
  31597. var geometry = scene.getGeometryByID(geometryId);
  31598. if (geometry) {
  31599. geometry.applyToMesh(mesh);
  31600. }
  31601. }
  31602. else if (parsedGeometry instanceof ArrayBuffer) {
  31603. var binaryInfo = mesh._binaryInfo;
  31604. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  31605. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  31606. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  31607. }
  31608. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  31609. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  31610. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  31611. }
  31612. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  31613. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  31614. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  31615. }
  31616. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  31617. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  31618. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  31619. }
  31620. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  31621. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  31622. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  31623. }
  31624. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  31625. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  31626. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  31627. }
  31628. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  31629. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  31630. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  31631. }
  31632. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  31633. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  31634. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  31635. }
  31636. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  31637. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  31638. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  31639. }
  31640. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  31641. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  31642. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  31643. }
  31644. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  31645. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  31646. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  31647. }
  31648. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  31649. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  31650. mesh.setIndices(indicesData, null);
  31651. }
  31652. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  31653. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  31654. mesh.subMeshes = [];
  31655. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  31656. var materialIndex = subMeshesData[(i * 5) + 0];
  31657. var verticesStart = subMeshesData[(i * 5) + 1];
  31658. var verticesCount = subMeshesData[(i * 5) + 2];
  31659. var indexStart = subMeshesData[(i * 5) + 3];
  31660. var indexCount = subMeshesData[(i * 5) + 4];
  31661. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  31662. }
  31663. }
  31664. }
  31665. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  31666. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  31667. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  31668. if (parsedGeometry.uvs) {
  31669. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  31670. }
  31671. if (parsedGeometry.uvs2) {
  31672. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  31673. }
  31674. if (parsedGeometry.uvs3) {
  31675. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  31676. }
  31677. if (parsedGeometry.uvs4) {
  31678. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  31679. }
  31680. if (parsedGeometry.uvs5) {
  31681. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  31682. }
  31683. if (parsedGeometry.uvs6) {
  31684. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  31685. }
  31686. if (parsedGeometry.colors) {
  31687. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  31688. }
  31689. if (parsedGeometry.matricesIndices) {
  31690. if (!parsedGeometry.matricesIndices._isExpanded) {
  31691. var floatIndices = [];
  31692. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  31693. var matricesIndex = parsedGeometry.matricesIndices[i];
  31694. floatIndices.push(matricesIndex & 0x000000FF);
  31695. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31696. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31697. floatIndices.push(matricesIndex >> 24);
  31698. }
  31699. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  31700. }
  31701. else {
  31702. delete parsedGeometry.matricesIndices._isExpanded;
  31703. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  31704. }
  31705. }
  31706. if (parsedGeometry.matricesIndicesExtra) {
  31707. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  31708. var floatIndices = [];
  31709. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  31710. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  31711. floatIndices.push(matricesIndex & 0x000000FF);
  31712. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31713. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31714. floatIndices.push(matricesIndex >> 24);
  31715. }
  31716. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  31717. }
  31718. else {
  31719. delete parsedGeometry.matricesIndices._isExpanded;
  31720. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  31721. }
  31722. }
  31723. if (parsedGeometry.matricesWeights) {
  31724. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  31725. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  31726. }
  31727. if (parsedGeometry.matricesWeightsExtra) {
  31728. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  31729. }
  31730. mesh.setIndices(parsedGeometry.indices, null);
  31731. }
  31732. // SubMeshes
  31733. if (parsedGeometry.subMeshes) {
  31734. mesh.subMeshes = [];
  31735. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  31736. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  31737. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  31738. }
  31739. }
  31740. // Flat shading
  31741. if (mesh._shouldGenerateFlatShading) {
  31742. mesh.convertToFlatShadedMesh();
  31743. delete mesh._shouldGenerateFlatShading;
  31744. }
  31745. // Update
  31746. mesh.computeWorldMatrix(true);
  31747. // Octree
  31748. if (scene['_selectionOctree']) {
  31749. scene['_selectionOctree'].addMesh(mesh);
  31750. }
  31751. };
  31752. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  31753. var epsilon = 1e-3;
  31754. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  31755. return;
  31756. }
  31757. var noInfluenceBoneIndex = 0.0;
  31758. if (parsedGeometry.skeletonId > -1) {
  31759. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  31760. if (!skeleton) {
  31761. return;
  31762. }
  31763. noInfluenceBoneIndex = skeleton.bones.length;
  31764. }
  31765. else {
  31766. return;
  31767. }
  31768. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31769. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  31770. var matricesWeights = parsedGeometry.matricesWeights;
  31771. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  31772. var influencers = parsedGeometry.numBoneInfluencer;
  31773. var size = matricesWeights.length;
  31774. for (var i = 0; i < size; i += 4) {
  31775. var weight = 0.0;
  31776. var firstZeroWeight = -1;
  31777. for (var j = 0; j < 4; j++) {
  31778. var w = matricesWeights[i + j];
  31779. weight += w;
  31780. if (w < epsilon && firstZeroWeight < 0) {
  31781. firstZeroWeight = j;
  31782. }
  31783. }
  31784. if (matricesWeightsExtra) {
  31785. for (var j = 0; j < 4; j++) {
  31786. var w = matricesWeightsExtra[i + j];
  31787. weight += w;
  31788. if (w < epsilon && firstZeroWeight < 0) {
  31789. firstZeroWeight = j + 4;
  31790. }
  31791. }
  31792. }
  31793. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  31794. firstZeroWeight = influencers - 1;
  31795. }
  31796. if (weight > epsilon) {
  31797. var mweight = 1.0 / weight;
  31798. for (var j = 0; j < 4; j++) {
  31799. matricesWeights[i + j] *= mweight;
  31800. }
  31801. if (matricesWeightsExtra) {
  31802. for (var j = 0; j < 4; j++) {
  31803. matricesWeightsExtra[i + j] *= mweight;
  31804. }
  31805. }
  31806. }
  31807. else {
  31808. if (firstZeroWeight >= 4) {
  31809. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  31810. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  31811. }
  31812. else {
  31813. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  31814. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  31815. }
  31816. }
  31817. }
  31818. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  31819. if (parsedGeometry.matricesWeightsExtra) {
  31820. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  31821. }
  31822. };
  31823. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  31824. if (scene.getGeometryByID(parsedVertexData.id)) {
  31825. return null; // null since geometry could be something else than a box...
  31826. }
  31827. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  31828. if (BABYLON.Tags) {
  31829. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  31830. }
  31831. if (parsedVertexData.delayLoadingFile) {
  31832. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31833. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  31834. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  31835. geometry._delayInfo = [];
  31836. if (parsedVertexData.hasUVs) {
  31837. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  31838. }
  31839. if (parsedVertexData.hasUVs2) {
  31840. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  31841. }
  31842. if (parsedVertexData.hasUVs3) {
  31843. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  31844. }
  31845. if (parsedVertexData.hasUVs4) {
  31846. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  31847. }
  31848. if (parsedVertexData.hasUVs5) {
  31849. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  31850. }
  31851. if (parsedVertexData.hasUVs6) {
  31852. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  31853. }
  31854. if (parsedVertexData.hasColors) {
  31855. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  31856. }
  31857. if (parsedVertexData.hasMatricesIndices) {
  31858. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31859. }
  31860. if (parsedVertexData.hasMatricesWeights) {
  31861. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31862. }
  31863. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  31864. }
  31865. else {
  31866. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  31867. }
  31868. scene.pushGeometry(geometry, true);
  31869. return geometry;
  31870. };
  31871. return Geometry;
  31872. }());
  31873. BABYLON.Geometry = Geometry;
  31874. /////// Primitives //////////////////////////////////////////////
  31875. (function (Geometry) {
  31876. var Primitives;
  31877. (function (Primitives) {
  31878. /// Abstract class
  31879. var _Primitive = /** @class */ (function (_super) {
  31880. __extends(_Primitive, _super);
  31881. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  31882. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  31883. if (mesh === void 0) { mesh = null; }
  31884. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  31885. _this._canBeRegenerated = _canBeRegenerated;
  31886. _this._beingRegenerated = true;
  31887. _this.regenerate();
  31888. _this._beingRegenerated = false;
  31889. return _this;
  31890. }
  31891. _Primitive.prototype.canBeRegenerated = function () {
  31892. return this._canBeRegenerated;
  31893. };
  31894. _Primitive.prototype.regenerate = function () {
  31895. if (!this._canBeRegenerated) {
  31896. return;
  31897. }
  31898. this._beingRegenerated = true;
  31899. this.setAllVerticesData(this._regenerateVertexData(), false);
  31900. this._beingRegenerated = false;
  31901. };
  31902. _Primitive.prototype.asNewGeometry = function (id) {
  31903. return _super.prototype.copy.call(this, id);
  31904. };
  31905. // overrides
  31906. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  31907. if (!this._beingRegenerated) {
  31908. return;
  31909. }
  31910. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  31911. };
  31912. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  31913. if (!this._beingRegenerated) {
  31914. return;
  31915. }
  31916. _super.prototype.setVerticesData.call(this, kind, data, false);
  31917. };
  31918. // to override
  31919. // protected
  31920. _Primitive.prototype._regenerateVertexData = function () {
  31921. throw new Error("Abstract method");
  31922. };
  31923. _Primitive.prototype.copy = function (id) {
  31924. throw new Error("Must be overriden in sub-classes.");
  31925. };
  31926. _Primitive.prototype.serialize = function () {
  31927. var serializationObject = _super.prototype.serialize.call(this);
  31928. serializationObject.canBeRegenerated = this.canBeRegenerated();
  31929. return serializationObject;
  31930. };
  31931. return _Primitive;
  31932. }(Geometry));
  31933. Primitives._Primitive = _Primitive;
  31934. var Ribbon = /** @class */ (function (_super) {
  31935. __extends(Ribbon, _super);
  31936. // Members
  31937. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  31938. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31939. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31940. _this.pathArray = pathArray;
  31941. _this.closeArray = closeArray;
  31942. _this.closePath = closePath;
  31943. _this.offset = offset;
  31944. _this.side = side;
  31945. return _this;
  31946. }
  31947. Ribbon.prototype._regenerateVertexData = function () {
  31948. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  31949. };
  31950. Ribbon.prototype.copy = function (id) {
  31951. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  31952. };
  31953. return Ribbon;
  31954. }(_Primitive));
  31955. Primitives.Ribbon = Ribbon;
  31956. var Box = /** @class */ (function (_super) {
  31957. __extends(Box, _super);
  31958. // Members
  31959. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  31960. if (mesh === void 0) { mesh = null; }
  31961. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31962. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31963. _this.size = size;
  31964. _this.side = side;
  31965. return _this;
  31966. }
  31967. Box.prototype._regenerateVertexData = function () {
  31968. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  31969. };
  31970. Box.prototype.copy = function (id) {
  31971. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  31972. };
  31973. Box.prototype.serialize = function () {
  31974. var serializationObject = _super.prototype.serialize.call(this);
  31975. serializationObject.size = this.size;
  31976. return serializationObject;
  31977. };
  31978. Box.Parse = function (parsedBox, scene) {
  31979. if (scene.getGeometryByID(parsedBox.id)) {
  31980. return null; // null since geometry could be something else than a box...
  31981. }
  31982. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  31983. if (BABYLON.Tags) {
  31984. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  31985. }
  31986. scene.pushGeometry(box, true);
  31987. return box;
  31988. };
  31989. return Box;
  31990. }(_Primitive));
  31991. Primitives.Box = Box;
  31992. var Sphere = /** @class */ (function (_super) {
  31993. __extends(Sphere, _super);
  31994. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  31995. if (mesh === void 0) { mesh = null; }
  31996. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31997. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31998. _this.segments = segments;
  31999. _this.diameter = diameter;
  32000. _this.side = side;
  32001. return _this;
  32002. }
  32003. Sphere.prototype._regenerateVertexData = function () {
  32004. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  32005. };
  32006. Sphere.prototype.copy = function (id) {
  32007. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  32008. };
  32009. Sphere.prototype.serialize = function () {
  32010. var serializationObject = _super.prototype.serialize.call(this);
  32011. serializationObject.segments = this.segments;
  32012. serializationObject.diameter = this.diameter;
  32013. return serializationObject;
  32014. };
  32015. Sphere.Parse = function (parsedSphere, scene) {
  32016. if (scene.getGeometryByID(parsedSphere.id)) {
  32017. return null; // null since geometry could be something else than a sphere...
  32018. }
  32019. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  32020. if (BABYLON.Tags) {
  32021. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  32022. }
  32023. scene.pushGeometry(sphere, true);
  32024. return sphere;
  32025. };
  32026. return Sphere;
  32027. }(_Primitive));
  32028. Primitives.Sphere = Sphere;
  32029. var Disc = /** @class */ (function (_super) {
  32030. __extends(Disc, _super);
  32031. // Members
  32032. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  32033. if (mesh === void 0) { mesh = null; }
  32034. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32035. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32036. _this.radius = radius;
  32037. _this.tessellation = tessellation;
  32038. _this.side = side;
  32039. return _this;
  32040. }
  32041. Disc.prototype._regenerateVertexData = function () {
  32042. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  32043. };
  32044. Disc.prototype.copy = function (id) {
  32045. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  32046. };
  32047. return Disc;
  32048. }(_Primitive));
  32049. Primitives.Disc = Disc;
  32050. var Cylinder = /** @class */ (function (_super) {
  32051. __extends(Cylinder, _super);
  32052. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  32053. if (subdivisions === void 0) { subdivisions = 1; }
  32054. if (mesh === void 0) { mesh = null; }
  32055. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32056. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32057. _this.height = height;
  32058. _this.diameterTop = diameterTop;
  32059. _this.diameterBottom = diameterBottom;
  32060. _this.tessellation = tessellation;
  32061. _this.subdivisions = subdivisions;
  32062. _this.side = side;
  32063. return _this;
  32064. }
  32065. Cylinder.prototype._regenerateVertexData = function () {
  32066. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  32067. };
  32068. Cylinder.prototype.copy = function (id) {
  32069. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  32070. };
  32071. Cylinder.prototype.serialize = function () {
  32072. var serializationObject = _super.prototype.serialize.call(this);
  32073. serializationObject.height = this.height;
  32074. serializationObject.diameterTop = this.diameterTop;
  32075. serializationObject.diameterBottom = this.diameterBottom;
  32076. serializationObject.tessellation = this.tessellation;
  32077. return serializationObject;
  32078. };
  32079. Cylinder.Parse = function (parsedCylinder, scene) {
  32080. if (scene.getGeometryByID(parsedCylinder.id)) {
  32081. return null; // null since geometry could be something else than a cylinder...
  32082. }
  32083. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  32084. if (BABYLON.Tags) {
  32085. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  32086. }
  32087. scene.pushGeometry(cylinder, true);
  32088. return cylinder;
  32089. };
  32090. return Cylinder;
  32091. }(_Primitive));
  32092. Primitives.Cylinder = Cylinder;
  32093. var Torus = /** @class */ (function (_super) {
  32094. __extends(Torus, _super);
  32095. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  32096. if (mesh === void 0) { mesh = null; }
  32097. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32098. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32099. _this.diameter = diameter;
  32100. _this.thickness = thickness;
  32101. _this.tessellation = tessellation;
  32102. _this.side = side;
  32103. return _this;
  32104. }
  32105. Torus.prototype._regenerateVertexData = function () {
  32106. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  32107. };
  32108. Torus.prototype.copy = function (id) {
  32109. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  32110. };
  32111. Torus.prototype.serialize = function () {
  32112. var serializationObject = _super.prototype.serialize.call(this);
  32113. serializationObject.diameter = this.diameter;
  32114. serializationObject.thickness = this.thickness;
  32115. serializationObject.tessellation = this.tessellation;
  32116. return serializationObject;
  32117. };
  32118. Torus.Parse = function (parsedTorus, scene) {
  32119. if (scene.getGeometryByID(parsedTorus.id)) {
  32120. return null; // null since geometry could be something else than a torus...
  32121. }
  32122. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  32123. if (BABYLON.Tags) {
  32124. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  32125. }
  32126. scene.pushGeometry(torus, true);
  32127. return torus;
  32128. };
  32129. return Torus;
  32130. }(_Primitive));
  32131. Primitives.Torus = Torus;
  32132. var Ground = /** @class */ (function (_super) {
  32133. __extends(Ground, _super);
  32134. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  32135. if (mesh === void 0) { mesh = null; }
  32136. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32137. _this.width = width;
  32138. _this.height = height;
  32139. _this.subdivisions = subdivisions;
  32140. return _this;
  32141. }
  32142. Ground.prototype._regenerateVertexData = function () {
  32143. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  32144. };
  32145. Ground.prototype.copy = function (id) {
  32146. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  32147. };
  32148. Ground.prototype.serialize = function () {
  32149. var serializationObject = _super.prototype.serialize.call(this);
  32150. serializationObject.width = this.width;
  32151. serializationObject.height = this.height;
  32152. serializationObject.subdivisions = this.subdivisions;
  32153. return serializationObject;
  32154. };
  32155. Ground.Parse = function (parsedGround, scene) {
  32156. if (scene.getGeometryByID(parsedGround.id)) {
  32157. return null; // null since geometry could be something else than a ground...
  32158. }
  32159. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  32160. if (BABYLON.Tags) {
  32161. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  32162. }
  32163. scene.pushGeometry(ground, true);
  32164. return ground;
  32165. };
  32166. return Ground;
  32167. }(_Primitive));
  32168. Primitives.Ground = Ground;
  32169. var TiledGround = /** @class */ (function (_super) {
  32170. __extends(TiledGround, _super);
  32171. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  32172. if (mesh === void 0) { mesh = null; }
  32173. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32174. _this.xmin = xmin;
  32175. _this.zmin = zmin;
  32176. _this.xmax = xmax;
  32177. _this.zmax = zmax;
  32178. _this.subdivisions = subdivisions;
  32179. _this.precision = precision;
  32180. return _this;
  32181. }
  32182. TiledGround.prototype._regenerateVertexData = function () {
  32183. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  32184. };
  32185. TiledGround.prototype.copy = function (id) {
  32186. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  32187. };
  32188. return TiledGround;
  32189. }(_Primitive));
  32190. Primitives.TiledGround = TiledGround;
  32191. var Plane = /** @class */ (function (_super) {
  32192. __extends(Plane, _super);
  32193. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  32194. if (mesh === void 0) { mesh = null; }
  32195. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32196. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32197. _this.size = size;
  32198. _this.side = side;
  32199. return _this;
  32200. }
  32201. Plane.prototype._regenerateVertexData = function () {
  32202. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  32203. };
  32204. Plane.prototype.copy = function (id) {
  32205. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  32206. };
  32207. Plane.prototype.serialize = function () {
  32208. var serializationObject = _super.prototype.serialize.call(this);
  32209. serializationObject.size = this.size;
  32210. return serializationObject;
  32211. };
  32212. Plane.Parse = function (parsedPlane, scene) {
  32213. if (scene.getGeometryByID(parsedPlane.id)) {
  32214. return null; // null since geometry could be something else than a ground...
  32215. }
  32216. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  32217. if (BABYLON.Tags) {
  32218. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  32219. }
  32220. scene.pushGeometry(plane, true);
  32221. return plane;
  32222. };
  32223. return Plane;
  32224. }(_Primitive));
  32225. Primitives.Plane = Plane;
  32226. var TorusKnot = /** @class */ (function (_super) {
  32227. __extends(TorusKnot, _super);
  32228. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  32229. if (mesh === void 0) { mesh = null; }
  32230. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32231. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32232. _this.radius = radius;
  32233. _this.tube = tube;
  32234. _this.radialSegments = radialSegments;
  32235. _this.tubularSegments = tubularSegments;
  32236. _this.p = p;
  32237. _this.q = q;
  32238. _this.side = side;
  32239. return _this;
  32240. }
  32241. TorusKnot.prototype._regenerateVertexData = function () {
  32242. 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 });
  32243. };
  32244. TorusKnot.prototype.copy = function (id) {
  32245. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  32246. };
  32247. TorusKnot.prototype.serialize = function () {
  32248. var serializationObject = _super.prototype.serialize.call(this);
  32249. serializationObject.radius = this.radius;
  32250. serializationObject.tube = this.tube;
  32251. serializationObject.radialSegments = this.radialSegments;
  32252. serializationObject.tubularSegments = this.tubularSegments;
  32253. serializationObject.p = this.p;
  32254. serializationObject.q = this.q;
  32255. return serializationObject;
  32256. };
  32257. ;
  32258. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  32259. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  32260. return null; // null since geometry could be something else than a ground...
  32261. }
  32262. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  32263. if (BABYLON.Tags) {
  32264. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  32265. }
  32266. scene.pushGeometry(torusKnot, true);
  32267. return torusKnot;
  32268. };
  32269. return TorusKnot;
  32270. }(_Primitive));
  32271. Primitives.TorusKnot = TorusKnot;
  32272. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  32273. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  32274. })(BABYLON || (BABYLON = {}));
  32275. //# sourceMappingURL=babylon.geometry.js.map
  32276. var BABYLON;
  32277. (function (BABYLON) {
  32278. var PostProcessManager = /** @class */ (function () {
  32279. function PostProcessManager(scene) {
  32280. this._vertexBuffers = {};
  32281. this._scene = scene;
  32282. }
  32283. PostProcessManager.prototype._prepareBuffers = function () {
  32284. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  32285. return;
  32286. }
  32287. // VBO
  32288. var vertices = [];
  32289. vertices.push(1, 1);
  32290. vertices.push(-1, 1);
  32291. vertices.push(-1, -1);
  32292. vertices.push(1, -1);
  32293. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  32294. this._buildIndexBuffer();
  32295. };
  32296. PostProcessManager.prototype._buildIndexBuffer = function () {
  32297. // Indices
  32298. var indices = [];
  32299. indices.push(0);
  32300. indices.push(1);
  32301. indices.push(2);
  32302. indices.push(0);
  32303. indices.push(2);
  32304. indices.push(3);
  32305. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  32306. };
  32307. PostProcessManager.prototype._rebuild = function () {
  32308. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32309. if (!vb) {
  32310. return;
  32311. }
  32312. vb._rebuild();
  32313. this._buildIndexBuffer();
  32314. };
  32315. // Methods
  32316. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  32317. if (sourceTexture === void 0) { sourceTexture = null; }
  32318. if (postProcesses === void 0) { postProcesses = null; }
  32319. var camera = this._scene.activeCamera;
  32320. if (!camera) {
  32321. return false;
  32322. }
  32323. var postProcesses = postProcesses || camera._postProcesses;
  32324. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32325. return false;
  32326. }
  32327. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  32328. return true;
  32329. };
  32330. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  32331. if (targetTexture === void 0) { targetTexture = null; }
  32332. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  32333. var engine = this._scene.getEngine();
  32334. for (var index = 0; index < postProcesses.length; index++) {
  32335. if (index < postProcesses.length - 1) {
  32336. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  32337. }
  32338. else {
  32339. if (targetTexture) {
  32340. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  32341. }
  32342. else {
  32343. engine.restoreDefaultFramebuffer();
  32344. }
  32345. }
  32346. var pp = postProcesses[index];
  32347. var effect = pp.apply();
  32348. if (effect) {
  32349. pp.onBeforeRenderObservable.notifyObservers(effect);
  32350. // VBOs
  32351. this._prepareBuffers();
  32352. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32353. // Draw order
  32354. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  32355. pp.onAfterRenderObservable.notifyObservers(effect);
  32356. }
  32357. }
  32358. // Restore depth buffer
  32359. engine.setDepthBuffer(true);
  32360. engine.setDepthWrite(true);
  32361. };
  32362. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  32363. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  32364. var camera = this._scene.activeCamera;
  32365. if (!camera) {
  32366. return;
  32367. }
  32368. postProcesses = postProcesses || camera._postProcesses;
  32369. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32370. return;
  32371. }
  32372. var engine = this._scene.getEngine();
  32373. for (var index = 0, len = postProcesses.length; index < len; index++) {
  32374. if (index < len - 1) {
  32375. postProcesses[index + 1].activate(camera, targetTexture);
  32376. }
  32377. else {
  32378. if (targetTexture) {
  32379. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  32380. }
  32381. else {
  32382. engine.restoreDefaultFramebuffer();
  32383. }
  32384. }
  32385. if (doNotPresent) {
  32386. break;
  32387. }
  32388. var pp = postProcesses[index];
  32389. var effect = pp.apply();
  32390. if (effect) {
  32391. pp.onBeforeRenderObservable.notifyObservers(effect);
  32392. // VBOs
  32393. this._prepareBuffers();
  32394. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32395. // Draw order
  32396. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  32397. pp.onAfterRenderObservable.notifyObservers(effect);
  32398. }
  32399. }
  32400. // Restore states
  32401. engine.setDepthBuffer(true);
  32402. engine.setDepthWrite(true);
  32403. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32404. };
  32405. PostProcessManager.prototype.dispose = function () {
  32406. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32407. if (buffer) {
  32408. buffer.dispose();
  32409. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  32410. }
  32411. if (this._indexBuffer) {
  32412. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32413. this._indexBuffer = null;
  32414. }
  32415. };
  32416. return PostProcessManager;
  32417. }());
  32418. BABYLON.PostProcessManager = PostProcessManager;
  32419. })(BABYLON || (BABYLON = {}));
  32420. //# sourceMappingURL=babylon.postProcessManager.js.map
  32421. var BABYLON;
  32422. (function (BABYLON) {
  32423. /**
  32424. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  32425. */
  32426. var PerformanceMonitor = /** @class */ (function () {
  32427. /**
  32428. * constructor
  32429. * @param frameSampleSize The number of samples required to saturate the sliding window
  32430. */
  32431. function PerformanceMonitor(frameSampleSize) {
  32432. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  32433. this._enabled = true;
  32434. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  32435. }
  32436. /**
  32437. * Samples current frame
  32438. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  32439. */
  32440. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  32441. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  32442. if (!this._enabled)
  32443. return;
  32444. if (this._lastFrameTimeMs != null) {
  32445. var dt = timeMs - this._lastFrameTimeMs;
  32446. this._rollingFrameTime.add(dt);
  32447. }
  32448. this._lastFrameTimeMs = timeMs;
  32449. };
  32450. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  32451. /**
  32452. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  32453. * @return Average frame time in milliseconds
  32454. */
  32455. get: function () {
  32456. return this._rollingFrameTime.average;
  32457. },
  32458. enumerable: true,
  32459. configurable: true
  32460. });
  32461. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  32462. /**
  32463. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  32464. * @return Frame time variance in milliseconds squared
  32465. */
  32466. get: function () {
  32467. return this._rollingFrameTime.variance;
  32468. },
  32469. enumerable: true,
  32470. configurable: true
  32471. });
  32472. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  32473. /**
  32474. * Returns the frame time of the most recent frame
  32475. * @return Frame time in milliseconds
  32476. */
  32477. get: function () {
  32478. return this._rollingFrameTime.history(0);
  32479. },
  32480. enumerable: true,
  32481. configurable: true
  32482. });
  32483. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  32484. /**
  32485. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  32486. * @return Framerate in frames per second
  32487. */
  32488. get: function () {
  32489. return 1000.0 / this._rollingFrameTime.average;
  32490. },
  32491. enumerable: true,
  32492. configurable: true
  32493. });
  32494. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  32495. /**
  32496. * Returns the average framerate in frames per second using the most recent frame time
  32497. * @return Framerate in frames per second
  32498. */
  32499. get: function () {
  32500. var history = this._rollingFrameTime.history(0);
  32501. if (history === 0) {
  32502. return 0;
  32503. }
  32504. return 1000.0 / history;
  32505. },
  32506. enumerable: true,
  32507. configurable: true
  32508. });
  32509. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  32510. /**
  32511. * Returns true if enough samples have been taken to completely fill the sliding window
  32512. * @return true if saturated
  32513. */
  32514. get: function () {
  32515. return this._rollingFrameTime.isSaturated();
  32516. },
  32517. enumerable: true,
  32518. configurable: true
  32519. });
  32520. /**
  32521. * Enables contributions to the sliding window sample set
  32522. */
  32523. PerformanceMonitor.prototype.enable = function () {
  32524. this._enabled = true;
  32525. };
  32526. /**
  32527. * Disables contributions to the sliding window sample set
  32528. * Samples will not be interpolated over the disabled period
  32529. */
  32530. PerformanceMonitor.prototype.disable = function () {
  32531. this._enabled = false;
  32532. //clear last sample to avoid interpolating over the disabled period when next enabled
  32533. this._lastFrameTimeMs = null;
  32534. };
  32535. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  32536. /**
  32537. * Returns true if sampling is enabled
  32538. * @return true if enabled
  32539. */
  32540. get: function () {
  32541. return this._enabled;
  32542. },
  32543. enumerable: true,
  32544. configurable: true
  32545. });
  32546. /**
  32547. * Resets performance monitor
  32548. */
  32549. PerformanceMonitor.prototype.reset = function () {
  32550. //clear last sample to avoid interpolating over the disabled period when next enabled
  32551. this._lastFrameTimeMs = null;
  32552. //wipe record
  32553. this._rollingFrameTime.reset();
  32554. };
  32555. return PerformanceMonitor;
  32556. }());
  32557. BABYLON.PerformanceMonitor = PerformanceMonitor;
  32558. /**
  32559. * RollingAverage
  32560. *
  32561. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  32562. */
  32563. var RollingAverage = /** @class */ (function () {
  32564. /**
  32565. * constructor
  32566. * @param length The number of samples required to saturate the sliding window
  32567. */
  32568. function RollingAverage(length) {
  32569. this._samples = new Array(length);
  32570. this.reset();
  32571. }
  32572. /**
  32573. * Adds a sample to the sample set
  32574. * @param v The sample value
  32575. */
  32576. RollingAverage.prototype.add = function (v) {
  32577. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  32578. var delta;
  32579. //we need to check if we've already wrapped round
  32580. if (this.isSaturated()) {
  32581. //remove bottom of stack from mean
  32582. var bottomValue = this._samples[this._pos];
  32583. delta = bottomValue - this.average;
  32584. this.average -= delta / (this._sampleCount - 1);
  32585. this._m2 -= delta * (bottomValue - this.average);
  32586. }
  32587. else {
  32588. this._sampleCount++;
  32589. }
  32590. //add new value to mean
  32591. delta = v - this.average;
  32592. this.average += delta / (this._sampleCount);
  32593. this._m2 += delta * (v - this.average);
  32594. //set the new variance
  32595. this.variance = this._m2 / (this._sampleCount - 1);
  32596. this._samples[this._pos] = v;
  32597. this._pos++;
  32598. this._pos %= this._samples.length; //positive wrap around
  32599. };
  32600. /**
  32601. * Returns previously added values or null if outside of history or outside the sliding window domain
  32602. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  32603. * @return Value previously recorded with add() or null if outside of range
  32604. */
  32605. RollingAverage.prototype.history = function (i) {
  32606. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  32607. return 0;
  32608. }
  32609. var i0 = this._wrapPosition(this._pos - 1.0);
  32610. return this._samples[this._wrapPosition(i0 - i)];
  32611. };
  32612. /**
  32613. * Returns true if enough samples have been taken to completely fill the sliding window
  32614. * @return true if sample-set saturated
  32615. */
  32616. RollingAverage.prototype.isSaturated = function () {
  32617. return this._sampleCount >= this._samples.length;
  32618. };
  32619. /**
  32620. * Resets the rolling average (equivalent to 0 samples taken so far)
  32621. */
  32622. RollingAverage.prototype.reset = function () {
  32623. this.average = 0;
  32624. this.variance = 0;
  32625. this._sampleCount = 0;
  32626. this._pos = 0;
  32627. this._m2 = 0;
  32628. };
  32629. /**
  32630. * Wraps a value around the sample range boundaries
  32631. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  32632. * @return Wrapped position in sample range
  32633. */
  32634. RollingAverage.prototype._wrapPosition = function (i) {
  32635. var max = this._samples.length;
  32636. return ((i % max) + max) % max;
  32637. };
  32638. return RollingAverage;
  32639. }());
  32640. BABYLON.RollingAverage = RollingAverage;
  32641. })(BABYLON || (BABYLON = {}));
  32642. //# sourceMappingURL=babylon.performanceMonitor.js.map
  32643. var BABYLON;
  32644. (function (BABYLON) {
  32645. /**
  32646. * This groups together the common properties used for image processing either in direct forward pass
  32647. * or through post processing effect depending on the use of the image processing pipeline in your scene
  32648. * or not.
  32649. */
  32650. var ImageProcessingConfiguration = /** @class */ (function () {
  32651. function ImageProcessingConfiguration() {
  32652. /**
  32653. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  32654. */
  32655. this.colorCurves = new BABYLON.ColorCurves();
  32656. this._colorCurvesEnabled = false;
  32657. this._colorGradingEnabled = false;
  32658. this._colorGradingWithGreenDepth = true;
  32659. this._colorGradingBGR = true;
  32660. this._exposure = 1.0;
  32661. this._toneMappingEnabled = false;
  32662. this._contrast = 1.0;
  32663. /**
  32664. * Vignette stretch size.
  32665. */
  32666. this.vignetteStretch = 0;
  32667. /**
  32668. * Vignette centre X Offset.
  32669. */
  32670. this.vignetteCentreX = 0;
  32671. /**
  32672. * Vignette centre Y Offset.
  32673. */
  32674. this.vignetteCentreY = 0;
  32675. /**
  32676. * Vignette weight or intensity of the vignette effect.
  32677. */
  32678. this.vignetteWeight = 1.5;
  32679. /**
  32680. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  32681. * if vignetteEnabled is set to true.
  32682. */
  32683. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  32684. /**
  32685. * Camera field of view used by the Vignette effect.
  32686. */
  32687. this.vignetteCameraFov = 0.5;
  32688. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  32689. this._vignetteEnabled = false;
  32690. this._applyByPostProcess = false;
  32691. this._isEnabled = true;
  32692. /**
  32693. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  32694. * @type {BABYLON.Observable}
  32695. */
  32696. this.onUpdateParameters = new BABYLON.Observable();
  32697. }
  32698. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  32699. /**
  32700. * Gets wether the color curves effect is enabled.
  32701. */
  32702. get: function () {
  32703. return this._colorCurvesEnabled;
  32704. },
  32705. /**
  32706. * Sets wether the color curves effect is enabled.
  32707. */
  32708. set: function (value) {
  32709. if (this._colorCurvesEnabled === value) {
  32710. return;
  32711. }
  32712. this._colorCurvesEnabled = value;
  32713. this._updateParameters();
  32714. },
  32715. enumerable: true,
  32716. configurable: true
  32717. });
  32718. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  32719. /**
  32720. * Gets wether the color grading effect is enabled.
  32721. */
  32722. get: function () {
  32723. return this._colorGradingEnabled;
  32724. },
  32725. /**
  32726. * Sets wether the color grading effect is enabled.
  32727. */
  32728. set: function (value) {
  32729. if (this._colorGradingEnabled === value) {
  32730. return;
  32731. }
  32732. this._colorGradingEnabled = value;
  32733. this._updateParameters();
  32734. },
  32735. enumerable: true,
  32736. configurable: true
  32737. });
  32738. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  32739. /**
  32740. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  32741. */
  32742. get: function () {
  32743. return this._colorGradingWithGreenDepth;
  32744. },
  32745. /**
  32746. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  32747. */
  32748. set: function (value) {
  32749. if (this._colorGradingWithGreenDepth === value) {
  32750. return;
  32751. }
  32752. this._colorGradingWithGreenDepth = value;
  32753. this._updateParameters();
  32754. },
  32755. enumerable: true,
  32756. configurable: true
  32757. });
  32758. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  32759. /**
  32760. * Gets wether the color grading texture contains BGR values.
  32761. */
  32762. get: function () {
  32763. return this._colorGradingBGR;
  32764. },
  32765. /**
  32766. * Sets wether the color grading texture contains BGR values.
  32767. */
  32768. set: function (value) {
  32769. if (this._colorGradingBGR === value) {
  32770. return;
  32771. }
  32772. this._colorGradingBGR = value;
  32773. this._updateParameters();
  32774. },
  32775. enumerable: true,
  32776. configurable: true
  32777. });
  32778. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  32779. /**
  32780. * Gets the Exposure used in the effect.
  32781. */
  32782. get: function () {
  32783. return this._exposure;
  32784. },
  32785. /**
  32786. * Sets the Exposure used in the effect.
  32787. */
  32788. set: function (value) {
  32789. if (this._exposure === value) {
  32790. return;
  32791. }
  32792. this._exposure = value;
  32793. this._updateParameters();
  32794. },
  32795. enumerable: true,
  32796. configurable: true
  32797. });
  32798. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  32799. /**
  32800. * Gets wether the tone mapping effect is enabled.
  32801. */
  32802. get: function () {
  32803. return this._toneMappingEnabled;
  32804. },
  32805. /**
  32806. * Sets wether the tone mapping effect is enabled.
  32807. */
  32808. set: function (value) {
  32809. if (this._toneMappingEnabled === value) {
  32810. return;
  32811. }
  32812. this._toneMappingEnabled = value;
  32813. this._updateParameters();
  32814. },
  32815. enumerable: true,
  32816. configurable: true
  32817. });
  32818. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  32819. /**
  32820. * Gets the contrast used in the effect.
  32821. */
  32822. get: function () {
  32823. return this._contrast;
  32824. },
  32825. /**
  32826. * Sets the contrast used in the effect.
  32827. */
  32828. set: function (value) {
  32829. if (this._contrast === value) {
  32830. return;
  32831. }
  32832. this._contrast = value;
  32833. this._updateParameters();
  32834. },
  32835. enumerable: true,
  32836. configurable: true
  32837. });
  32838. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  32839. /**
  32840. * Gets the vignette blend mode allowing different kind of effect.
  32841. */
  32842. get: function () {
  32843. return this._vignetteBlendMode;
  32844. },
  32845. /**
  32846. * Sets the vignette blend mode allowing different kind of effect.
  32847. */
  32848. set: function (value) {
  32849. if (this._vignetteBlendMode === value) {
  32850. return;
  32851. }
  32852. this._vignetteBlendMode = value;
  32853. this._updateParameters();
  32854. },
  32855. enumerable: true,
  32856. configurable: true
  32857. });
  32858. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  32859. /**
  32860. * Gets wether the vignette effect is enabled.
  32861. */
  32862. get: function () {
  32863. return this._vignetteEnabled;
  32864. },
  32865. /**
  32866. * Sets wether the vignette effect is enabled.
  32867. */
  32868. set: function (value) {
  32869. if (this._vignetteEnabled === value) {
  32870. return;
  32871. }
  32872. this._vignetteEnabled = value;
  32873. this._updateParameters();
  32874. },
  32875. enumerable: true,
  32876. configurable: true
  32877. });
  32878. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  32879. /**
  32880. * Gets wether the image processing is applied through a post process or not.
  32881. */
  32882. get: function () {
  32883. return this._applyByPostProcess;
  32884. },
  32885. /**
  32886. * Sets wether the image processing is applied through a post process or not.
  32887. */
  32888. set: function (value) {
  32889. if (this._applyByPostProcess === value) {
  32890. return;
  32891. }
  32892. this._applyByPostProcess = value;
  32893. this._updateParameters();
  32894. },
  32895. enumerable: true,
  32896. configurable: true
  32897. });
  32898. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  32899. /**
  32900. * Gets wether the image processing is enabled or not.
  32901. */
  32902. get: function () {
  32903. return this._isEnabled;
  32904. },
  32905. /**
  32906. * Sets wether the image processing is enabled or not.
  32907. */
  32908. set: function (value) {
  32909. if (this._isEnabled === value) {
  32910. return;
  32911. }
  32912. this._isEnabled = value;
  32913. this._updateParameters();
  32914. },
  32915. enumerable: true,
  32916. configurable: true
  32917. });
  32918. /**
  32919. * Method called each time the image processing information changes requires to recompile the effect.
  32920. */
  32921. ImageProcessingConfiguration.prototype._updateParameters = function () {
  32922. this.onUpdateParameters.notifyObservers(this);
  32923. };
  32924. ImageProcessingConfiguration.prototype.getClassName = function () {
  32925. return "ImageProcessingConfiguration";
  32926. };
  32927. /**
  32928. * Prepare the list of uniforms associated with the Image Processing effects.
  32929. * @param uniformsList The list of uniforms used in the effect
  32930. * @param defines the list of defines currently in use
  32931. */
  32932. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  32933. if (defines.EXPOSURE) {
  32934. uniforms.push("exposureLinear");
  32935. }
  32936. if (defines.CONTRAST) {
  32937. uniforms.push("contrast");
  32938. }
  32939. if (defines.COLORGRADING) {
  32940. uniforms.push("colorTransformSettings");
  32941. }
  32942. if (defines.VIGNETTE) {
  32943. uniforms.push("vInverseScreenSize");
  32944. uniforms.push("vignetteSettings1");
  32945. uniforms.push("vignetteSettings2");
  32946. }
  32947. if (defines.COLORCURVES) {
  32948. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  32949. }
  32950. };
  32951. /**
  32952. * Prepare the list of samplers associated with the Image Processing effects.
  32953. * @param uniformsList The list of uniforms used in the effect
  32954. * @param defines the list of defines currently in use
  32955. */
  32956. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  32957. if (defines.COLORGRADING) {
  32958. samplersList.push("txColorTransform");
  32959. }
  32960. };
  32961. /**
  32962. * Prepare the list of defines associated to the shader.
  32963. * @param defines the list of defines to complete
  32964. */
  32965. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  32966. if (forPostProcess === void 0) { forPostProcess = false; }
  32967. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  32968. defines.VIGNETTE = false;
  32969. defines.TONEMAPPING = false;
  32970. defines.CONTRAST = false;
  32971. defines.EXPOSURE = false;
  32972. defines.COLORCURVES = false;
  32973. defines.COLORGRADING = false;
  32974. defines.COLORGRADING3D = false;
  32975. defines.IMAGEPROCESSING = false;
  32976. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  32977. return;
  32978. }
  32979. defines.VIGNETTE = this.vignetteEnabled;
  32980. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  32981. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  32982. defines.TONEMAPPING = this.toneMappingEnabled;
  32983. defines.CONTRAST = (this.contrast !== 1.0);
  32984. defines.EXPOSURE = (this.exposure !== 1.0);
  32985. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  32986. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  32987. if (defines.COLORGRADING) {
  32988. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  32989. }
  32990. else {
  32991. defines.COLORGRADING3D = false;
  32992. }
  32993. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  32994. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  32995. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  32996. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  32997. };
  32998. /**
  32999. * Returns true if all the image processing information are ready.
  33000. */
  33001. ImageProcessingConfiguration.prototype.isReady = function () {
  33002. // Color Grading texure can not be none blocking.
  33003. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  33004. };
  33005. /**
  33006. * Binds the image processing to the shader.
  33007. * @param effect The effect to bind to
  33008. */
  33009. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  33010. if (aspectRatio === void 0) { aspectRatio = 1; }
  33011. // Color Curves
  33012. if (this._colorCurvesEnabled && this.colorCurves) {
  33013. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  33014. }
  33015. // Vignette
  33016. if (this._vignetteEnabled) {
  33017. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  33018. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  33019. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  33020. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  33021. var vignetteScaleX = vignetteScaleY * aspectRatio;
  33022. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  33023. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  33024. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  33025. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  33026. var vignettePower = -2.0 * this.vignetteWeight;
  33027. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  33028. }
  33029. // Exposure
  33030. effect.setFloat("exposureLinear", this.exposure);
  33031. // Contrast
  33032. effect.setFloat("contrast", this.contrast);
  33033. // Color transform settings
  33034. if (this.colorGradingTexture) {
  33035. effect.setTexture("txColorTransform", this.colorGradingTexture);
  33036. var textureSize = this.colorGradingTexture.getSize().height;
  33037. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  33038. 0.5 / textureSize, // textureOffset
  33039. textureSize, // textureSize
  33040. this.colorGradingTexture.level // weight
  33041. );
  33042. }
  33043. };
  33044. /**
  33045. * Clones the current image processing instance.
  33046. * @return The cloned image processing
  33047. */
  33048. ImageProcessingConfiguration.prototype.clone = function () {
  33049. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  33050. };
  33051. /**
  33052. * Serializes the current image processing instance to a json representation.
  33053. * @return a JSON representation
  33054. */
  33055. ImageProcessingConfiguration.prototype.serialize = function () {
  33056. return BABYLON.SerializationHelper.Serialize(this);
  33057. };
  33058. /**
  33059. * Parses the image processing from a json representation.
  33060. * @param source the JSON source to parse
  33061. * @return The parsed image processing
  33062. */
  33063. ImageProcessingConfiguration.Parse = function (source) {
  33064. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  33065. };
  33066. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  33067. /**
  33068. * Used to apply the vignette as a mix with the pixel color.
  33069. */
  33070. get: function () {
  33071. return this._VIGNETTEMODE_MULTIPLY;
  33072. },
  33073. enumerable: true,
  33074. configurable: true
  33075. });
  33076. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  33077. /**
  33078. * Used to apply the vignette as a replacement of the pixel color.
  33079. */
  33080. get: function () {
  33081. return this._VIGNETTEMODE_OPAQUE;
  33082. },
  33083. enumerable: true,
  33084. configurable: true
  33085. });
  33086. // Static constants associated to the image processing.
  33087. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  33088. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  33089. __decorate([
  33090. BABYLON.serializeAsColorCurves()
  33091. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  33092. __decorate([
  33093. BABYLON.serialize()
  33094. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  33095. __decorate([
  33096. BABYLON.serializeAsTexture()
  33097. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  33098. __decorate([
  33099. BABYLON.serialize()
  33100. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  33101. __decorate([
  33102. BABYLON.serialize()
  33103. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  33104. __decorate([
  33105. BABYLON.serialize()
  33106. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  33107. __decorate([
  33108. BABYLON.serialize()
  33109. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  33110. __decorate([
  33111. BABYLON.serialize()
  33112. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  33113. __decorate([
  33114. BABYLON.serialize()
  33115. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  33116. __decorate([
  33117. BABYLON.serialize()
  33118. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  33119. __decorate([
  33120. BABYLON.serialize()
  33121. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  33122. __decorate([
  33123. BABYLON.serialize()
  33124. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  33125. __decorate([
  33126. BABYLON.serialize()
  33127. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  33128. __decorate([
  33129. BABYLON.serializeAsColor4()
  33130. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  33131. __decorate([
  33132. BABYLON.serialize()
  33133. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  33134. __decorate([
  33135. BABYLON.serialize()
  33136. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  33137. __decorate([
  33138. BABYLON.serialize()
  33139. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  33140. __decorate([
  33141. BABYLON.serialize()
  33142. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  33143. __decorate([
  33144. BABYLON.serialize()
  33145. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  33146. return ImageProcessingConfiguration;
  33147. }());
  33148. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  33149. })(BABYLON || (BABYLON = {}));
  33150. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  33151. var BABYLON;
  33152. (function (BABYLON) {
  33153. /**
  33154. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  33155. * It can help converting any input color in a desired output one. This can then be used to create effects
  33156. * from sepia, black and white to sixties or futuristic rendering...
  33157. *
  33158. * The only supported format is currently 3dl.
  33159. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  33160. */
  33161. var ColorGradingTexture = /** @class */ (function (_super) {
  33162. __extends(ColorGradingTexture, _super);
  33163. /**
  33164. * Instantiates a ColorGradingTexture from the following parameters.
  33165. *
  33166. * @param url The location of the color gradind data (currently only supporting 3dl)
  33167. * @param scene The scene the texture will be used in
  33168. */
  33169. function ColorGradingTexture(url, scene) {
  33170. var _this = _super.call(this, scene) || this;
  33171. if (!url) {
  33172. return _this;
  33173. }
  33174. _this._engine = scene.getEngine();
  33175. _this._textureMatrix = BABYLON.Matrix.Identity();
  33176. _this.name = url;
  33177. _this.url = url;
  33178. _this.hasAlpha = false;
  33179. _this.isCube = false;
  33180. _this.is3D = _this._engine.webGLVersion > 1;
  33181. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33182. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33183. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33184. _this.anisotropicFilteringLevel = 1;
  33185. _this._texture = _this._getFromCache(url, true);
  33186. if (!_this._texture) {
  33187. if (!scene.useDelayedTextureLoading) {
  33188. _this.loadTexture();
  33189. }
  33190. else {
  33191. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33192. }
  33193. }
  33194. return _this;
  33195. }
  33196. /**
  33197. * Returns the texture matrix used in most of the material.
  33198. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  33199. */
  33200. ColorGradingTexture.prototype.getTextureMatrix = function () {
  33201. return this._textureMatrix;
  33202. };
  33203. /**
  33204. * Occurs when the file being loaded is a .3dl LUT file.
  33205. */
  33206. ColorGradingTexture.prototype.load3dlTexture = function () {
  33207. var engine = this._engine;
  33208. var texture;
  33209. if (engine.webGLVersion === 1) {
  33210. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33211. }
  33212. else {
  33213. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33214. }
  33215. this._texture = texture;
  33216. var callback = function (text) {
  33217. if (typeof text !== "string") {
  33218. return;
  33219. }
  33220. var data = null;
  33221. var tempData = null;
  33222. var line;
  33223. var lines = text.split('\n');
  33224. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  33225. var maxColor = 0;
  33226. for (var i = 0; i < lines.length; i++) {
  33227. line = lines[i];
  33228. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  33229. continue;
  33230. if (line.indexOf('#') === 0)
  33231. continue;
  33232. var words = line.split(" ");
  33233. if (size === 0) {
  33234. // Number of space + one
  33235. size = words.length;
  33236. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  33237. tempData = new Float32Array(size * size * size * 4);
  33238. continue;
  33239. }
  33240. if (size != 0) {
  33241. var r = Math.max(parseInt(words[0]), 0);
  33242. var g = Math.max(parseInt(words[1]), 0);
  33243. var b = Math.max(parseInt(words[2]), 0);
  33244. maxColor = Math.max(r, maxColor);
  33245. maxColor = Math.max(g, maxColor);
  33246. maxColor = Math.max(b, maxColor);
  33247. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  33248. if (tempData) {
  33249. tempData[pixelStorageIndex + 0] = r;
  33250. tempData[pixelStorageIndex + 1] = g;
  33251. tempData[pixelStorageIndex + 2] = b;
  33252. }
  33253. pixelIndexSlice++;
  33254. if (pixelIndexSlice % size == 0) {
  33255. pixelIndexH++;
  33256. pixelIndexSlice = 0;
  33257. if (pixelIndexH % size == 0) {
  33258. pixelIndexW++;
  33259. pixelIndexH = 0;
  33260. }
  33261. }
  33262. }
  33263. }
  33264. if (tempData && data) {
  33265. for (var i = 0; i < tempData.length; i++) {
  33266. if (i > 0 && (i + 1) % 4 === 0) {
  33267. data[i] = 255;
  33268. }
  33269. else {
  33270. var value = tempData[i];
  33271. data[i] = (value / maxColor * 255);
  33272. }
  33273. }
  33274. }
  33275. if (texture.is3D) {
  33276. texture.updateSize(size, size, size);
  33277. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33278. }
  33279. else {
  33280. texture.updateSize(size * size, size);
  33281. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33282. }
  33283. };
  33284. BABYLON.Tools.LoadFile(this.url, callback);
  33285. return this._texture;
  33286. };
  33287. /**
  33288. * Starts the loading process of the texture.
  33289. */
  33290. ColorGradingTexture.prototype.loadTexture = function () {
  33291. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  33292. this.load3dlTexture();
  33293. }
  33294. };
  33295. /**
  33296. * Clones the color gradind texture.
  33297. */
  33298. ColorGradingTexture.prototype.clone = function () {
  33299. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  33300. // Base texture
  33301. newTexture.level = this.level;
  33302. return newTexture;
  33303. };
  33304. /**
  33305. * Called during delayed load for textures.
  33306. */
  33307. ColorGradingTexture.prototype.delayLoad = function () {
  33308. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  33309. return;
  33310. }
  33311. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33312. this._texture = this._getFromCache(this.url, true);
  33313. if (!this._texture) {
  33314. this.loadTexture();
  33315. }
  33316. };
  33317. /**
  33318. * Parses a color grading texture serialized by Babylon.
  33319. * @param parsedTexture The texture information being parsedTexture
  33320. * @param scene The scene to load the texture in
  33321. * @param rootUrl The root url of the data assets to load
  33322. * @return A color gradind texture
  33323. */
  33324. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  33325. var texture = null;
  33326. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  33327. texture = new ColorGradingTexture(parsedTexture.name, scene);
  33328. texture.name = parsedTexture.name;
  33329. texture.level = parsedTexture.level;
  33330. }
  33331. return texture;
  33332. };
  33333. /**
  33334. * Serializes the LUT texture to json format.
  33335. */
  33336. ColorGradingTexture.prototype.serialize = function () {
  33337. if (!this.name) {
  33338. return null;
  33339. }
  33340. var serializationObject = {};
  33341. serializationObject.name = this.name;
  33342. serializationObject.level = this.level;
  33343. serializationObject.customType = "BABYLON.ColorGradingTexture";
  33344. return serializationObject;
  33345. };
  33346. /**
  33347. * Empty line regex stored for GC.
  33348. */
  33349. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  33350. return ColorGradingTexture;
  33351. }(BABYLON.BaseTexture));
  33352. BABYLON.ColorGradingTexture = ColorGradingTexture;
  33353. })(BABYLON || (BABYLON = {}));
  33354. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  33355. var BABYLON;
  33356. (function (BABYLON) {
  33357. /**
  33358. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33359. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33360. * 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;
  33361. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33362. */
  33363. var ColorCurves = /** @class */ (function () {
  33364. function ColorCurves() {
  33365. this._dirty = true;
  33366. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  33367. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  33368. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  33369. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  33370. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  33371. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  33372. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  33373. this._globalHue = 30;
  33374. this._globalDensity = 0;
  33375. this._globalSaturation = 0;
  33376. this._globalExposure = 0;
  33377. this._highlightsHue = 30;
  33378. this._highlightsDensity = 0;
  33379. this._highlightsSaturation = 0;
  33380. this._highlightsExposure = 0;
  33381. this._midtonesHue = 30;
  33382. this._midtonesDensity = 0;
  33383. this._midtonesSaturation = 0;
  33384. this._midtonesExposure = 0;
  33385. this._shadowsHue = 30;
  33386. this._shadowsDensity = 0;
  33387. this._shadowsSaturation = 0;
  33388. this._shadowsExposure = 0;
  33389. }
  33390. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  33391. /**
  33392. * Gets the global Hue value.
  33393. * 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).
  33394. */
  33395. get: function () {
  33396. return this._globalHue;
  33397. },
  33398. /**
  33399. * Sets the global Hue value.
  33400. * 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).
  33401. */
  33402. set: function (value) {
  33403. this._globalHue = value;
  33404. this._dirty = true;
  33405. },
  33406. enumerable: true,
  33407. configurable: true
  33408. });
  33409. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  33410. /**
  33411. * Gets the global Density value.
  33412. * 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.
  33413. * Values less than zero provide a filter of opposite hue.
  33414. */
  33415. get: function () {
  33416. return this._globalDensity;
  33417. },
  33418. /**
  33419. * Sets the global Density value.
  33420. * 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.
  33421. * Values less than zero provide a filter of opposite hue.
  33422. */
  33423. set: function (value) {
  33424. this._globalDensity = value;
  33425. this._dirty = true;
  33426. },
  33427. enumerable: true,
  33428. configurable: true
  33429. });
  33430. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  33431. /**
  33432. * Gets the global Saturation value.
  33433. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  33434. */
  33435. get: function () {
  33436. return this._globalSaturation;
  33437. },
  33438. /**
  33439. * Sets the global Saturation value.
  33440. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  33441. */
  33442. set: function (value) {
  33443. this._globalSaturation = value;
  33444. this._dirty = true;
  33445. },
  33446. enumerable: true,
  33447. configurable: true
  33448. });
  33449. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  33450. /**
  33451. * Gets the highlights Hue value.
  33452. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  33453. */
  33454. get: function () {
  33455. return this._highlightsHue;
  33456. },
  33457. /**
  33458. * Sets the highlights Hue value.
  33459. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  33460. */
  33461. set: function (value) {
  33462. this._highlightsHue = value;
  33463. this._dirty = true;
  33464. },
  33465. enumerable: true,
  33466. configurable: true
  33467. });
  33468. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  33469. /**
  33470. * Gets the highlights Density value.
  33471. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  33472. * Values less than zero provide a filter of opposite hue.
  33473. */
  33474. get: function () {
  33475. return this._highlightsDensity;
  33476. },
  33477. /**
  33478. * Sets the highlights Density value.
  33479. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  33480. * Values less than zero provide a filter of opposite hue.
  33481. */
  33482. set: function (value) {
  33483. this._highlightsDensity = value;
  33484. this._dirty = true;
  33485. },
  33486. enumerable: true,
  33487. configurable: true
  33488. });
  33489. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  33490. /**
  33491. * Gets the highlights Saturation value.
  33492. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  33493. */
  33494. get: function () {
  33495. return this._highlightsSaturation;
  33496. },
  33497. /**
  33498. * Sets the highlights Saturation value.
  33499. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  33500. */
  33501. set: function (value) {
  33502. this._highlightsSaturation = value;
  33503. this._dirty = true;
  33504. },
  33505. enumerable: true,
  33506. configurable: true
  33507. });
  33508. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  33509. /**
  33510. * Gets the highlights Exposure value.
  33511. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  33512. */
  33513. get: function () {
  33514. return this._highlightsExposure;
  33515. },
  33516. /**
  33517. * Sets the highlights Exposure value.
  33518. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  33519. */
  33520. set: function (value) {
  33521. this._highlightsExposure = value;
  33522. this._dirty = true;
  33523. },
  33524. enumerable: true,
  33525. configurable: true
  33526. });
  33527. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  33528. /**
  33529. * Gets the midtones Hue value.
  33530. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  33531. */
  33532. get: function () {
  33533. return this._midtonesHue;
  33534. },
  33535. /**
  33536. * Sets the midtones Hue value.
  33537. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  33538. */
  33539. set: function (value) {
  33540. this._midtonesHue = value;
  33541. this._dirty = true;
  33542. },
  33543. enumerable: true,
  33544. configurable: true
  33545. });
  33546. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  33547. /**
  33548. * Gets the midtones Density value.
  33549. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  33550. * Values less than zero provide a filter of opposite hue.
  33551. */
  33552. get: function () {
  33553. return this._midtonesDensity;
  33554. },
  33555. /**
  33556. * Sets the midtones Density value.
  33557. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  33558. * Values less than zero provide a filter of opposite hue.
  33559. */
  33560. set: function (value) {
  33561. this._midtonesDensity = value;
  33562. this._dirty = true;
  33563. },
  33564. enumerable: true,
  33565. configurable: true
  33566. });
  33567. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  33568. /**
  33569. * Gets the midtones Saturation value.
  33570. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  33571. */
  33572. get: function () {
  33573. return this._midtonesSaturation;
  33574. },
  33575. /**
  33576. * Sets the midtones Saturation value.
  33577. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  33578. */
  33579. set: function (value) {
  33580. this._midtonesSaturation = value;
  33581. this._dirty = true;
  33582. },
  33583. enumerable: true,
  33584. configurable: true
  33585. });
  33586. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  33587. /**
  33588. * Gets the midtones Exposure value.
  33589. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  33590. */
  33591. get: function () {
  33592. return this._midtonesExposure;
  33593. },
  33594. /**
  33595. * Sets the midtones Exposure value.
  33596. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  33597. */
  33598. set: function (value) {
  33599. this._midtonesExposure = value;
  33600. this._dirty = true;
  33601. },
  33602. enumerable: true,
  33603. configurable: true
  33604. });
  33605. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  33606. /**
  33607. * Gets the shadows Hue value.
  33608. * 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).
  33609. */
  33610. get: function () {
  33611. return this._shadowsHue;
  33612. },
  33613. /**
  33614. * Sets the shadows Hue value.
  33615. * 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).
  33616. */
  33617. set: function (value) {
  33618. this._shadowsHue = value;
  33619. this._dirty = true;
  33620. },
  33621. enumerable: true,
  33622. configurable: true
  33623. });
  33624. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  33625. /**
  33626. * Gets the shadows Density value.
  33627. * 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.
  33628. * Values less than zero provide a filter of opposite hue.
  33629. */
  33630. get: function () {
  33631. return this._shadowsDensity;
  33632. },
  33633. /**
  33634. * Sets the shadows Density value.
  33635. * 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.
  33636. * Values less than zero provide a filter of opposite hue.
  33637. */
  33638. set: function (value) {
  33639. this._shadowsDensity = value;
  33640. this._dirty = true;
  33641. },
  33642. enumerable: true,
  33643. configurable: true
  33644. });
  33645. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  33646. /**
  33647. * Gets the shadows Saturation value.
  33648. * 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.
  33649. */
  33650. get: function () {
  33651. return this._shadowsSaturation;
  33652. },
  33653. /**
  33654. * Sets the shadows Saturation value.
  33655. * 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.
  33656. */
  33657. set: function (value) {
  33658. this._shadowsSaturation = value;
  33659. this._dirty = true;
  33660. },
  33661. enumerable: true,
  33662. configurable: true
  33663. });
  33664. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  33665. /**
  33666. * Gets the shadows Exposure value.
  33667. * 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.
  33668. */
  33669. get: function () {
  33670. return this._shadowsExposure;
  33671. },
  33672. /**
  33673. * Sets the shadows Exposure value.
  33674. * 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.
  33675. */
  33676. set: function (value) {
  33677. this._shadowsExposure = value;
  33678. this._dirty = true;
  33679. },
  33680. enumerable: true,
  33681. configurable: true
  33682. });
  33683. ColorCurves.prototype.getClassName = function () {
  33684. return "ColorCurves";
  33685. };
  33686. /**
  33687. * Binds the color curves to the shader.
  33688. * @param colorCurves The color curve to bind
  33689. * @param effect The effect to bind to
  33690. */
  33691. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  33692. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  33693. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  33694. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  33695. if (colorCurves._dirty) {
  33696. colorCurves._dirty = false;
  33697. // Fill in global info.
  33698. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  33699. // Compute highlights info.
  33700. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  33701. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  33702. // Compute midtones info.
  33703. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  33704. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  33705. // Compute shadows info.
  33706. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  33707. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  33708. // Compute deltas (neutral is midtones).
  33709. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  33710. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  33711. }
  33712. if (effect) {
  33713. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  33714. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  33715. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  33716. }
  33717. };
  33718. /**
  33719. * Prepare the list of uniforms associated with the ColorCurves effects.
  33720. * @param uniformsList The list of uniforms used in the effect
  33721. */
  33722. ColorCurves.PrepareUniforms = function (uniformsList) {
  33723. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  33724. };
  33725. /**
  33726. * Returns color grading data based on a hue, density, saturation and exposure value.
  33727. * @param filterHue The hue of the color filter.
  33728. * @param filterDensity The density of the color filter.
  33729. * @param saturation The saturation.
  33730. * @param exposure The exposure.
  33731. * @param result The result data container.
  33732. */
  33733. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  33734. if (hue == null) {
  33735. return;
  33736. }
  33737. hue = ColorCurves.clamp(hue, 0, 360);
  33738. density = ColorCurves.clamp(density, -100, 100);
  33739. saturation = ColorCurves.clamp(saturation, -100, 100);
  33740. exposure = ColorCurves.clamp(exposure, -100, 100);
  33741. // Remap the slider/config filter density with non-linear mapping and also scale by half
  33742. // so that the maximum filter density is only 50% control. This provides fine control
  33743. // for small values and reasonable range.
  33744. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  33745. density *= 0.5;
  33746. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  33747. if (density < 0) {
  33748. density *= -1;
  33749. hue = (hue + 180) % 360;
  33750. }
  33751. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  33752. result.scaleToRef(2, result);
  33753. result.a = 1 + 0.01 * saturation;
  33754. };
  33755. /**
  33756. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  33757. * @param value The input slider value in range [-100,100].
  33758. * @returns Adjusted value.
  33759. */
  33760. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  33761. value /= 100;
  33762. var x = Math.abs(value);
  33763. x = Math.pow(x, 2);
  33764. if (value < 0) {
  33765. x *= -1;
  33766. }
  33767. x *= 100;
  33768. return x;
  33769. };
  33770. /**
  33771. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  33772. * @param hue The hue (H) input.
  33773. * @param saturation The saturation (S) input.
  33774. * @param brightness The brightness (B) input.
  33775. * @result An RGBA color represented as Vector4.
  33776. */
  33777. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  33778. var h = ColorCurves.clamp(hue, 0, 360);
  33779. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  33780. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  33781. if (s === 0) {
  33782. result.r = v;
  33783. result.g = v;
  33784. result.b = v;
  33785. }
  33786. else {
  33787. // sector 0 to 5
  33788. h /= 60;
  33789. var i = Math.floor(h);
  33790. // fractional part of h
  33791. var f = h - i;
  33792. var p = v * (1 - s);
  33793. var q = v * (1 - s * f);
  33794. var t = v * (1 - s * (1 - f));
  33795. switch (i) {
  33796. case 0:
  33797. result.r = v;
  33798. result.g = t;
  33799. result.b = p;
  33800. break;
  33801. case 1:
  33802. result.r = q;
  33803. result.g = v;
  33804. result.b = p;
  33805. break;
  33806. case 2:
  33807. result.r = p;
  33808. result.g = v;
  33809. result.b = t;
  33810. break;
  33811. case 3:
  33812. result.r = p;
  33813. result.g = q;
  33814. result.b = v;
  33815. break;
  33816. case 4:
  33817. result.r = t;
  33818. result.g = p;
  33819. result.b = v;
  33820. break;
  33821. default:// case 5:
  33822. result.r = v;
  33823. result.g = p;
  33824. result.b = q;
  33825. break;
  33826. }
  33827. }
  33828. result.a = 1;
  33829. };
  33830. /**
  33831. * Returns a value clamped between min and max
  33832. * @param value The value to clamp
  33833. * @param min The minimum of value
  33834. * @param max The maximum of value
  33835. * @returns The clamped value.
  33836. */
  33837. ColorCurves.clamp = function (value, min, max) {
  33838. return Math.min(Math.max(value, min), max);
  33839. };
  33840. /**
  33841. * Clones the current color curve instance.
  33842. * @return The cloned curves
  33843. */
  33844. ColorCurves.prototype.clone = function () {
  33845. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  33846. };
  33847. /**
  33848. * Serializes the current color curve instance to a json representation.
  33849. * @return a JSON representation
  33850. */
  33851. ColorCurves.prototype.serialize = function () {
  33852. return BABYLON.SerializationHelper.Serialize(this);
  33853. };
  33854. /**
  33855. * Parses the color curve from a json representation.
  33856. * @param source the JSON source to parse
  33857. * @return The parsed curves
  33858. */
  33859. ColorCurves.Parse = function (source) {
  33860. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  33861. };
  33862. __decorate([
  33863. BABYLON.serialize()
  33864. ], ColorCurves.prototype, "_globalHue", void 0);
  33865. __decorate([
  33866. BABYLON.serialize()
  33867. ], ColorCurves.prototype, "_globalDensity", void 0);
  33868. __decorate([
  33869. BABYLON.serialize()
  33870. ], ColorCurves.prototype, "_globalSaturation", void 0);
  33871. __decorate([
  33872. BABYLON.serialize()
  33873. ], ColorCurves.prototype, "_globalExposure", void 0);
  33874. __decorate([
  33875. BABYLON.serialize()
  33876. ], ColorCurves.prototype, "_highlightsHue", void 0);
  33877. __decorate([
  33878. BABYLON.serialize()
  33879. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  33880. __decorate([
  33881. BABYLON.serialize()
  33882. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  33883. __decorate([
  33884. BABYLON.serialize()
  33885. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  33886. __decorate([
  33887. BABYLON.serialize()
  33888. ], ColorCurves.prototype, "_midtonesHue", void 0);
  33889. __decorate([
  33890. BABYLON.serialize()
  33891. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  33892. __decorate([
  33893. BABYLON.serialize()
  33894. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  33895. __decorate([
  33896. BABYLON.serialize()
  33897. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  33898. return ColorCurves;
  33899. }());
  33900. BABYLON.ColorCurves = ColorCurves;
  33901. })(BABYLON || (BABYLON = {}));
  33902. //# sourceMappingURL=babylon.colorCurves.js.map
  33903. var BABYLON;
  33904. (function (BABYLON) {
  33905. var MaterialHelper = /** @class */ (function () {
  33906. function MaterialHelper() {
  33907. }
  33908. MaterialHelper.BindEyePosition = function (effect, scene) {
  33909. if (scene._forcedViewPosition) {
  33910. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  33911. return;
  33912. }
  33913. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  33914. };
  33915. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  33916. defines._needUVs = true;
  33917. defines[key] = true;
  33918. if (texture.getTextureMatrix().isIdentity(true)) {
  33919. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  33920. if (texture.coordinatesIndex === 0) {
  33921. defines["MAINUV1"] = true;
  33922. }
  33923. else {
  33924. defines["MAINUV2"] = true;
  33925. }
  33926. }
  33927. else {
  33928. defines[key + "DIRECTUV"] = 0;
  33929. }
  33930. };
  33931. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  33932. var matrix = texture.getTextureMatrix();
  33933. if (!matrix.isIdentity(true)) {
  33934. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  33935. }
  33936. };
  33937. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  33938. if (defines._areMiscDirty) {
  33939. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  33940. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  33941. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  33942. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  33943. }
  33944. };
  33945. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  33946. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  33947. var changed = false;
  33948. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  33949. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  33950. changed = true;
  33951. }
  33952. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  33953. defines["ALPHATEST"] = !defines["ALPHATEST"];
  33954. changed = true;
  33955. }
  33956. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  33957. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  33958. changed = true;
  33959. }
  33960. if (defines["INSTANCES"] !== useInstances) {
  33961. defines["INSTANCES"] = useInstances;
  33962. changed = true;
  33963. }
  33964. if (changed) {
  33965. defines.markAsUnprocessed();
  33966. }
  33967. };
  33968. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  33969. if (useMorphTargets === void 0) { useMorphTargets = false; }
  33970. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  33971. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  33972. return false;
  33973. }
  33974. defines._normals = defines._needNormals;
  33975. defines._uvs = defines._needUVs;
  33976. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  33977. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  33978. defines["TANGENT"] = true;
  33979. }
  33980. if (defines._needUVs) {
  33981. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  33982. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  33983. }
  33984. else {
  33985. defines["UV1"] = false;
  33986. defines["UV2"] = false;
  33987. }
  33988. if (useVertexColor) {
  33989. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  33990. defines["VERTEXCOLOR"] = hasVertexColors;
  33991. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  33992. }
  33993. if (useBones) {
  33994. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  33995. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  33996. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  33997. }
  33998. else {
  33999. defines["NUM_BONE_INFLUENCERS"] = 0;
  34000. defines["BonesPerMesh"] = 0;
  34001. }
  34002. }
  34003. if (useMorphTargets) {
  34004. var manager = mesh.morphTargetManager;
  34005. if (manager) {
  34006. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  34007. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  34008. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  34009. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  34010. }
  34011. else {
  34012. defines["MORPHTARGETS_TANGENT"] = false;
  34013. defines["MORPHTARGETS_NORMAL"] = false;
  34014. defines["MORPHTARGETS"] = false;
  34015. defines["NUM_MORPH_INFLUENCERS"] = 0;
  34016. }
  34017. }
  34018. return true;
  34019. };
  34020. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  34021. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34022. if (disableLighting === void 0) { disableLighting = false; }
  34023. if (!defines._areLightsDirty) {
  34024. return defines._needNormals;
  34025. }
  34026. var lightIndex = 0;
  34027. var needNormals = false;
  34028. var needRebuild = false;
  34029. var lightmapMode = false;
  34030. var shadowEnabled = false;
  34031. var specularEnabled = false;
  34032. if (scene.lightsEnabled && !disableLighting) {
  34033. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  34034. var light = _a[_i];
  34035. needNormals = true;
  34036. if (defines["LIGHT" + lightIndex] === undefined) {
  34037. needRebuild = true;
  34038. }
  34039. defines["LIGHT" + lightIndex] = true;
  34040. defines["SPOTLIGHT" + lightIndex] = false;
  34041. defines["HEMILIGHT" + lightIndex] = false;
  34042. defines["POINTLIGHT" + lightIndex] = false;
  34043. defines["DIRLIGHT" + lightIndex] = false;
  34044. var type;
  34045. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  34046. type = "SPOTLIGHT" + lightIndex;
  34047. }
  34048. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  34049. type = "HEMILIGHT" + lightIndex;
  34050. }
  34051. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  34052. type = "POINTLIGHT" + lightIndex;
  34053. }
  34054. else {
  34055. type = "DIRLIGHT" + lightIndex;
  34056. }
  34057. defines[type] = true;
  34058. // Specular
  34059. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  34060. specularEnabled = true;
  34061. }
  34062. // Shadows
  34063. defines["SHADOW" + lightIndex] = false;
  34064. defines["SHADOWPCF" + lightIndex] = false;
  34065. defines["SHADOWESM" + lightIndex] = false;
  34066. defines["SHADOWCUBE" + lightIndex] = false;
  34067. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  34068. var shadowGenerator = light.getShadowGenerator();
  34069. if (shadowGenerator) {
  34070. shadowEnabled = true;
  34071. shadowGenerator.prepareDefines(defines, lightIndex);
  34072. }
  34073. }
  34074. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  34075. lightmapMode = true;
  34076. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  34077. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  34078. }
  34079. else {
  34080. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  34081. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  34082. }
  34083. lightIndex++;
  34084. if (lightIndex === maxSimultaneousLights)
  34085. break;
  34086. }
  34087. }
  34088. defines["SPECULARTERM"] = specularEnabled;
  34089. defines["SHADOWS"] = shadowEnabled;
  34090. // Resetting all other lights if any
  34091. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  34092. if (defines["LIGHT" + index] !== undefined) {
  34093. defines["LIGHT" + index] = false;
  34094. defines["HEMILIGHT" + lightIndex] = false;
  34095. defines["POINTLIGHT" + lightIndex] = false;
  34096. defines["DIRLIGHT" + lightIndex] = false;
  34097. defines["SPOTLIGHT" + lightIndex] = false;
  34098. defines["SHADOW" + lightIndex] = false;
  34099. }
  34100. }
  34101. var caps = scene.getEngine().getCaps();
  34102. if (defines["SHADOWFLOAT"] === undefined) {
  34103. needRebuild = true;
  34104. }
  34105. defines["SHADOWFLOAT"] = shadowEnabled &&
  34106. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  34107. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  34108. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  34109. if (needRebuild) {
  34110. defines.rebuild();
  34111. }
  34112. return needNormals;
  34113. };
  34114. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  34115. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34116. var uniformsList;
  34117. var uniformBuffersList = null;
  34118. if (uniformsListOrOptions.uniformsNames) {
  34119. var options = uniformsListOrOptions;
  34120. uniformsList = options.uniformsNames;
  34121. uniformBuffersList = options.uniformBuffersNames;
  34122. samplersList = options.samplers;
  34123. defines = options.defines;
  34124. maxSimultaneousLights = options.maxSimultaneousLights;
  34125. }
  34126. else {
  34127. uniformsList = uniformsListOrOptions;
  34128. if (!samplersList) {
  34129. samplersList = [];
  34130. }
  34131. }
  34132. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  34133. if (!defines["LIGHT" + lightIndex]) {
  34134. break;
  34135. }
  34136. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  34137. if (uniformBuffersList) {
  34138. uniformBuffersList.push("Light" + lightIndex);
  34139. }
  34140. samplersList.push("shadowSampler" + lightIndex);
  34141. }
  34142. if (defines["NUM_MORPH_INFLUENCERS"]) {
  34143. uniformsList.push("morphTargetInfluences");
  34144. }
  34145. };
  34146. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  34147. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34148. if (rank === void 0) { rank = 0; }
  34149. var lightFallbackRank = 0;
  34150. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  34151. if (!defines["LIGHT" + lightIndex]) {
  34152. break;
  34153. }
  34154. if (lightIndex > 0) {
  34155. lightFallbackRank = rank + lightIndex;
  34156. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  34157. }
  34158. if (!defines["SHADOWS"]) {
  34159. if (defines["SHADOW" + lightIndex]) {
  34160. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  34161. }
  34162. if (defines["SHADOWPCF" + lightIndex]) {
  34163. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  34164. }
  34165. if (defines["SHADOWESM" + lightIndex]) {
  34166. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  34167. }
  34168. }
  34169. }
  34170. return lightFallbackRank++;
  34171. };
  34172. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  34173. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  34174. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  34175. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  34176. var manager = mesh.morphTargetManager;
  34177. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  34178. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  34179. for (var index = 0; index < influencers; index++) {
  34180. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  34181. if (normal) {
  34182. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  34183. }
  34184. if (tangent) {
  34185. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  34186. }
  34187. if (attribs.length > maxAttributesCount) {
  34188. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  34189. }
  34190. }
  34191. }
  34192. };
  34193. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  34194. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  34195. fallbacks.addCPUSkinningFallback(0, mesh);
  34196. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34197. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34198. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  34199. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  34200. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  34201. }
  34202. }
  34203. };
  34204. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  34205. if (defines["INSTANCES"]) {
  34206. attribs.push("world0");
  34207. attribs.push("world1");
  34208. attribs.push("world2");
  34209. attribs.push("world3");
  34210. }
  34211. };
  34212. // Bindings
  34213. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  34214. if (light.shadowEnabled && mesh.receiveShadows) {
  34215. var shadowGenerator = light.getShadowGenerator();
  34216. if (shadowGenerator) {
  34217. shadowGenerator.bindShadowLight(lightIndex, effect);
  34218. }
  34219. }
  34220. };
  34221. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  34222. light.transferToEffect(effect, lightIndex + "");
  34223. };
  34224. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  34225. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34226. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  34227. var lightIndex = 0;
  34228. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  34229. var light = _a[_i];
  34230. var scaledIntensity = light.getScaledIntensity();
  34231. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  34232. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  34233. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  34234. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  34235. if (defines["SPECULARTERM"]) {
  34236. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  34237. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  34238. }
  34239. // Shadows
  34240. if (scene.shadowsEnabled) {
  34241. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  34242. }
  34243. light._uniformBuffer.update();
  34244. lightIndex++;
  34245. if (lightIndex === maxSimultaneousLights)
  34246. break;
  34247. }
  34248. };
  34249. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  34250. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  34251. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  34252. effect.setColor3("vFogColor", scene.fogColor);
  34253. }
  34254. };
  34255. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  34256. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  34257. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  34258. if (matrices && effect) {
  34259. effect.setMatrices("mBones", matrices);
  34260. }
  34261. }
  34262. };
  34263. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  34264. var manager = abstractMesh.morphTargetManager;
  34265. if (!abstractMesh || !manager) {
  34266. return;
  34267. }
  34268. effect.setFloatArray("morphTargetInfluences", manager.influences);
  34269. };
  34270. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  34271. if (defines["LOGARITHMICDEPTH"]) {
  34272. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  34273. }
  34274. };
  34275. MaterialHelper.BindClipPlane = function (effect, scene) {
  34276. if (scene.clipPlane) {
  34277. var clipPlane = scene.clipPlane;
  34278. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  34279. }
  34280. };
  34281. return MaterialHelper;
  34282. }());
  34283. BABYLON.MaterialHelper = MaterialHelper;
  34284. })(BABYLON || (BABYLON = {}));
  34285. //# sourceMappingURL=babylon.materialHelper.js.map
  34286. var BABYLON;
  34287. (function (BABYLON) {
  34288. var PushMaterial = /** @class */ (function (_super) {
  34289. __extends(PushMaterial, _super);
  34290. function PushMaterial(name, scene) {
  34291. var _this = _super.call(this, name, scene) || this;
  34292. _this.storeEffectOnSubMeshes = true;
  34293. return _this;
  34294. }
  34295. PushMaterial.prototype.getEffect = function () {
  34296. return this._activeEffect;
  34297. };
  34298. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  34299. if (!mesh) {
  34300. return false;
  34301. }
  34302. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  34303. return true;
  34304. }
  34305. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  34306. };
  34307. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  34308. this._activeEffect.setMatrix("world", world);
  34309. };
  34310. PushMaterial.prototype.bind = function (world, mesh) {
  34311. if (!mesh) {
  34312. return;
  34313. }
  34314. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  34315. };
  34316. PushMaterial.prototype._afterBind = function (mesh, effect) {
  34317. if (effect === void 0) { effect = null; }
  34318. _super.prototype._afterBind.call(this, mesh);
  34319. this.getScene()._cachedEffect = effect;
  34320. };
  34321. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  34322. if (visibility === void 0) { visibility = 1; }
  34323. return scene.isCachedMaterialInvalid(this, effect, visibility);
  34324. };
  34325. return PushMaterial;
  34326. }(BABYLON.Material));
  34327. BABYLON.PushMaterial = PushMaterial;
  34328. })(BABYLON || (BABYLON = {}));
  34329. //# sourceMappingURL=babylon.pushMaterial.js.map
  34330. var BABYLON;
  34331. (function (BABYLON) {
  34332. var StandardMaterialDefines = /** @class */ (function (_super) {
  34333. __extends(StandardMaterialDefines, _super);
  34334. function StandardMaterialDefines() {
  34335. var _this = _super.call(this) || this;
  34336. _this.MAINUV1 = false;
  34337. _this.MAINUV2 = false;
  34338. _this.DIFFUSE = false;
  34339. _this.DIFFUSEDIRECTUV = 0;
  34340. _this.AMBIENT = false;
  34341. _this.AMBIENTDIRECTUV = 0;
  34342. _this.OPACITY = false;
  34343. _this.OPACITYDIRECTUV = 0;
  34344. _this.OPACITYRGB = false;
  34345. _this.REFLECTION = false;
  34346. _this.EMISSIVE = false;
  34347. _this.EMISSIVEDIRECTUV = 0;
  34348. _this.SPECULAR = false;
  34349. _this.SPECULARDIRECTUV = 0;
  34350. _this.BUMP = false;
  34351. _this.BUMPDIRECTUV = 0;
  34352. _this.PARALLAX = false;
  34353. _this.PARALLAXOCCLUSION = false;
  34354. _this.SPECULAROVERALPHA = false;
  34355. _this.CLIPPLANE = false;
  34356. _this.ALPHATEST = false;
  34357. _this.DEPTHPREPASS = false;
  34358. _this.ALPHAFROMDIFFUSE = false;
  34359. _this.POINTSIZE = false;
  34360. _this.FOG = false;
  34361. _this.SPECULARTERM = false;
  34362. _this.DIFFUSEFRESNEL = false;
  34363. _this.OPACITYFRESNEL = false;
  34364. _this.REFLECTIONFRESNEL = false;
  34365. _this.REFRACTIONFRESNEL = false;
  34366. _this.EMISSIVEFRESNEL = false;
  34367. _this.FRESNEL = false;
  34368. _this.NORMAL = false;
  34369. _this.UV1 = false;
  34370. _this.UV2 = false;
  34371. _this.VERTEXCOLOR = false;
  34372. _this.VERTEXALPHA = false;
  34373. _this.NUM_BONE_INFLUENCERS = 0;
  34374. _this.BonesPerMesh = 0;
  34375. _this.INSTANCES = false;
  34376. _this.GLOSSINESS = false;
  34377. _this.ROUGHNESS = false;
  34378. _this.EMISSIVEASILLUMINATION = false;
  34379. _this.LINKEMISSIVEWITHDIFFUSE = false;
  34380. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  34381. _this.LIGHTMAP = false;
  34382. _this.LIGHTMAPDIRECTUV = 0;
  34383. _this.USELIGHTMAPASSHADOWMAP = false;
  34384. _this.REFLECTIONMAP_3D = false;
  34385. _this.REFLECTIONMAP_SPHERICAL = false;
  34386. _this.REFLECTIONMAP_PLANAR = false;
  34387. _this.REFLECTIONMAP_CUBIC = false;
  34388. _this.REFLECTIONMAP_PROJECTION = false;
  34389. _this.REFLECTIONMAP_SKYBOX = false;
  34390. _this.REFLECTIONMAP_EXPLICIT = false;
  34391. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  34392. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  34393. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  34394. _this.INVERTCUBICMAP = false;
  34395. _this.LOGARITHMICDEPTH = false;
  34396. _this.REFRACTION = false;
  34397. _this.REFRACTIONMAP_3D = false;
  34398. _this.REFLECTIONOVERALPHA = false;
  34399. _this.TWOSIDEDLIGHTING = false;
  34400. _this.SHADOWFLOAT = false;
  34401. _this.MORPHTARGETS = false;
  34402. _this.MORPHTARGETS_NORMAL = false;
  34403. _this.MORPHTARGETS_TANGENT = false;
  34404. _this.NUM_MORPH_INFLUENCERS = 0;
  34405. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  34406. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  34407. _this.IMAGEPROCESSING = false;
  34408. _this.VIGNETTE = false;
  34409. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  34410. _this.VIGNETTEBLENDMODEOPAQUE = false;
  34411. _this.TONEMAPPING = false;
  34412. _this.CONTRAST = false;
  34413. _this.COLORCURVES = false;
  34414. _this.COLORGRADING = false;
  34415. _this.COLORGRADING3D = false;
  34416. _this.SAMPLER3DGREENDEPTH = false;
  34417. _this.SAMPLER3DBGRMAP = false;
  34418. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  34419. _this.EXPOSURE = false;
  34420. _this.rebuild();
  34421. return _this;
  34422. }
  34423. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  34424. var modes = [
  34425. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  34426. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  34427. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  34428. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  34429. ];
  34430. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  34431. var mode = modes_1[_i];
  34432. this[mode] = (mode === modeToEnable);
  34433. }
  34434. };
  34435. return StandardMaterialDefines;
  34436. }(BABYLON.MaterialDefines));
  34437. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  34438. var StandardMaterial = /** @class */ (function (_super) {
  34439. __extends(StandardMaterial, _super);
  34440. function StandardMaterial(name, scene) {
  34441. var _this = _super.call(this, name, scene) || this;
  34442. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  34443. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  34444. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  34445. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  34446. _this.specularPower = 64;
  34447. _this._useAlphaFromDiffuseTexture = false;
  34448. _this._useEmissiveAsIllumination = false;
  34449. _this._linkEmissiveWithDiffuse = false;
  34450. _this._useSpecularOverAlpha = false;
  34451. _this._useReflectionOverAlpha = false;
  34452. _this._disableLighting = false;
  34453. _this._useParallax = false;
  34454. _this._useParallaxOcclusion = false;
  34455. _this.parallaxScaleBias = 0.05;
  34456. _this._roughness = 0;
  34457. _this.indexOfRefraction = 0.98;
  34458. _this.invertRefractionY = true;
  34459. _this._useLightmapAsShadowmap = false;
  34460. _this._useReflectionFresnelFromSpecular = false;
  34461. _this._useGlossinessFromSpecularMapAlpha = false;
  34462. _this._maxSimultaneousLights = 4;
  34463. /**
  34464. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  34465. */
  34466. _this._invertNormalMapX = false;
  34467. /**
  34468. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  34469. */
  34470. _this._invertNormalMapY = false;
  34471. /**
  34472. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  34473. */
  34474. _this._twoSidedLighting = false;
  34475. _this._renderTargets = new BABYLON.SmartArray(16);
  34476. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  34477. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  34478. // Setup the default processing configuration to the scene.
  34479. _this._attachImageProcessingConfiguration(null);
  34480. _this.getRenderTargetTextures = function () {
  34481. _this._renderTargets.reset();
  34482. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  34483. _this._renderTargets.push(_this._reflectionTexture);
  34484. }
  34485. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  34486. _this._renderTargets.push(_this._refractionTexture);
  34487. }
  34488. return _this._renderTargets;
  34489. };
  34490. return _this;
  34491. }
  34492. ;
  34493. ;
  34494. ;
  34495. ;
  34496. ;
  34497. ;
  34498. ;
  34499. ;
  34500. ;
  34501. ;
  34502. ;
  34503. ;
  34504. ;
  34505. ;
  34506. ;
  34507. ;
  34508. ;
  34509. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  34510. /**
  34511. * Gets the image processing configuration used either in this material.
  34512. */
  34513. get: function () {
  34514. return this._imageProcessingConfiguration;
  34515. },
  34516. /**
  34517. * Sets the Default image processing configuration used either in the this material.
  34518. *
  34519. * If sets to null, the scene one is in use.
  34520. */
  34521. set: function (value) {
  34522. this._attachImageProcessingConfiguration(value);
  34523. // Ensure the effect will be rebuilt.
  34524. this._markAllSubMeshesAsTexturesDirty();
  34525. },
  34526. enumerable: true,
  34527. configurable: true
  34528. });
  34529. /**
  34530. * Attaches a new image processing configuration to the Standard Material.
  34531. * @param configuration
  34532. */
  34533. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  34534. var _this = this;
  34535. if (configuration === this._imageProcessingConfiguration) {
  34536. return;
  34537. }
  34538. // Detaches observer.
  34539. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  34540. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  34541. }
  34542. // Pick the scene configuration if needed.
  34543. if (!configuration) {
  34544. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  34545. }
  34546. else {
  34547. this._imageProcessingConfiguration = configuration;
  34548. }
  34549. // Attaches observer.
  34550. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  34551. _this._markAllSubMeshesAsImageProcessingDirty();
  34552. });
  34553. };
  34554. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  34555. /**
  34556. * Gets wether the color curves effect is enabled.
  34557. */
  34558. get: function () {
  34559. return this.imageProcessingConfiguration.colorCurvesEnabled;
  34560. },
  34561. /**
  34562. * Sets wether the color curves effect is enabled.
  34563. */
  34564. set: function (value) {
  34565. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  34566. },
  34567. enumerable: true,
  34568. configurable: true
  34569. });
  34570. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  34571. /**
  34572. * Gets wether the color grading effect is enabled.
  34573. */
  34574. get: function () {
  34575. return this.imageProcessingConfiguration.colorGradingEnabled;
  34576. },
  34577. /**
  34578. * Gets wether the color grading effect is enabled.
  34579. */
  34580. set: function (value) {
  34581. this.imageProcessingConfiguration.colorGradingEnabled = value;
  34582. },
  34583. enumerable: true,
  34584. configurable: true
  34585. });
  34586. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  34587. /**
  34588. * Gets wether tonemapping is enabled or not.
  34589. */
  34590. get: function () {
  34591. return this._imageProcessingConfiguration.toneMappingEnabled;
  34592. },
  34593. /**
  34594. * Sets wether tonemapping is enabled or not
  34595. */
  34596. set: function (value) {
  34597. this._imageProcessingConfiguration.toneMappingEnabled = value;
  34598. },
  34599. enumerable: true,
  34600. configurable: true
  34601. });
  34602. ;
  34603. ;
  34604. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  34605. /**
  34606. * The camera exposure used on this material.
  34607. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  34608. * This corresponds to a photographic exposure.
  34609. */
  34610. get: function () {
  34611. return this._imageProcessingConfiguration.exposure;
  34612. },
  34613. /**
  34614. * The camera exposure used on this material.
  34615. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  34616. * This corresponds to a photographic exposure.
  34617. */
  34618. set: function (value) {
  34619. this._imageProcessingConfiguration.exposure = value;
  34620. },
  34621. enumerable: true,
  34622. configurable: true
  34623. });
  34624. ;
  34625. ;
  34626. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  34627. /**
  34628. * Gets The camera contrast used on this material.
  34629. */
  34630. get: function () {
  34631. return this._imageProcessingConfiguration.contrast;
  34632. },
  34633. /**
  34634. * Sets The camera contrast used on this material.
  34635. */
  34636. set: function (value) {
  34637. this._imageProcessingConfiguration.contrast = value;
  34638. },
  34639. enumerable: true,
  34640. configurable: true
  34641. });
  34642. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  34643. /**
  34644. * Gets the Color Grading 2D Lookup Texture.
  34645. */
  34646. get: function () {
  34647. return this._imageProcessingConfiguration.colorGradingTexture;
  34648. },
  34649. /**
  34650. * Sets the Color Grading 2D Lookup Texture.
  34651. */
  34652. set: function (value) {
  34653. this._imageProcessingConfiguration.colorGradingTexture = value;
  34654. },
  34655. enumerable: true,
  34656. configurable: true
  34657. });
  34658. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  34659. /**
  34660. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  34661. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  34662. * 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;
  34663. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  34664. */
  34665. get: function () {
  34666. return this._imageProcessingConfiguration.colorCurves;
  34667. },
  34668. /**
  34669. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  34670. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  34671. * 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;
  34672. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  34673. */
  34674. set: function (value) {
  34675. this._imageProcessingConfiguration.colorCurves = value;
  34676. },
  34677. enumerable: true,
  34678. configurable: true
  34679. });
  34680. StandardMaterial.prototype.getClassName = function () {
  34681. return "StandardMaterial";
  34682. };
  34683. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  34684. get: function () {
  34685. return this._useLogarithmicDepth;
  34686. },
  34687. set: function (value) {
  34688. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  34689. this._markAllSubMeshesAsMiscDirty();
  34690. },
  34691. enumerable: true,
  34692. configurable: true
  34693. });
  34694. StandardMaterial.prototype.needAlphaBlending = function () {
  34695. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  34696. };
  34697. StandardMaterial.prototype.needAlphaTesting = function () {
  34698. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  34699. };
  34700. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  34701. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  34702. };
  34703. StandardMaterial.prototype.getAlphaTestTexture = function () {
  34704. return this._diffuseTexture;
  34705. };
  34706. /**
  34707. * Child classes can use it to update shaders
  34708. */
  34709. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34710. if (useInstances === void 0) { useInstances = false; }
  34711. if (subMesh.effect && this.isFrozen) {
  34712. if (this._wasPreviouslyReady && subMesh.effect) {
  34713. return true;
  34714. }
  34715. }
  34716. if (!subMesh._materialDefines) {
  34717. subMesh._materialDefines = new StandardMaterialDefines();
  34718. }
  34719. var scene = this.getScene();
  34720. var defines = subMesh._materialDefines;
  34721. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  34722. if (defines._renderId === scene.getRenderId()) {
  34723. return true;
  34724. }
  34725. }
  34726. var engine = scene.getEngine();
  34727. // Lights
  34728. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  34729. // Textures
  34730. if (defines._areTexturesDirty) {
  34731. defines._needUVs = false;
  34732. defines.MAINUV1 = false;
  34733. defines.MAINUV2 = false;
  34734. if (scene.texturesEnabled) {
  34735. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  34736. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  34737. return false;
  34738. }
  34739. else {
  34740. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  34741. }
  34742. }
  34743. else {
  34744. defines.DIFFUSE = false;
  34745. }
  34746. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  34747. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  34748. return false;
  34749. }
  34750. else {
  34751. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  34752. }
  34753. }
  34754. else {
  34755. defines.AMBIENT = false;
  34756. }
  34757. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  34758. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  34759. return false;
  34760. }
  34761. else {
  34762. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  34763. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  34764. }
  34765. }
  34766. else {
  34767. defines.OPACITY = false;
  34768. }
  34769. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  34770. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  34771. return false;
  34772. }
  34773. else {
  34774. defines._needNormals = true;
  34775. defines.REFLECTION = true;
  34776. defines.ROUGHNESS = (this._roughness > 0);
  34777. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  34778. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  34779. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  34780. switch (this._reflectionTexture.coordinatesMode) {
  34781. case BABYLON.Texture.CUBIC_MODE:
  34782. case BABYLON.Texture.INVCUBIC_MODE:
  34783. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  34784. break;
  34785. case BABYLON.Texture.EXPLICIT_MODE:
  34786. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  34787. break;
  34788. case BABYLON.Texture.PLANAR_MODE:
  34789. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  34790. break;
  34791. case BABYLON.Texture.PROJECTION_MODE:
  34792. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  34793. break;
  34794. case BABYLON.Texture.SKYBOX_MODE:
  34795. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  34796. break;
  34797. case BABYLON.Texture.SPHERICAL_MODE:
  34798. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  34799. break;
  34800. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  34801. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  34802. break;
  34803. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  34804. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  34805. break;
  34806. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  34807. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  34808. break;
  34809. }
  34810. }
  34811. }
  34812. else {
  34813. defines.REFLECTION = false;
  34814. }
  34815. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  34816. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  34817. return false;
  34818. }
  34819. else {
  34820. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  34821. }
  34822. }
  34823. else {
  34824. defines.EMISSIVE = false;
  34825. }
  34826. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  34827. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  34828. return false;
  34829. }
  34830. else {
  34831. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  34832. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  34833. }
  34834. }
  34835. else {
  34836. defines.LIGHTMAP = false;
  34837. }
  34838. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  34839. if (!this._specularTexture.isReadyOrNotBlocking()) {
  34840. return false;
  34841. }
  34842. else {
  34843. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  34844. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  34845. }
  34846. }
  34847. else {
  34848. defines.SPECULAR = false;
  34849. }
  34850. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  34851. // Bump texure can not be not blocking.
  34852. if (!this._bumpTexture.isReady()) {
  34853. return false;
  34854. }
  34855. else {
  34856. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  34857. defines.PARALLAX = this._useParallax;
  34858. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  34859. }
  34860. }
  34861. else {
  34862. defines.BUMP = false;
  34863. }
  34864. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  34865. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  34866. return false;
  34867. }
  34868. else {
  34869. defines._needUVs = true;
  34870. defines.REFRACTION = true;
  34871. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  34872. }
  34873. }
  34874. else {
  34875. defines.REFRACTION = false;
  34876. }
  34877. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  34878. }
  34879. else {
  34880. defines.DIFFUSE = false;
  34881. defines.AMBIENT = false;
  34882. defines.OPACITY = false;
  34883. defines.REFLECTION = false;
  34884. defines.EMISSIVE = false;
  34885. defines.LIGHTMAP = false;
  34886. defines.BUMP = false;
  34887. defines.REFRACTION = false;
  34888. }
  34889. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  34890. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  34891. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  34892. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  34893. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  34894. }
  34895. if (defines._areImageProcessingDirty) {
  34896. if (!this._imageProcessingConfiguration.isReady()) {
  34897. return false;
  34898. }
  34899. this._imageProcessingConfiguration.prepareDefines(defines);
  34900. }
  34901. if (defines._areFresnelDirty) {
  34902. if (StandardMaterial.FresnelEnabled) {
  34903. // Fresnel
  34904. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  34905. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  34906. this._reflectionFresnelParameters) {
  34907. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  34908. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  34909. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  34910. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  34911. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  34912. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  34913. defines._needNormals = true;
  34914. defines.FRESNEL = true;
  34915. }
  34916. }
  34917. else {
  34918. defines.FRESNEL = false;
  34919. }
  34920. }
  34921. // Misc.
  34922. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  34923. // Attribs
  34924. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  34925. // Values that need to be evaluated on every frame
  34926. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  34927. // Get correct effect
  34928. if (defines.isDirty) {
  34929. defines.markAsProcessed();
  34930. scene.resetCachedMaterial();
  34931. // Fallbacks
  34932. var fallbacks = new BABYLON.EffectFallbacks();
  34933. if (defines.REFLECTION) {
  34934. fallbacks.addFallback(0, "REFLECTION");
  34935. }
  34936. if (defines.SPECULAR) {
  34937. fallbacks.addFallback(0, "SPECULAR");
  34938. }
  34939. if (defines.BUMP) {
  34940. fallbacks.addFallback(0, "BUMP");
  34941. }
  34942. if (defines.PARALLAX) {
  34943. fallbacks.addFallback(1, "PARALLAX");
  34944. }
  34945. if (defines.PARALLAXOCCLUSION) {
  34946. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  34947. }
  34948. if (defines.SPECULAROVERALPHA) {
  34949. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  34950. }
  34951. if (defines.FOG) {
  34952. fallbacks.addFallback(1, "FOG");
  34953. }
  34954. if (defines.POINTSIZE) {
  34955. fallbacks.addFallback(0, "POINTSIZE");
  34956. }
  34957. if (defines.LOGARITHMICDEPTH) {
  34958. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  34959. }
  34960. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  34961. if (defines.SPECULARTERM) {
  34962. fallbacks.addFallback(0, "SPECULARTERM");
  34963. }
  34964. if (defines.DIFFUSEFRESNEL) {
  34965. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  34966. }
  34967. if (defines.OPACITYFRESNEL) {
  34968. fallbacks.addFallback(2, "OPACITYFRESNEL");
  34969. }
  34970. if (defines.REFLECTIONFRESNEL) {
  34971. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  34972. }
  34973. if (defines.EMISSIVEFRESNEL) {
  34974. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  34975. }
  34976. if (defines.FRESNEL) {
  34977. fallbacks.addFallback(4, "FRESNEL");
  34978. }
  34979. //Attributes
  34980. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34981. if (defines.NORMAL) {
  34982. attribs.push(BABYLON.VertexBuffer.NormalKind);
  34983. }
  34984. if (defines.UV1) {
  34985. attribs.push(BABYLON.VertexBuffer.UVKind);
  34986. }
  34987. if (defines.UV2) {
  34988. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34989. }
  34990. if (defines.VERTEXCOLOR) {
  34991. attribs.push(BABYLON.VertexBuffer.ColorKind);
  34992. }
  34993. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  34994. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  34995. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  34996. var shaderName = "default";
  34997. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  34998. "vFogInfos", "vFogColor", "pointSize",
  34999. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  35000. "mBones",
  35001. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  35002. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  35003. "logarithmicDepthConstant", "vTangentSpaceParams"
  35004. ];
  35005. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  35006. var uniformBuffers = ["Material", "Scene"];
  35007. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  35008. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  35009. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  35010. uniformsNames: uniforms,
  35011. uniformBuffersNames: uniformBuffers,
  35012. samplers: samplers,
  35013. defines: defines,
  35014. maxSimultaneousLights: this._maxSimultaneousLights
  35015. });
  35016. if (this.customShaderNameResolve) {
  35017. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  35018. }
  35019. var join = defines.toString();
  35020. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  35021. attributes: attribs,
  35022. uniformsNames: uniforms,
  35023. uniformBuffersNames: uniformBuffers,
  35024. samplers: samplers,
  35025. defines: join,
  35026. fallbacks: fallbacks,
  35027. onCompiled: this.onCompiled,
  35028. onError: this.onError,
  35029. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  35030. }, engine), defines);
  35031. this.buildUniformLayout();
  35032. }
  35033. if (!subMesh.effect || !subMesh.effect.isReady()) {
  35034. return false;
  35035. }
  35036. defines._renderId = scene.getRenderId();
  35037. this._wasPreviouslyReady = true;
  35038. return true;
  35039. };
  35040. StandardMaterial.prototype.buildUniformLayout = function () {
  35041. // Order is important !
  35042. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  35043. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  35044. this._uniformBuffer.addUniform("opacityParts", 4);
  35045. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  35046. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  35047. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  35048. this._uniformBuffer.addUniform("refractionRightColor", 4);
  35049. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  35050. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  35051. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  35052. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  35053. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  35054. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  35055. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  35056. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  35057. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  35058. this._uniformBuffer.addUniform("vBumpInfos", 3);
  35059. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  35060. this._uniformBuffer.addUniform("ambientMatrix", 16);
  35061. this._uniformBuffer.addUniform("opacityMatrix", 16);
  35062. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  35063. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  35064. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  35065. this._uniformBuffer.addUniform("specularMatrix", 16);
  35066. this._uniformBuffer.addUniform("bumpMatrix", 16);
  35067. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  35068. this._uniformBuffer.addUniform("refractionMatrix", 16);
  35069. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  35070. this._uniformBuffer.addUniform("vSpecularColor", 4);
  35071. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  35072. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  35073. this._uniformBuffer.addUniform("pointSize", 1);
  35074. this._uniformBuffer.create();
  35075. };
  35076. StandardMaterial.prototype.unbind = function () {
  35077. if (this._activeEffect) {
  35078. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  35079. this._activeEffect.setTexture("reflection2DSampler", null);
  35080. }
  35081. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  35082. this._activeEffect.setTexture("refraction2DSampler", null);
  35083. }
  35084. }
  35085. _super.prototype.unbind.call(this);
  35086. };
  35087. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35088. var scene = this.getScene();
  35089. var defines = subMesh._materialDefines;
  35090. if (!defines) {
  35091. return;
  35092. }
  35093. var effect = subMesh.effect;
  35094. if (!effect) {
  35095. return;
  35096. }
  35097. this._activeEffect = effect;
  35098. // Matrices
  35099. this.bindOnlyWorldMatrix(world);
  35100. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  35101. // Bones
  35102. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  35103. if (mustRebind) {
  35104. this._uniformBuffer.bindToEffect(effect, "Material");
  35105. this.bindViewProjection(effect);
  35106. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  35107. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  35108. // Fresnel
  35109. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  35110. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  35111. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  35112. }
  35113. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  35114. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  35115. }
  35116. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  35117. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  35118. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  35119. }
  35120. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  35121. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  35122. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  35123. }
  35124. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  35125. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  35126. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  35127. }
  35128. }
  35129. // Textures
  35130. if (scene.texturesEnabled) {
  35131. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35132. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  35133. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  35134. }
  35135. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35136. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  35137. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  35138. }
  35139. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35140. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  35141. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  35142. }
  35143. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35144. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  35145. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  35146. }
  35147. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35148. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  35149. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  35150. }
  35151. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35152. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  35153. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  35154. }
  35155. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35156. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  35157. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  35158. }
  35159. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35160. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  35161. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  35162. if (scene._mirroredCameraPosition) {
  35163. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  35164. }
  35165. else {
  35166. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  35167. }
  35168. }
  35169. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35170. var depth = 1.0;
  35171. if (!this._refractionTexture.isCube) {
  35172. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  35173. if (this._refractionTexture.depth) {
  35174. depth = this._refractionTexture.depth;
  35175. }
  35176. }
  35177. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  35178. }
  35179. }
  35180. // Point size
  35181. if (this.pointsCloud) {
  35182. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  35183. }
  35184. if (defines.SPECULARTERM) {
  35185. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  35186. }
  35187. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  35188. // Diffuse
  35189. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  35190. }
  35191. // Textures
  35192. if (scene.texturesEnabled) {
  35193. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35194. effect.setTexture("diffuseSampler", this._diffuseTexture);
  35195. }
  35196. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35197. effect.setTexture("ambientSampler", this._ambientTexture);
  35198. }
  35199. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35200. effect.setTexture("opacitySampler", this._opacityTexture);
  35201. }
  35202. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35203. if (this._reflectionTexture.isCube) {
  35204. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  35205. }
  35206. else {
  35207. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  35208. }
  35209. }
  35210. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35211. effect.setTexture("emissiveSampler", this._emissiveTexture);
  35212. }
  35213. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35214. effect.setTexture("lightmapSampler", this._lightmapTexture);
  35215. }
  35216. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35217. effect.setTexture("specularSampler", this._specularTexture);
  35218. }
  35219. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35220. effect.setTexture("bumpSampler", this._bumpTexture);
  35221. }
  35222. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35223. var depth = 1.0;
  35224. if (this._refractionTexture.isCube) {
  35225. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  35226. }
  35227. else {
  35228. effect.setTexture("refraction2DSampler", this._refractionTexture);
  35229. }
  35230. }
  35231. }
  35232. // Clip plane
  35233. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  35234. // Colors
  35235. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  35236. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  35237. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  35238. }
  35239. if (mustRebind || !this.isFrozen) {
  35240. // Lights
  35241. if (scene.lightsEnabled && !this._disableLighting) {
  35242. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  35243. }
  35244. // View
  35245. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  35246. this.bindView(effect);
  35247. }
  35248. // Fog
  35249. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  35250. // Morph targets
  35251. if (defines.NUM_MORPH_INFLUENCERS) {
  35252. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  35253. }
  35254. // Log. depth
  35255. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  35256. // image processing
  35257. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  35258. this._imageProcessingConfiguration.bind(this._activeEffect);
  35259. }
  35260. }
  35261. this._uniformBuffer.update();
  35262. this._afterBind(mesh, this._activeEffect);
  35263. };
  35264. StandardMaterial.prototype.getAnimatables = function () {
  35265. var results = [];
  35266. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  35267. results.push(this._diffuseTexture);
  35268. }
  35269. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  35270. results.push(this._ambientTexture);
  35271. }
  35272. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  35273. results.push(this._opacityTexture);
  35274. }
  35275. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  35276. results.push(this._reflectionTexture);
  35277. }
  35278. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  35279. results.push(this._emissiveTexture);
  35280. }
  35281. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  35282. results.push(this._specularTexture);
  35283. }
  35284. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  35285. results.push(this._bumpTexture);
  35286. }
  35287. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  35288. results.push(this._lightmapTexture);
  35289. }
  35290. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  35291. results.push(this._refractionTexture);
  35292. }
  35293. return results;
  35294. };
  35295. StandardMaterial.prototype.getActiveTextures = function () {
  35296. var activeTextures = _super.prototype.getActiveTextures.call(this);
  35297. if (this._diffuseTexture) {
  35298. activeTextures.push(this._diffuseTexture);
  35299. }
  35300. if (this._ambientTexture) {
  35301. activeTextures.push(this._ambientTexture);
  35302. }
  35303. if (this._opacityTexture) {
  35304. activeTextures.push(this._opacityTexture);
  35305. }
  35306. if (this._reflectionTexture) {
  35307. activeTextures.push(this._reflectionTexture);
  35308. }
  35309. if (this._emissiveTexture) {
  35310. activeTextures.push(this._emissiveTexture);
  35311. }
  35312. if (this._specularTexture) {
  35313. activeTextures.push(this._specularTexture);
  35314. }
  35315. if (this._bumpTexture) {
  35316. activeTextures.push(this._bumpTexture);
  35317. }
  35318. if (this._lightmapTexture) {
  35319. activeTextures.push(this._lightmapTexture);
  35320. }
  35321. if (this._refractionTexture) {
  35322. activeTextures.push(this._refractionTexture);
  35323. }
  35324. return activeTextures;
  35325. };
  35326. StandardMaterial.prototype.hasTexture = function (texture) {
  35327. if (_super.prototype.hasTexture.call(this, texture)) {
  35328. return true;
  35329. }
  35330. if (this._diffuseTexture === texture) {
  35331. return true;
  35332. }
  35333. if (this._ambientTexture === texture) {
  35334. return true;
  35335. }
  35336. if (this._opacityTexture === texture) {
  35337. return true;
  35338. }
  35339. if (this._reflectionTexture === texture) {
  35340. return true;
  35341. }
  35342. if (this._emissiveTexture === texture) {
  35343. return true;
  35344. }
  35345. if (this._specularTexture === texture) {
  35346. return true;
  35347. }
  35348. if (this._bumpTexture === texture) {
  35349. return true;
  35350. }
  35351. if (this._lightmapTexture === texture) {
  35352. return true;
  35353. }
  35354. if (this._refractionTexture === texture) {
  35355. return true;
  35356. }
  35357. return false;
  35358. };
  35359. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35360. if (forceDisposeTextures) {
  35361. if (this._diffuseTexture) {
  35362. this._diffuseTexture.dispose();
  35363. }
  35364. if (this._ambientTexture) {
  35365. this._ambientTexture.dispose();
  35366. }
  35367. if (this._opacityTexture) {
  35368. this._opacityTexture.dispose();
  35369. }
  35370. if (this._reflectionTexture) {
  35371. this._reflectionTexture.dispose();
  35372. }
  35373. if (this._emissiveTexture) {
  35374. this._emissiveTexture.dispose();
  35375. }
  35376. if (this._specularTexture) {
  35377. this._specularTexture.dispose();
  35378. }
  35379. if (this._bumpTexture) {
  35380. this._bumpTexture.dispose();
  35381. }
  35382. if (this._lightmapTexture) {
  35383. this._lightmapTexture.dispose();
  35384. }
  35385. if (this._refractionTexture) {
  35386. this._refractionTexture.dispose();
  35387. }
  35388. }
  35389. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35390. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35391. }
  35392. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  35393. };
  35394. StandardMaterial.prototype.clone = function (name) {
  35395. var _this = this;
  35396. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  35397. result.name = name;
  35398. result.id = name;
  35399. return result;
  35400. };
  35401. StandardMaterial.prototype.serialize = function () {
  35402. return BABYLON.SerializationHelper.Serialize(this);
  35403. };
  35404. // Statics
  35405. StandardMaterial.Parse = function (source, scene, rootUrl) {
  35406. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  35407. };
  35408. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  35409. get: function () {
  35410. return StandardMaterial._DiffuseTextureEnabled;
  35411. },
  35412. set: function (value) {
  35413. if (StandardMaterial._DiffuseTextureEnabled === value) {
  35414. return;
  35415. }
  35416. StandardMaterial._DiffuseTextureEnabled = value;
  35417. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35418. },
  35419. enumerable: true,
  35420. configurable: true
  35421. });
  35422. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  35423. get: function () {
  35424. return StandardMaterial._AmbientTextureEnabled;
  35425. },
  35426. set: function (value) {
  35427. if (StandardMaterial._AmbientTextureEnabled === value) {
  35428. return;
  35429. }
  35430. StandardMaterial._AmbientTextureEnabled = value;
  35431. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35432. },
  35433. enumerable: true,
  35434. configurable: true
  35435. });
  35436. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  35437. get: function () {
  35438. return StandardMaterial._OpacityTextureEnabled;
  35439. },
  35440. set: function (value) {
  35441. if (StandardMaterial._OpacityTextureEnabled === value) {
  35442. return;
  35443. }
  35444. StandardMaterial._OpacityTextureEnabled = value;
  35445. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35446. },
  35447. enumerable: true,
  35448. configurable: true
  35449. });
  35450. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  35451. get: function () {
  35452. return StandardMaterial._ReflectionTextureEnabled;
  35453. },
  35454. set: function (value) {
  35455. if (StandardMaterial._ReflectionTextureEnabled === value) {
  35456. return;
  35457. }
  35458. StandardMaterial._ReflectionTextureEnabled = value;
  35459. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35460. },
  35461. enumerable: true,
  35462. configurable: true
  35463. });
  35464. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  35465. get: function () {
  35466. return StandardMaterial._EmissiveTextureEnabled;
  35467. },
  35468. set: function (value) {
  35469. if (StandardMaterial._EmissiveTextureEnabled === value) {
  35470. return;
  35471. }
  35472. StandardMaterial._EmissiveTextureEnabled = value;
  35473. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35474. },
  35475. enumerable: true,
  35476. configurable: true
  35477. });
  35478. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  35479. get: function () {
  35480. return StandardMaterial._SpecularTextureEnabled;
  35481. },
  35482. set: function (value) {
  35483. if (StandardMaterial._SpecularTextureEnabled === value) {
  35484. return;
  35485. }
  35486. StandardMaterial._SpecularTextureEnabled = value;
  35487. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35488. },
  35489. enumerable: true,
  35490. configurable: true
  35491. });
  35492. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  35493. get: function () {
  35494. return StandardMaterial._BumpTextureEnabled;
  35495. },
  35496. set: function (value) {
  35497. if (StandardMaterial._BumpTextureEnabled === value) {
  35498. return;
  35499. }
  35500. StandardMaterial._BumpTextureEnabled = value;
  35501. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35502. },
  35503. enumerable: true,
  35504. configurable: true
  35505. });
  35506. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  35507. get: function () {
  35508. return StandardMaterial._LightmapTextureEnabled;
  35509. },
  35510. set: function (value) {
  35511. if (StandardMaterial._LightmapTextureEnabled === value) {
  35512. return;
  35513. }
  35514. StandardMaterial._LightmapTextureEnabled = value;
  35515. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35516. },
  35517. enumerable: true,
  35518. configurable: true
  35519. });
  35520. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  35521. get: function () {
  35522. return StandardMaterial._RefractionTextureEnabled;
  35523. },
  35524. set: function (value) {
  35525. if (StandardMaterial._RefractionTextureEnabled === value) {
  35526. return;
  35527. }
  35528. StandardMaterial._RefractionTextureEnabled = value;
  35529. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35530. },
  35531. enumerable: true,
  35532. configurable: true
  35533. });
  35534. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  35535. get: function () {
  35536. return StandardMaterial._ColorGradingTextureEnabled;
  35537. },
  35538. set: function (value) {
  35539. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  35540. return;
  35541. }
  35542. StandardMaterial._ColorGradingTextureEnabled = value;
  35543. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35544. },
  35545. enumerable: true,
  35546. configurable: true
  35547. });
  35548. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  35549. get: function () {
  35550. return StandardMaterial._FresnelEnabled;
  35551. },
  35552. set: function (value) {
  35553. if (StandardMaterial._FresnelEnabled === value) {
  35554. return;
  35555. }
  35556. StandardMaterial._FresnelEnabled = value;
  35557. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  35558. },
  35559. enumerable: true,
  35560. configurable: true
  35561. });
  35562. // Flags used to enable or disable a type of texture for all Standard Materials
  35563. StandardMaterial._DiffuseTextureEnabled = true;
  35564. StandardMaterial._AmbientTextureEnabled = true;
  35565. StandardMaterial._OpacityTextureEnabled = true;
  35566. StandardMaterial._ReflectionTextureEnabled = true;
  35567. StandardMaterial._EmissiveTextureEnabled = true;
  35568. StandardMaterial._SpecularTextureEnabled = true;
  35569. StandardMaterial._BumpTextureEnabled = true;
  35570. StandardMaterial._LightmapTextureEnabled = true;
  35571. StandardMaterial._RefractionTextureEnabled = true;
  35572. StandardMaterial._ColorGradingTextureEnabled = true;
  35573. StandardMaterial._FresnelEnabled = true;
  35574. __decorate([
  35575. BABYLON.serializeAsTexture("diffuseTexture")
  35576. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  35577. __decorate([
  35578. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35579. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  35580. __decorate([
  35581. BABYLON.serializeAsTexture("ambientTexture")
  35582. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  35583. __decorate([
  35584. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35585. ], StandardMaterial.prototype, "ambientTexture", void 0);
  35586. __decorate([
  35587. BABYLON.serializeAsTexture("opacityTexture")
  35588. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  35589. __decorate([
  35590. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35591. ], StandardMaterial.prototype, "opacityTexture", void 0);
  35592. __decorate([
  35593. BABYLON.serializeAsTexture("reflectionTexture")
  35594. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  35595. __decorate([
  35596. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35597. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  35598. __decorate([
  35599. BABYLON.serializeAsTexture("emissiveTexture")
  35600. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  35601. __decorate([
  35602. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35603. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  35604. __decorate([
  35605. BABYLON.serializeAsTexture("specularTexture")
  35606. ], StandardMaterial.prototype, "_specularTexture", void 0);
  35607. __decorate([
  35608. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35609. ], StandardMaterial.prototype, "specularTexture", void 0);
  35610. __decorate([
  35611. BABYLON.serializeAsTexture("bumpTexture")
  35612. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  35613. __decorate([
  35614. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35615. ], StandardMaterial.prototype, "bumpTexture", void 0);
  35616. __decorate([
  35617. BABYLON.serializeAsTexture("lightmapTexture")
  35618. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  35619. __decorate([
  35620. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35621. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  35622. __decorate([
  35623. BABYLON.serializeAsTexture("refractionTexture")
  35624. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  35625. __decorate([
  35626. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35627. ], StandardMaterial.prototype, "refractionTexture", void 0);
  35628. __decorate([
  35629. BABYLON.serializeAsColor3("ambient")
  35630. ], StandardMaterial.prototype, "ambientColor", void 0);
  35631. __decorate([
  35632. BABYLON.serializeAsColor3("diffuse")
  35633. ], StandardMaterial.prototype, "diffuseColor", void 0);
  35634. __decorate([
  35635. BABYLON.serializeAsColor3("specular")
  35636. ], StandardMaterial.prototype, "specularColor", void 0);
  35637. __decorate([
  35638. BABYLON.serializeAsColor3("emissive")
  35639. ], StandardMaterial.prototype, "emissiveColor", void 0);
  35640. __decorate([
  35641. BABYLON.serialize()
  35642. ], StandardMaterial.prototype, "specularPower", void 0);
  35643. __decorate([
  35644. BABYLON.serialize("useAlphaFromDiffuseTexture")
  35645. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  35646. __decorate([
  35647. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35648. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  35649. __decorate([
  35650. BABYLON.serialize("useEmissiveAsIllumination")
  35651. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  35652. __decorate([
  35653. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35654. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  35655. __decorate([
  35656. BABYLON.serialize("linkEmissiveWithDiffuse")
  35657. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  35658. __decorate([
  35659. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35660. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  35661. __decorate([
  35662. BABYLON.serialize("useSpecularOverAlpha")
  35663. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  35664. __decorate([
  35665. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35666. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  35667. __decorate([
  35668. BABYLON.serialize("useReflectionOverAlpha")
  35669. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  35670. __decorate([
  35671. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35672. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  35673. __decorate([
  35674. BABYLON.serialize("disableLighting")
  35675. ], StandardMaterial.prototype, "_disableLighting", void 0);
  35676. __decorate([
  35677. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35678. ], StandardMaterial.prototype, "disableLighting", void 0);
  35679. __decorate([
  35680. BABYLON.serialize("useParallax")
  35681. ], StandardMaterial.prototype, "_useParallax", void 0);
  35682. __decorate([
  35683. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35684. ], StandardMaterial.prototype, "useParallax", void 0);
  35685. __decorate([
  35686. BABYLON.serialize("useParallaxOcclusion")
  35687. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  35688. __decorate([
  35689. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35690. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  35691. __decorate([
  35692. BABYLON.serialize()
  35693. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  35694. __decorate([
  35695. BABYLON.serialize("roughness")
  35696. ], StandardMaterial.prototype, "_roughness", void 0);
  35697. __decorate([
  35698. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35699. ], StandardMaterial.prototype, "roughness", void 0);
  35700. __decorate([
  35701. BABYLON.serialize()
  35702. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  35703. __decorate([
  35704. BABYLON.serialize()
  35705. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  35706. __decorate([
  35707. BABYLON.serialize("useLightmapAsShadowmap")
  35708. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  35709. __decorate([
  35710. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35711. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  35712. __decorate([
  35713. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  35714. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  35715. __decorate([
  35716. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35717. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  35718. __decorate([
  35719. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  35720. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  35721. __decorate([
  35722. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35723. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  35724. __decorate([
  35725. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  35726. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  35727. __decorate([
  35728. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35729. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  35730. __decorate([
  35731. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  35732. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  35733. __decorate([
  35734. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35735. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  35736. __decorate([
  35737. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  35738. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  35739. __decorate([
  35740. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35741. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  35742. __decorate([
  35743. BABYLON.serialize("useReflectionFresnelFromSpecular")
  35744. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  35745. __decorate([
  35746. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35747. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  35748. __decorate([
  35749. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  35750. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  35751. __decorate([
  35752. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35753. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  35754. __decorate([
  35755. BABYLON.serialize("maxSimultaneousLights")
  35756. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  35757. __decorate([
  35758. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35759. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  35760. __decorate([
  35761. BABYLON.serialize("invertNormalMapX")
  35762. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  35763. __decorate([
  35764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35765. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  35766. __decorate([
  35767. BABYLON.serialize("invertNormalMapY")
  35768. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  35769. __decorate([
  35770. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35771. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  35772. __decorate([
  35773. BABYLON.serialize("twoSidedLighting")
  35774. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  35775. __decorate([
  35776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35777. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  35778. __decorate([
  35779. BABYLON.serialize()
  35780. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  35781. return StandardMaterial;
  35782. }(BABYLON.PushMaterial));
  35783. BABYLON.StandardMaterial = StandardMaterial;
  35784. })(BABYLON || (BABYLON = {}));
  35785. //# sourceMappingURL=babylon.standardMaterial.js.map
  35786. var BABYLON;
  35787. (function (BABYLON) {
  35788. var PBRMaterialDefines = /** @class */ (function (_super) {
  35789. __extends(PBRMaterialDefines, _super);
  35790. function PBRMaterialDefines() {
  35791. var _this = _super.call(this) || this;
  35792. _this.PBR = true;
  35793. _this.MAINUV1 = false;
  35794. _this.MAINUV2 = false;
  35795. _this.UV1 = false;
  35796. _this.UV2 = false;
  35797. _this.ALBEDO = false;
  35798. _this.ALBEDODIRECTUV = 0;
  35799. _this.VERTEXCOLOR = false;
  35800. _this.AMBIENT = false;
  35801. _this.AMBIENTDIRECTUV = 0;
  35802. _this.AMBIENTINGRAYSCALE = false;
  35803. _this.OPACITY = false;
  35804. _this.VERTEXALPHA = false;
  35805. _this.OPACITYDIRECTUV = 0;
  35806. _this.OPACITYRGB = false;
  35807. _this.ALPHATEST = false;
  35808. _this.DEPTHPREPASS = false;
  35809. _this.ALPHABLEND = false;
  35810. _this.ALPHAFROMALBEDO = false;
  35811. _this.ALPHATESTVALUE = 0.5;
  35812. _this.SPECULAROVERALPHA = false;
  35813. _this.RADIANCEOVERALPHA = false;
  35814. _this.ALPHAFRESNEL = false;
  35815. _this.LINEARALPHAFRESNEL = false;
  35816. _this.PREMULTIPLYALPHA = false;
  35817. _this.EMISSIVE = false;
  35818. _this.EMISSIVEDIRECTUV = 0;
  35819. _this.REFLECTIVITY = false;
  35820. _this.REFLECTIVITYDIRECTUV = 0;
  35821. _this.SPECULARTERM = false;
  35822. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  35823. _this.MICROSURFACEAUTOMATIC = false;
  35824. _this.LODBASEDMICROSFURACE = false;
  35825. _this.MICROSURFACEMAP = false;
  35826. _this.MICROSURFACEMAPDIRECTUV = 0;
  35827. _this.METALLICWORKFLOW = false;
  35828. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  35829. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  35830. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  35831. _this.AOSTOREINMETALMAPRED = false;
  35832. _this.ENVIRONMENTBRDF = false;
  35833. _this.NORMAL = false;
  35834. _this.TANGENT = false;
  35835. _this.BUMP = false;
  35836. _this.BUMPDIRECTUV = 0;
  35837. _this.PARALLAX = false;
  35838. _this.PARALLAXOCCLUSION = false;
  35839. _this.NORMALXYSCALE = true;
  35840. _this.LIGHTMAP = false;
  35841. _this.LIGHTMAPDIRECTUV = 0;
  35842. _this.USELIGHTMAPASSHADOWMAP = false;
  35843. _this.REFLECTION = false;
  35844. _this.REFLECTIONMAP_3D = false;
  35845. _this.REFLECTIONMAP_SPHERICAL = false;
  35846. _this.REFLECTIONMAP_PLANAR = false;
  35847. _this.REFLECTIONMAP_CUBIC = false;
  35848. _this.REFLECTIONMAP_PROJECTION = false;
  35849. _this.REFLECTIONMAP_SKYBOX = false;
  35850. _this.REFLECTIONMAP_EXPLICIT = false;
  35851. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  35852. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  35853. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  35854. _this.INVERTCUBICMAP = false;
  35855. _this.USESPHERICALFROMREFLECTIONMAP = false;
  35856. _this.USESPHERICALINVERTEX = false;
  35857. _this.REFLECTIONMAP_OPPOSITEZ = false;
  35858. _this.LODINREFLECTIONALPHA = false;
  35859. _this.GAMMAREFLECTION = false;
  35860. _this.RADIANCEOCCLUSION = false;
  35861. _this.HORIZONOCCLUSION = false;
  35862. _this.REFRACTION = false;
  35863. _this.REFRACTIONMAP_3D = false;
  35864. _this.REFRACTIONMAP_OPPOSITEZ = false;
  35865. _this.LODINREFRACTIONALPHA = false;
  35866. _this.GAMMAREFRACTION = false;
  35867. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  35868. _this.INSTANCES = false;
  35869. _this.NUM_BONE_INFLUENCERS = 0;
  35870. _this.BonesPerMesh = 0;
  35871. _this.NONUNIFORMSCALING = false;
  35872. _this.MORPHTARGETS = false;
  35873. _this.MORPHTARGETS_NORMAL = false;
  35874. _this.MORPHTARGETS_TANGENT = false;
  35875. _this.NUM_MORPH_INFLUENCERS = 0;
  35876. _this.IMAGEPROCESSING = false;
  35877. _this.VIGNETTE = false;
  35878. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  35879. _this.VIGNETTEBLENDMODEOPAQUE = false;
  35880. _this.TONEMAPPING = false;
  35881. _this.CONTRAST = false;
  35882. _this.COLORCURVES = false;
  35883. _this.COLORGRADING = false;
  35884. _this.COLORGRADING3D = false;
  35885. _this.SAMPLER3DGREENDEPTH = false;
  35886. _this.SAMPLER3DBGRMAP = false;
  35887. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  35888. _this.EXPOSURE = false;
  35889. _this.USEPHYSICALLIGHTFALLOFF = false;
  35890. _this.TWOSIDEDLIGHTING = false;
  35891. _this.SHADOWFLOAT = false;
  35892. _this.CLIPPLANE = false;
  35893. _this.POINTSIZE = false;
  35894. _this.FOG = false;
  35895. _this.LOGARITHMICDEPTH = false;
  35896. _this.FORCENORMALFORWARD = false;
  35897. _this.rebuild();
  35898. return _this;
  35899. }
  35900. PBRMaterialDefines.prototype.reset = function () {
  35901. _super.prototype.reset.call(this);
  35902. this.ALPHATESTVALUE = 0.5;
  35903. this.PBR = true;
  35904. };
  35905. return PBRMaterialDefines;
  35906. }(BABYLON.MaterialDefines));
  35907. /**
  35908. * The Physically based material base class of BJS.
  35909. *
  35910. * This offers the main features of a standard PBR material.
  35911. * For more information, please refer to the documentation :
  35912. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  35913. */
  35914. var PBRBaseMaterial = /** @class */ (function (_super) {
  35915. __extends(PBRBaseMaterial, _super);
  35916. /**
  35917. * Instantiates a new PBRMaterial instance.
  35918. *
  35919. * @param name The material name
  35920. * @param scene The scene the material will be use in.
  35921. */
  35922. function PBRBaseMaterial(name, scene) {
  35923. var _this = _super.call(this, name, scene) || this;
  35924. /**
  35925. * Intensity of the direct lights e.g. the four lights available in your scene.
  35926. * This impacts both the direct diffuse and specular highlights.
  35927. */
  35928. _this._directIntensity = 1.0;
  35929. /**
  35930. * Intensity of the emissive part of the material.
  35931. * This helps controlling the emissive effect without modifying the emissive color.
  35932. */
  35933. _this._emissiveIntensity = 1.0;
  35934. /**
  35935. * Intensity of the environment e.g. how much the environment will light the object
  35936. * either through harmonics for rough material or through the refelction for shiny ones.
  35937. */
  35938. _this._environmentIntensity = 1.0;
  35939. /**
  35940. * This is a special control allowing the reduction of the specular highlights coming from the
  35941. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  35942. */
  35943. _this._specularIntensity = 1.0;
  35944. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  35945. /**
  35946. * Debug Control allowing disabling the bump map on this material.
  35947. */
  35948. _this._disableBumpMap = false;
  35949. /**
  35950. * AKA Occlusion Texture Intensity in other nomenclature.
  35951. */
  35952. _this._ambientTextureStrength = 1.0;
  35953. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  35954. /**
  35955. * AKA Diffuse Color in other nomenclature.
  35956. */
  35957. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  35958. /**
  35959. * AKA Specular Color in other nomenclature.
  35960. */
  35961. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  35962. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  35963. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  35964. /**
  35965. * AKA Glossiness in other nomenclature.
  35966. */
  35967. _this._microSurface = 0.9;
  35968. /**
  35969. * source material index of refraction (IOR)' / 'destination material IOR.
  35970. */
  35971. _this._indexOfRefraction = 0.66;
  35972. /**
  35973. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  35974. */
  35975. _this._invertRefractionY = false;
  35976. /**
  35977. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  35978. * Materials half opaque for instance using refraction could benefit from this control.
  35979. */
  35980. _this._linkRefractionWithTransparency = false;
  35981. _this._useLightmapAsShadowmap = false;
  35982. /**
  35983. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  35984. * makes the reflect vector face the model (under horizon).
  35985. */
  35986. _this._useHorizonOcclusion = true;
  35987. /**
  35988. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  35989. * too much the area relying on ambient texture to define their ambient occlusion.
  35990. */
  35991. _this._useRadianceOcclusion = true;
  35992. /**
  35993. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  35994. */
  35995. _this._useAlphaFromAlbedoTexture = false;
  35996. /**
  35997. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  35998. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  35999. */
  36000. _this._useSpecularOverAlpha = true;
  36001. /**
  36002. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  36003. */
  36004. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  36005. /**
  36006. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  36007. */
  36008. _this._useRoughnessFromMetallicTextureAlpha = true;
  36009. /**
  36010. * Specifies if the metallic texture contains the roughness information in its green channel.
  36011. */
  36012. _this._useRoughnessFromMetallicTextureGreen = false;
  36013. /**
  36014. * Specifies if the metallic texture contains the metallness information in its blue channel.
  36015. */
  36016. _this._useMetallnessFromMetallicTextureBlue = false;
  36017. /**
  36018. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  36019. */
  36020. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  36021. /**
  36022. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  36023. */
  36024. _this._useAmbientInGrayScale = false;
  36025. /**
  36026. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  36027. * The material will try to infer what glossiness each pixel should be.
  36028. */
  36029. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  36030. /**
  36031. * BJS is using an harcoded light falloff based on a manually sets up range.
  36032. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  36033. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  36034. */
  36035. _this._usePhysicalLightFalloff = true;
  36036. /**
  36037. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  36038. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  36039. */
  36040. _this._useRadianceOverAlpha = true;
  36041. /**
  36042. * Allows using the bump map in parallax mode.
  36043. */
  36044. _this._useParallax = false;
  36045. /**
  36046. * Allows using the bump map in parallax occlusion mode.
  36047. */
  36048. _this._useParallaxOcclusion = false;
  36049. /**
  36050. * Controls the scale bias of the parallax mode.
  36051. */
  36052. _this._parallaxScaleBias = 0.05;
  36053. /**
  36054. * If sets to true, disables all the lights affecting the material.
  36055. */
  36056. _this._disableLighting = false;
  36057. /**
  36058. * Number of Simultaneous lights allowed on the material.
  36059. */
  36060. _this._maxSimultaneousLights = 4;
  36061. /**
  36062. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  36063. */
  36064. _this._invertNormalMapX = false;
  36065. /**
  36066. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  36067. */
  36068. _this._invertNormalMapY = false;
  36069. /**
  36070. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36071. */
  36072. _this._twoSidedLighting = false;
  36073. /**
  36074. * Defines the alpha limits in alpha test mode.
  36075. */
  36076. _this._alphaCutOff = 0.4;
  36077. /**
  36078. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  36079. */
  36080. _this._forceAlphaTest = false;
  36081. /**
  36082. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36083. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  36084. */
  36085. _this._useAlphaFresnel = false;
  36086. /**
  36087. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36088. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  36089. */
  36090. _this._useLinearAlphaFresnel = false;
  36091. /**
  36092. * The transparency mode of the material.
  36093. */
  36094. _this._transparencyMode = null;
  36095. /**
  36096. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  36097. * from cos thetav and roughness:
  36098. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  36099. */
  36100. _this._environmentBRDFTexture = null;
  36101. /**
  36102. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  36103. */
  36104. _this._forceIrradianceInFragment = false;
  36105. /**
  36106. * Force normal to face away from face.
  36107. */
  36108. _this._forceNormalForward = false;
  36109. _this._renderTargets = new BABYLON.SmartArray(16);
  36110. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  36111. // Setup the default processing configuration to the scene.
  36112. _this._attachImageProcessingConfiguration(null);
  36113. _this.getRenderTargetTextures = function () {
  36114. _this._renderTargets.reset();
  36115. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  36116. _this._renderTargets.push(_this._reflectionTexture);
  36117. }
  36118. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  36119. _this._renderTargets.push(_this._refractionTexture);
  36120. }
  36121. return _this._renderTargets;
  36122. };
  36123. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  36124. return _this;
  36125. }
  36126. /**
  36127. * Attaches a new image processing configuration to the PBR Material.
  36128. * @param configuration
  36129. */
  36130. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  36131. var _this = this;
  36132. if (configuration === this._imageProcessingConfiguration) {
  36133. return;
  36134. }
  36135. // Detaches observer.
  36136. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36137. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36138. }
  36139. // Pick the scene configuration if needed.
  36140. if (!configuration) {
  36141. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  36142. }
  36143. else {
  36144. this._imageProcessingConfiguration = configuration;
  36145. }
  36146. // Attaches observer.
  36147. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  36148. _this._markAllSubMeshesAsImageProcessingDirty();
  36149. });
  36150. };
  36151. PBRBaseMaterial.prototype.getClassName = function () {
  36152. return "PBRBaseMaterial";
  36153. };
  36154. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  36155. get: function () {
  36156. return this._useLogarithmicDepth;
  36157. },
  36158. set: function (value) {
  36159. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  36160. },
  36161. enumerable: true,
  36162. configurable: true
  36163. });
  36164. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  36165. /**
  36166. * Gets the current transparency mode.
  36167. */
  36168. get: function () {
  36169. return this._transparencyMode;
  36170. },
  36171. /**
  36172. * Sets the transparency mode of the material.
  36173. */
  36174. set: function (value) {
  36175. if (this._transparencyMode === value) {
  36176. return;
  36177. }
  36178. this._transparencyMode = value;
  36179. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  36180. this._markAllSubMeshesAsTexturesDirty();
  36181. },
  36182. enumerable: true,
  36183. configurable: true
  36184. });
  36185. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  36186. /**
  36187. * Returns true if alpha blending should be disabled.
  36188. */
  36189. get: function () {
  36190. return (this._linkRefractionWithTransparency ||
  36191. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  36192. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  36193. },
  36194. enumerable: true,
  36195. configurable: true
  36196. });
  36197. /**
  36198. * Specifies whether or not this material should be rendered in alpha blend mode.
  36199. */
  36200. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  36201. if (this._disableAlphaBlending) {
  36202. return false;
  36203. }
  36204. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  36205. };
  36206. /**
  36207. * Specifies whether or not this material should be rendered in alpha blend mode for the given mesh.
  36208. */
  36209. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  36210. if (this._disableAlphaBlending) {
  36211. return false;
  36212. }
  36213. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  36214. };
  36215. /**
  36216. * Specifies whether or not this material should be rendered in alpha test mode.
  36217. */
  36218. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  36219. if (this._forceAlphaTest) {
  36220. return true;
  36221. }
  36222. if (this._linkRefractionWithTransparency) {
  36223. return false;
  36224. }
  36225. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  36226. };
  36227. /**
  36228. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  36229. */
  36230. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  36231. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  36232. };
  36233. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  36234. return this._albedoTexture;
  36235. };
  36236. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36237. var _this = this;
  36238. if (subMesh.effect && this.isFrozen) {
  36239. if (this._wasPreviouslyReady) {
  36240. return true;
  36241. }
  36242. }
  36243. if (!subMesh._materialDefines) {
  36244. subMesh._materialDefines = new PBRMaterialDefines();
  36245. }
  36246. var scene = this.getScene();
  36247. var defines = subMesh._materialDefines;
  36248. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  36249. if (defines._renderId === scene.getRenderId()) {
  36250. return true;
  36251. }
  36252. }
  36253. var engine = scene.getEngine();
  36254. // Lights
  36255. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  36256. defines._needNormals = true;
  36257. // Textures
  36258. if (defines._areTexturesDirty) {
  36259. defines._needUVs = false;
  36260. if (scene.texturesEnabled) {
  36261. if (scene.getEngine().getCaps().textureLOD) {
  36262. defines.LODBASEDMICROSFURACE = true;
  36263. }
  36264. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36265. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  36266. return false;
  36267. }
  36268. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  36269. }
  36270. else {
  36271. defines.ALBEDO = false;
  36272. }
  36273. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  36274. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  36275. return false;
  36276. }
  36277. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  36278. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  36279. }
  36280. else {
  36281. defines.AMBIENT = false;
  36282. }
  36283. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  36284. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  36285. return false;
  36286. }
  36287. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  36288. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  36289. }
  36290. else {
  36291. defines.OPACITY = false;
  36292. }
  36293. var reflectionTexture = this._getReflectionTexture();
  36294. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36295. if (!reflectionTexture.isReadyOrNotBlocking()) {
  36296. return false;
  36297. }
  36298. defines.REFLECTION = true;
  36299. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  36300. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  36301. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  36302. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  36303. defines.INVERTCUBICMAP = true;
  36304. }
  36305. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  36306. switch (reflectionTexture.coordinatesMode) {
  36307. case BABYLON.Texture.CUBIC_MODE:
  36308. case BABYLON.Texture.INVCUBIC_MODE:
  36309. defines.REFLECTIONMAP_CUBIC = true;
  36310. break;
  36311. case BABYLON.Texture.EXPLICIT_MODE:
  36312. defines.REFLECTIONMAP_EXPLICIT = true;
  36313. break;
  36314. case BABYLON.Texture.PLANAR_MODE:
  36315. defines.REFLECTIONMAP_PLANAR = true;
  36316. break;
  36317. case BABYLON.Texture.PROJECTION_MODE:
  36318. defines.REFLECTIONMAP_PROJECTION = true;
  36319. break;
  36320. case BABYLON.Texture.SKYBOX_MODE:
  36321. defines.REFLECTIONMAP_SKYBOX = true;
  36322. break;
  36323. case BABYLON.Texture.SPHERICAL_MODE:
  36324. defines.REFLECTIONMAP_SPHERICAL = true;
  36325. break;
  36326. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  36327. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  36328. break;
  36329. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  36330. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  36331. break;
  36332. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  36333. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  36334. break;
  36335. }
  36336. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  36337. if (reflectionTexture.sphericalPolynomial) {
  36338. defines.USESPHERICALFROMREFLECTIONMAP = true;
  36339. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  36340. defines.USESPHERICALINVERTEX = false;
  36341. }
  36342. else {
  36343. defines.USESPHERICALINVERTEX = true;
  36344. }
  36345. }
  36346. }
  36347. }
  36348. else {
  36349. defines.REFLECTION = false;
  36350. defines.REFLECTIONMAP_3D = false;
  36351. defines.REFLECTIONMAP_SPHERICAL = false;
  36352. defines.REFLECTIONMAP_PLANAR = false;
  36353. defines.REFLECTIONMAP_CUBIC = false;
  36354. defines.REFLECTIONMAP_PROJECTION = false;
  36355. defines.REFLECTIONMAP_SKYBOX = false;
  36356. defines.REFLECTIONMAP_EXPLICIT = false;
  36357. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  36358. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  36359. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  36360. defines.INVERTCUBICMAP = false;
  36361. defines.USESPHERICALFROMREFLECTIONMAP = false;
  36362. defines.USESPHERICALINVERTEX = false;
  36363. defines.REFLECTIONMAP_OPPOSITEZ = false;
  36364. defines.LODINREFLECTIONALPHA = false;
  36365. defines.GAMMAREFLECTION = false;
  36366. }
  36367. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  36368. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  36369. return false;
  36370. }
  36371. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  36372. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  36373. }
  36374. else {
  36375. defines.LIGHTMAP = false;
  36376. }
  36377. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  36378. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  36379. return false;
  36380. }
  36381. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  36382. }
  36383. else {
  36384. defines.EMISSIVE = false;
  36385. }
  36386. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  36387. if (this._metallicTexture) {
  36388. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  36389. return false;
  36390. }
  36391. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  36392. defines.METALLICWORKFLOW = true;
  36393. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  36394. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  36395. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  36396. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  36397. }
  36398. else if (this._reflectivityTexture) {
  36399. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  36400. return false;
  36401. }
  36402. defines.METALLICWORKFLOW = false;
  36403. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  36404. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  36405. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  36406. }
  36407. else {
  36408. defines.METALLICWORKFLOW = false;
  36409. defines.REFLECTIVITY = false;
  36410. }
  36411. if (this._microSurfaceTexture) {
  36412. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  36413. return false;
  36414. }
  36415. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  36416. }
  36417. else {
  36418. defines.MICROSURFACEMAP = false;
  36419. }
  36420. }
  36421. else {
  36422. defines.REFLECTIVITY = false;
  36423. defines.MICROSURFACEMAP = false;
  36424. }
  36425. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  36426. // Bump texure can not be none blocking.
  36427. if (!this._bumpTexture.isReady()) {
  36428. return false;
  36429. }
  36430. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  36431. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36432. defines.PARALLAX = true;
  36433. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  36434. }
  36435. else {
  36436. defines.PARALLAX = false;
  36437. }
  36438. }
  36439. else {
  36440. defines.BUMP = false;
  36441. }
  36442. var refractionTexture = this._getRefractionTexture();
  36443. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  36444. if (!refractionTexture.isReadyOrNotBlocking()) {
  36445. return false;
  36446. }
  36447. defines.REFRACTION = true;
  36448. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  36449. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  36450. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  36451. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  36452. if (this._linkRefractionWithTransparency) {
  36453. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  36454. }
  36455. }
  36456. else {
  36457. defines.REFRACTION = false;
  36458. }
  36459. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36460. // This is blocking.
  36461. if (!this._environmentBRDFTexture.isReady()) {
  36462. return false;
  36463. }
  36464. defines.ENVIRONMENTBRDF = true;
  36465. }
  36466. else {
  36467. defines.ENVIRONMENTBRDF = false;
  36468. }
  36469. if (this._shouldUseAlphaFromAlbedoTexture()) {
  36470. defines.ALPHAFROMALBEDO = true;
  36471. }
  36472. else {
  36473. defines.ALPHAFROMALBEDO = false;
  36474. }
  36475. }
  36476. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  36477. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  36478. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  36479. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  36480. defines.METALLICWORKFLOW = true;
  36481. }
  36482. else {
  36483. defines.METALLICWORKFLOW = false;
  36484. }
  36485. if (!this.backFaceCulling && this._twoSidedLighting) {
  36486. defines.TWOSIDEDLIGHTING = true;
  36487. }
  36488. else {
  36489. defines.TWOSIDEDLIGHTING = false;
  36490. }
  36491. defines.ALPHATESTVALUE = this._alphaCutOff;
  36492. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  36493. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  36494. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  36495. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  36496. }
  36497. if (defines._areImageProcessingDirty) {
  36498. if (!this._imageProcessingConfiguration.isReady()) {
  36499. return false;
  36500. }
  36501. this._imageProcessingConfiguration.prepareDefines(defines);
  36502. }
  36503. defines.FORCENORMALFORWARD = this._forceNormalForward;
  36504. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  36505. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  36506. // Misc.
  36507. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  36508. // Values that need to be evaluated on every frame
  36509. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, this._forceAlphaTest);
  36510. // Attribs
  36511. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE) && mesh) {
  36512. var bufferMesh = null;
  36513. if (mesh instanceof BABYLON.InstancedMesh) {
  36514. bufferMesh = mesh.sourceMesh;
  36515. }
  36516. else if (mesh instanceof BABYLON.Mesh) {
  36517. bufferMesh = mesh;
  36518. }
  36519. if (bufferMesh) {
  36520. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36521. // If the first normal's components is the zero vector in one of the submeshes, we have invalid normals
  36522. var normalVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.NormalKind);
  36523. var normals = normalVertexBuffer.getData();
  36524. var vertexBufferOffset = normalVertexBuffer.getOffset();
  36525. var strideSize = normalVertexBuffer.getStrideSize();
  36526. var offset = vertexBufferOffset + subMesh.indexStart * strideSize;
  36527. if (normals[offset] === 0 && normals[offset + 1] === 0 && normals[offset + 2] === 0) {
  36528. defines.NORMAL = false;
  36529. }
  36530. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36531. // If the first tangent's components is the zero vector in one of the submeshes, we have invalid tangents
  36532. var tangentVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.TangentKind);
  36533. var tangents = tangentVertexBuffer.getData();
  36534. var vertexBufferOffset_1 = tangentVertexBuffer.getOffset();
  36535. var strideSize_1 = tangentVertexBuffer.getStrideSize();
  36536. var offset_1 = vertexBufferOffset_1 + subMesh.indexStart * strideSize_1;
  36537. if (tangents[offset_1] === 0 && tangents[offset_1 + 1] === 0 && tangents[offset_1 + 2] === 0) {
  36538. defines.TANGENT = false;
  36539. }
  36540. }
  36541. }
  36542. else {
  36543. if (!scene.getEngine().getCaps().standardDerivatives) {
  36544. bufferMesh.createNormals(true);
  36545. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  36546. }
  36547. }
  36548. }
  36549. }
  36550. // Get correct effect
  36551. if (defines.isDirty) {
  36552. defines.markAsProcessed();
  36553. scene.resetCachedMaterial();
  36554. // Fallbacks
  36555. var fallbacks = new BABYLON.EffectFallbacks();
  36556. var fallbackRank = 0;
  36557. if (defines.USESPHERICALINVERTEX) {
  36558. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  36559. }
  36560. if (defines.FOG) {
  36561. fallbacks.addFallback(fallbackRank, "FOG");
  36562. }
  36563. if (defines.POINTSIZE) {
  36564. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  36565. }
  36566. if (defines.LOGARITHMICDEPTH) {
  36567. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  36568. }
  36569. if (defines.PARALLAX) {
  36570. fallbacks.addFallback(fallbackRank, "PARALLAX");
  36571. }
  36572. if (defines.PARALLAXOCCLUSION) {
  36573. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  36574. }
  36575. if (defines.ENVIRONMENTBRDF) {
  36576. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  36577. }
  36578. if (defines.TANGENT) {
  36579. fallbacks.addFallback(fallbackRank++, "TANGENT");
  36580. }
  36581. if (defines.BUMP) {
  36582. fallbacks.addFallback(fallbackRank++, "BUMP");
  36583. }
  36584. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  36585. if (defines.SPECULARTERM) {
  36586. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  36587. }
  36588. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  36589. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  36590. }
  36591. if (defines.LIGHTMAP) {
  36592. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  36593. }
  36594. if (defines.NORMAL) {
  36595. fallbacks.addFallback(fallbackRank++, "NORMAL");
  36596. }
  36597. if (defines.AMBIENT) {
  36598. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  36599. }
  36600. if (defines.EMISSIVE) {
  36601. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  36602. }
  36603. if (defines.VERTEXCOLOR) {
  36604. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  36605. }
  36606. if (defines.NUM_BONE_INFLUENCERS > 0) {
  36607. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  36608. }
  36609. if (defines.MORPHTARGETS) {
  36610. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  36611. }
  36612. //Attributes
  36613. var attribs = [BABYLON.VertexBuffer.PositionKind];
  36614. if (defines.NORMAL) {
  36615. attribs.push(BABYLON.VertexBuffer.NormalKind);
  36616. }
  36617. if (defines.TANGENT) {
  36618. attribs.push(BABYLON.VertexBuffer.TangentKind);
  36619. }
  36620. if (defines.UV1) {
  36621. attribs.push(BABYLON.VertexBuffer.UVKind);
  36622. }
  36623. if (defines.UV2) {
  36624. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  36625. }
  36626. if (defines.VERTEXCOLOR) {
  36627. attribs.push(BABYLON.VertexBuffer.ColorKind);
  36628. }
  36629. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  36630. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  36631. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  36632. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  36633. "vFogInfos", "vFogColor", "pointSize",
  36634. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  36635. "mBones",
  36636. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  36637. "vLightingIntensity",
  36638. "logarithmicDepthConstant",
  36639. "vSphericalX", "vSphericalY", "vSphericalZ",
  36640. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  36641. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  36642. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  36643. "vTangentSpaceParams"
  36644. ];
  36645. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  36646. "bumpSampler", "lightmapSampler", "opacitySampler",
  36647. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  36648. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  36649. "microSurfaceSampler", "environmentBrdfSampler"];
  36650. var uniformBuffers = ["Material", "Scene"];
  36651. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  36652. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  36653. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  36654. uniformsNames: uniforms,
  36655. uniformBuffersNames: uniformBuffers,
  36656. samplers: samplers,
  36657. defines: defines,
  36658. maxSimultaneousLights: this._maxSimultaneousLights
  36659. });
  36660. var onCompiled = function (effect) {
  36661. if (_this.onCompiled) {
  36662. _this.onCompiled(effect);
  36663. }
  36664. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  36665. };
  36666. var join = defines.toString();
  36667. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  36668. attributes: attribs,
  36669. uniformsNames: uniforms,
  36670. uniformBuffersNames: uniformBuffers,
  36671. samplers: samplers,
  36672. defines: join,
  36673. fallbacks: fallbacks,
  36674. onCompiled: onCompiled,
  36675. onError: this.onError,
  36676. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  36677. }, engine), defines);
  36678. this.buildUniformLayout();
  36679. }
  36680. if (!subMesh.effect || !subMesh.effect.isReady()) {
  36681. return false;
  36682. }
  36683. defines._renderId = scene.getRenderId();
  36684. this._wasPreviouslyReady = true;
  36685. return true;
  36686. };
  36687. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  36688. // Order is important !
  36689. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  36690. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  36691. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  36692. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  36693. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  36694. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  36695. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  36696. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  36697. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  36698. this._uniformBuffer.addUniform("vBumpInfos", 3);
  36699. this._uniformBuffer.addUniform("albedoMatrix", 16);
  36700. this._uniformBuffer.addUniform("ambientMatrix", 16);
  36701. this._uniformBuffer.addUniform("opacityMatrix", 16);
  36702. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  36703. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  36704. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  36705. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  36706. this._uniformBuffer.addUniform("bumpMatrix", 16);
  36707. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  36708. this._uniformBuffer.addUniform("refractionMatrix", 16);
  36709. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  36710. this._uniformBuffer.addUniform("vReflectionColor", 3);
  36711. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  36712. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  36713. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  36714. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  36715. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  36716. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  36717. this._uniformBuffer.addUniform("pointSize", 1);
  36718. this._uniformBuffer.create();
  36719. };
  36720. PBRBaseMaterial.prototype.unbind = function () {
  36721. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  36722. this._uniformBuffer.setTexture("reflectionSampler", null);
  36723. }
  36724. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  36725. this._uniformBuffer.setTexture("refractionSampler", null);
  36726. }
  36727. _super.prototype.unbind.call(this);
  36728. };
  36729. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  36730. this._activeEffect.setMatrix("world", world);
  36731. };
  36732. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  36733. var scene = this.getScene();
  36734. var defines = subMesh._materialDefines;
  36735. if (!defines) {
  36736. return;
  36737. }
  36738. var effect = subMesh.effect;
  36739. if (!effect) {
  36740. return;
  36741. }
  36742. this._activeEffect = effect;
  36743. // Matrices
  36744. this.bindOnlyWorldMatrix(world);
  36745. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  36746. // Bones
  36747. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  36748. var reflectionTexture = null;
  36749. if (mustRebind) {
  36750. this._uniformBuffer.bindToEffect(effect, "Material");
  36751. this.bindViewProjection(effect);
  36752. reflectionTexture = this._getReflectionTexture();
  36753. var refractionTexture = this._getRefractionTexture();
  36754. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  36755. // Texture uniforms
  36756. if (scene.texturesEnabled) {
  36757. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36758. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  36759. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  36760. }
  36761. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  36762. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  36763. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  36764. }
  36765. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  36766. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  36767. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  36768. }
  36769. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36770. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  36771. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  36772. var polynomials = reflectionTexture.sphericalPolynomial;
  36773. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  36774. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  36775. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  36776. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  36777. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  36778. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  36779. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  36780. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  36781. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  36782. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  36783. }
  36784. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  36785. }
  36786. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  36787. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  36788. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  36789. }
  36790. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  36791. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  36792. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  36793. }
  36794. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  36795. if (this._metallicTexture) {
  36796. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  36797. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  36798. }
  36799. else if (this._reflectivityTexture) {
  36800. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  36801. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  36802. }
  36803. if (this._microSurfaceTexture) {
  36804. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  36805. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  36806. }
  36807. }
  36808. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  36809. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  36810. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  36811. if (scene._mirroredCameraPosition) {
  36812. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  36813. }
  36814. else {
  36815. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  36816. }
  36817. }
  36818. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  36819. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  36820. var depth = 1.0;
  36821. if (!refractionTexture.isCube) {
  36822. if (refractionTexture.depth) {
  36823. depth = refractionTexture.depth;
  36824. }
  36825. }
  36826. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  36827. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  36828. }
  36829. }
  36830. // Point size
  36831. if (this.pointsCloud) {
  36832. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  36833. }
  36834. // Colors
  36835. if (defines.METALLICWORKFLOW) {
  36836. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  36837. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  36838. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  36839. }
  36840. else {
  36841. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  36842. }
  36843. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  36844. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  36845. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  36846. // Misc
  36847. this._lightingInfos.x = this._directIntensity;
  36848. this._lightingInfos.y = this._emissiveIntensity;
  36849. this._lightingInfos.z = this._environmentIntensity;
  36850. this._lightingInfos.w = this._specularIntensity;
  36851. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  36852. }
  36853. // Textures
  36854. if (scene.texturesEnabled) {
  36855. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36856. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  36857. }
  36858. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  36859. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  36860. }
  36861. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  36862. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  36863. }
  36864. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36865. if (defines.LODBASEDMICROSFURACE) {
  36866. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  36867. }
  36868. else {
  36869. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  36870. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  36871. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  36872. }
  36873. }
  36874. if (defines.ENVIRONMENTBRDF) {
  36875. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  36876. }
  36877. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  36878. if (defines.LODBASEDMICROSFURACE) {
  36879. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  36880. }
  36881. else {
  36882. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  36883. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  36884. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  36885. }
  36886. }
  36887. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  36888. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  36889. }
  36890. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  36891. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  36892. }
  36893. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  36894. if (this._metallicTexture) {
  36895. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  36896. }
  36897. else if (this._reflectivityTexture) {
  36898. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  36899. }
  36900. if (this._microSurfaceTexture) {
  36901. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  36902. }
  36903. }
  36904. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  36905. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  36906. }
  36907. }
  36908. // Clip plane
  36909. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  36910. // Colors
  36911. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  36912. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  36913. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  36914. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  36915. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  36916. }
  36917. if (mustRebind || !this.isFrozen) {
  36918. // Lights
  36919. if (scene.lightsEnabled && !this._disableLighting) {
  36920. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  36921. }
  36922. // View
  36923. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  36924. this.bindView(effect);
  36925. }
  36926. // Fog
  36927. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  36928. // Morph targets
  36929. if (defines.NUM_MORPH_INFLUENCERS) {
  36930. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  36931. }
  36932. // image processing
  36933. this._imageProcessingConfiguration.bind(this._activeEffect);
  36934. // Log. depth
  36935. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  36936. }
  36937. this._uniformBuffer.update();
  36938. this._afterBind(mesh);
  36939. };
  36940. PBRBaseMaterial.prototype.getAnimatables = function () {
  36941. var results = [];
  36942. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  36943. results.push(this._albedoTexture);
  36944. }
  36945. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  36946. results.push(this._ambientTexture);
  36947. }
  36948. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  36949. results.push(this._opacityTexture);
  36950. }
  36951. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  36952. results.push(this._reflectionTexture);
  36953. }
  36954. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  36955. results.push(this._emissiveTexture);
  36956. }
  36957. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  36958. results.push(this._metallicTexture);
  36959. }
  36960. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  36961. results.push(this._reflectivityTexture);
  36962. }
  36963. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  36964. results.push(this._bumpTexture);
  36965. }
  36966. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  36967. results.push(this._lightmapTexture);
  36968. }
  36969. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  36970. results.push(this._refractionTexture);
  36971. }
  36972. return results;
  36973. };
  36974. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  36975. if (this._reflectionTexture) {
  36976. return this._reflectionTexture;
  36977. }
  36978. return this.getScene().environmentTexture;
  36979. };
  36980. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  36981. if (this._refractionTexture) {
  36982. return this._refractionTexture;
  36983. }
  36984. if (this._linkRefractionWithTransparency) {
  36985. return this.getScene().environmentTexture;
  36986. }
  36987. return null;
  36988. };
  36989. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36990. if (forceDisposeTextures) {
  36991. if (this._albedoTexture) {
  36992. this._albedoTexture.dispose();
  36993. }
  36994. if (this._ambientTexture) {
  36995. this._ambientTexture.dispose();
  36996. }
  36997. if (this._opacityTexture) {
  36998. this._opacityTexture.dispose();
  36999. }
  37000. if (this._reflectionTexture) {
  37001. this._reflectionTexture.dispose();
  37002. }
  37003. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  37004. this._environmentBRDFTexture.dispose();
  37005. }
  37006. if (this._emissiveTexture) {
  37007. this._emissiveTexture.dispose();
  37008. }
  37009. if (this._metallicTexture) {
  37010. this._metallicTexture.dispose();
  37011. }
  37012. if (this._reflectivityTexture) {
  37013. this._reflectivityTexture.dispose();
  37014. }
  37015. if (this._bumpTexture) {
  37016. this._bumpTexture.dispose();
  37017. }
  37018. if (this._lightmapTexture) {
  37019. this._lightmapTexture.dispose();
  37020. }
  37021. if (this._refractionTexture) {
  37022. this._refractionTexture.dispose();
  37023. }
  37024. }
  37025. this._renderTargets.dispose();
  37026. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37027. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37028. }
  37029. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  37030. };
  37031. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  37032. __decorate([
  37033. BABYLON.serializeAsImageProcessingConfiguration()
  37034. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  37035. __decorate([
  37036. BABYLON.serialize()
  37037. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  37038. __decorate([
  37039. BABYLON.serialize()
  37040. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  37041. return PBRBaseMaterial;
  37042. }(BABYLON.PushMaterial));
  37043. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  37044. })(BABYLON || (BABYLON = {}));
  37045. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  37046. var BABYLON;
  37047. (function (BABYLON) {
  37048. var Internals;
  37049. (function (Internals) {
  37050. /**
  37051. * The Physically based simple base material of BJS.
  37052. *
  37053. * This enables better naming and convention enforcements on top of the pbrMaterial.
  37054. * It is used as the base class for both the specGloss and metalRough conventions.
  37055. */
  37056. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  37057. __extends(PBRBaseSimpleMaterial, _super);
  37058. /**
  37059. * Instantiates a new PBRMaterial instance.
  37060. *
  37061. * @param name The material name
  37062. * @param scene The scene the material will be use in.
  37063. */
  37064. function PBRBaseSimpleMaterial(name, scene) {
  37065. var _this = _super.call(this, name, scene) || this;
  37066. /**
  37067. * Number of Simultaneous lights allowed on the material.
  37068. */
  37069. _this.maxSimultaneousLights = 4;
  37070. /**
  37071. * If sets to true, disables all the lights affecting the material.
  37072. */
  37073. _this.disableLighting = false;
  37074. /**
  37075. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  37076. */
  37077. _this.invertNormalMapX = false;
  37078. /**
  37079. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  37080. */
  37081. _this.invertNormalMapY = false;
  37082. /**
  37083. * Emissivie color used to self-illuminate the model.
  37084. */
  37085. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  37086. /**
  37087. * Occlusion Channel Strenght.
  37088. */
  37089. _this.occlusionStrength = 1.0;
  37090. _this.useLightmapAsShadowmap = false;
  37091. _this._useAlphaFromAlbedoTexture = true;
  37092. _this._useAmbientInGrayScale = true;
  37093. return _this;
  37094. }
  37095. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  37096. /**
  37097. * Gets the current double sided mode.
  37098. */
  37099. get: function () {
  37100. return this._twoSidedLighting;
  37101. },
  37102. /**
  37103. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  37104. */
  37105. set: function (value) {
  37106. if (this._twoSidedLighting === value) {
  37107. return;
  37108. }
  37109. this._twoSidedLighting = value;
  37110. this.backFaceCulling = !value;
  37111. this._markAllSubMeshesAsTexturesDirty();
  37112. },
  37113. enumerable: true,
  37114. configurable: true
  37115. });
  37116. /**
  37117. * Return the active textures of the material.
  37118. */
  37119. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  37120. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37121. if (this.environmentTexture) {
  37122. activeTextures.push(this.environmentTexture);
  37123. }
  37124. if (this.normalTexture) {
  37125. activeTextures.push(this.normalTexture);
  37126. }
  37127. if (this.emissiveTexture) {
  37128. activeTextures.push(this.emissiveTexture);
  37129. }
  37130. if (this.occlusionTexture) {
  37131. activeTextures.push(this.occlusionTexture);
  37132. }
  37133. if (this.lightmapTexture) {
  37134. activeTextures.push(this.lightmapTexture);
  37135. }
  37136. return activeTextures;
  37137. };
  37138. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  37139. if (_super.prototype.hasTexture.call(this, texture)) {
  37140. return true;
  37141. }
  37142. if (this.lightmapTexture === texture) {
  37143. return true;
  37144. }
  37145. return false;
  37146. };
  37147. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  37148. return "PBRBaseSimpleMaterial";
  37149. };
  37150. __decorate([
  37151. BABYLON.serialize(),
  37152. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37153. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  37154. __decorate([
  37155. BABYLON.serialize(),
  37156. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37157. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  37158. __decorate([
  37159. BABYLON.serializeAsTexture(),
  37160. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  37161. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  37162. __decorate([
  37163. BABYLON.serialize(),
  37164. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37165. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  37166. __decorate([
  37167. BABYLON.serialize(),
  37168. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37169. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  37170. __decorate([
  37171. BABYLON.serializeAsTexture(),
  37172. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  37173. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  37174. __decorate([
  37175. BABYLON.serializeAsColor3("emissive"),
  37176. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37177. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  37178. __decorate([
  37179. BABYLON.serializeAsTexture(),
  37180. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37181. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  37182. __decorate([
  37183. BABYLON.serialize(),
  37184. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  37185. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  37186. __decorate([
  37187. BABYLON.serializeAsTexture(),
  37188. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  37189. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  37190. __decorate([
  37191. BABYLON.serialize(),
  37192. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  37193. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  37194. __decorate([
  37195. BABYLON.serialize()
  37196. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  37197. __decorate([
  37198. BABYLON.serializeAsTexture(),
  37199. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  37200. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  37201. __decorate([
  37202. BABYLON.serialize(),
  37203. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37204. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  37205. return PBRBaseSimpleMaterial;
  37206. }(BABYLON.PBRBaseMaterial));
  37207. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  37208. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  37209. })(BABYLON || (BABYLON = {}));
  37210. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  37211. var BABYLON;
  37212. (function (BABYLON) {
  37213. /**
  37214. * The Physically based material of BJS.
  37215. *
  37216. * This offers the main features of a standard PBR material.
  37217. * For more information, please refer to the documentation :
  37218. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  37219. */
  37220. var PBRMaterial = /** @class */ (function (_super) {
  37221. __extends(PBRMaterial, _super);
  37222. /**
  37223. * Instantiates a new PBRMaterial instance.
  37224. *
  37225. * @param name The material name
  37226. * @param scene The scene the material will be use in.
  37227. */
  37228. function PBRMaterial(name, scene) {
  37229. var _this = _super.call(this, name, scene) || this;
  37230. /**
  37231. * Intensity of the direct lights e.g. the four lights available in your scene.
  37232. * This impacts both the direct diffuse and specular highlights.
  37233. */
  37234. _this.directIntensity = 1.0;
  37235. /**
  37236. * Intensity of the emissive part of the material.
  37237. * This helps controlling the emissive effect without modifying the emissive color.
  37238. */
  37239. _this.emissiveIntensity = 1.0;
  37240. /**
  37241. * Intensity of the environment e.g. how much the environment will light the object
  37242. * either through harmonics for rough material or through the refelction for shiny ones.
  37243. */
  37244. _this.environmentIntensity = 1.0;
  37245. /**
  37246. * This is a special control allowing the reduction of the specular highlights coming from the
  37247. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  37248. */
  37249. _this.specularIntensity = 1.0;
  37250. /**
  37251. * Debug Control allowing disabling the bump map on this material.
  37252. */
  37253. _this.disableBumpMap = false;
  37254. /**
  37255. * AKA Occlusion Texture Intensity in other nomenclature.
  37256. */
  37257. _this.ambientTextureStrength = 1.0;
  37258. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  37259. /**
  37260. * AKA Diffuse Color in other nomenclature.
  37261. */
  37262. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  37263. /**
  37264. * AKA Specular Color in other nomenclature.
  37265. */
  37266. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  37267. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  37268. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  37269. /**
  37270. * AKA Glossiness in other nomenclature.
  37271. */
  37272. _this.microSurface = 1.0;
  37273. /**
  37274. * source material index of refraction (IOR)' / 'destination material IOR.
  37275. */
  37276. _this.indexOfRefraction = 0.66;
  37277. /**
  37278. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  37279. */
  37280. _this.invertRefractionY = false;
  37281. /**
  37282. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  37283. * Materials half opaque for instance using refraction could benefit from this control.
  37284. */
  37285. _this.linkRefractionWithTransparency = false;
  37286. _this.useLightmapAsShadowmap = false;
  37287. /**
  37288. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  37289. */
  37290. _this.useAlphaFromAlbedoTexture = false;
  37291. /**
  37292. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  37293. */
  37294. _this.forceAlphaTest = false;
  37295. /**
  37296. * Defines the alpha limits in alpha test mode.
  37297. */
  37298. _this.alphaCutOff = 0.4;
  37299. /**
  37300. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  37301. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  37302. */
  37303. _this.useSpecularOverAlpha = true;
  37304. /**
  37305. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  37306. */
  37307. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  37308. /**
  37309. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  37310. */
  37311. _this.useRoughnessFromMetallicTextureAlpha = true;
  37312. /**
  37313. * Specifies if the metallic texture contains the roughness information in its green channel.
  37314. */
  37315. _this.useRoughnessFromMetallicTextureGreen = false;
  37316. /**
  37317. * Specifies if the metallic texture contains the metallness information in its blue channel.
  37318. */
  37319. _this.useMetallnessFromMetallicTextureBlue = false;
  37320. /**
  37321. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  37322. */
  37323. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  37324. /**
  37325. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  37326. */
  37327. _this.useAmbientInGrayScale = false;
  37328. /**
  37329. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  37330. * The material will try to infer what glossiness each pixel should be.
  37331. */
  37332. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  37333. /**
  37334. * BJS is using an harcoded light falloff based on a manually sets up range.
  37335. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  37336. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  37337. */
  37338. _this.usePhysicalLightFalloff = true;
  37339. /**
  37340. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  37341. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  37342. */
  37343. _this.useRadianceOverAlpha = true;
  37344. /**
  37345. * Allows using the bump map in parallax mode.
  37346. */
  37347. _this.useParallax = false;
  37348. /**
  37349. * Allows using the bump map in parallax occlusion mode.
  37350. */
  37351. _this.useParallaxOcclusion = false;
  37352. /**
  37353. * Controls the scale bias of the parallax mode.
  37354. */
  37355. _this.parallaxScaleBias = 0.05;
  37356. /**
  37357. * If sets to true, disables all the lights affecting the material.
  37358. */
  37359. _this.disableLighting = false;
  37360. /**
  37361. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  37362. */
  37363. _this.forceIrradianceInFragment = false;
  37364. /**
  37365. * Number of Simultaneous lights allowed on the material.
  37366. */
  37367. _this.maxSimultaneousLights = 4;
  37368. /**
  37369. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  37370. */
  37371. _this.invertNormalMapX = false;
  37372. /**
  37373. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  37374. */
  37375. _this.invertNormalMapY = false;
  37376. /**
  37377. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  37378. */
  37379. _this.twoSidedLighting = false;
  37380. /**
  37381. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37382. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  37383. */
  37384. _this.useAlphaFresnel = false;
  37385. /**
  37386. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37387. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  37388. */
  37389. _this.useLinearAlphaFresnel = false;
  37390. /**
  37391. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37392. * And/Or occlude the blended part.
  37393. */
  37394. _this.environmentBRDFTexture = null;
  37395. /**
  37396. * Force normal to face away from face.
  37397. */
  37398. _this.forceNormalForward = false;
  37399. /**
  37400. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  37401. * makes the reflect vector face the model (under horizon).
  37402. */
  37403. _this.useHorizonOcclusion = true;
  37404. /**
  37405. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  37406. * too much the area relying on ambient texture to define their ambient occlusion.
  37407. */
  37408. _this.useRadianceOcclusion = true;
  37409. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  37410. return _this;
  37411. }
  37412. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  37413. /**
  37414. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  37415. */
  37416. get: function () {
  37417. return this._PBRMATERIAL_OPAQUE;
  37418. },
  37419. enumerable: true,
  37420. configurable: true
  37421. });
  37422. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  37423. /**
  37424. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  37425. */
  37426. get: function () {
  37427. return this._PBRMATERIAL_ALPHATEST;
  37428. },
  37429. enumerable: true,
  37430. configurable: true
  37431. });
  37432. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  37433. /**
  37434. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  37435. */
  37436. get: function () {
  37437. return this._PBRMATERIAL_ALPHABLEND;
  37438. },
  37439. enumerable: true,
  37440. configurable: true
  37441. });
  37442. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  37443. /**
  37444. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  37445. * They are also discarded below the alpha cutoff threshold to improve performances.
  37446. */
  37447. get: function () {
  37448. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  37449. },
  37450. enumerable: true,
  37451. configurable: true
  37452. });
  37453. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  37454. /**
  37455. * Gets the image processing configuration used either in this material.
  37456. */
  37457. get: function () {
  37458. return this._imageProcessingConfiguration;
  37459. },
  37460. /**
  37461. * Sets the Default image processing configuration used either in the this material.
  37462. *
  37463. * If sets to null, the scene one is in use.
  37464. */
  37465. set: function (value) {
  37466. this._attachImageProcessingConfiguration(value);
  37467. // Ensure the effect will be rebuilt.
  37468. this._markAllSubMeshesAsTexturesDirty();
  37469. },
  37470. enumerable: true,
  37471. configurable: true
  37472. });
  37473. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  37474. /**
  37475. * Gets wether the color curves effect is enabled.
  37476. */
  37477. get: function () {
  37478. return this.imageProcessingConfiguration.colorCurvesEnabled;
  37479. },
  37480. /**
  37481. * Sets wether the color curves effect is enabled.
  37482. */
  37483. set: function (value) {
  37484. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  37485. },
  37486. enumerable: true,
  37487. configurable: true
  37488. });
  37489. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  37490. /**
  37491. * Gets wether the color grading effect is enabled.
  37492. */
  37493. get: function () {
  37494. return this.imageProcessingConfiguration.colorGradingEnabled;
  37495. },
  37496. /**
  37497. * Gets wether the color grading effect is enabled.
  37498. */
  37499. set: function (value) {
  37500. this.imageProcessingConfiguration.colorGradingEnabled = value;
  37501. },
  37502. enumerable: true,
  37503. configurable: true
  37504. });
  37505. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  37506. /**
  37507. * Gets wether tonemapping is enabled or not.
  37508. */
  37509. get: function () {
  37510. return this._imageProcessingConfiguration.toneMappingEnabled;
  37511. },
  37512. /**
  37513. * Sets wether tonemapping is enabled or not
  37514. */
  37515. set: function (value) {
  37516. this._imageProcessingConfiguration.toneMappingEnabled = value;
  37517. },
  37518. enumerable: true,
  37519. configurable: true
  37520. });
  37521. ;
  37522. ;
  37523. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  37524. /**
  37525. * The camera exposure used on this material.
  37526. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  37527. * This corresponds to a photographic exposure.
  37528. */
  37529. get: function () {
  37530. return this._imageProcessingConfiguration.exposure;
  37531. },
  37532. /**
  37533. * The camera exposure used on this material.
  37534. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  37535. * This corresponds to a photographic exposure.
  37536. */
  37537. set: function (value) {
  37538. this._imageProcessingConfiguration.exposure = value;
  37539. },
  37540. enumerable: true,
  37541. configurable: true
  37542. });
  37543. ;
  37544. ;
  37545. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  37546. /**
  37547. * Gets The camera contrast used on this material.
  37548. */
  37549. get: function () {
  37550. return this._imageProcessingConfiguration.contrast;
  37551. },
  37552. /**
  37553. * Sets The camera contrast used on this material.
  37554. */
  37555. set: function (value) {
  37556. this._imageProcessingConfiguration.contrast = value;
  37557. },
  37558. enumerable: true,
  37559. configurable: true
  37560. });
  37561. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  37562. /**
  37563. * Gets the Color Grading 2D Lookup Texture.
  37564. */
  37565. get: function () {
  37566. return this._imageProcessingConfiguration.colorGradingTexture;
  37567. },
  37568. /**
  37569. * Sets the Color Grading 2D Lookup Texture.
  37570. */
  37571. set: function (value) {
  37572. this._imageProcessingConfiguration.colorGradingTexture = value;
  37573. },
  37574. enumerable: true,
  37575. configurable: true
  37576. });
  37577. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  37578. /**
  37579. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37580. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37581. * 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;
  37582. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37583. */
  37584. get: function () {
  37585. return this._imageProcessingConfiguration.colorCurves;
  37586. },
  37587. /**
  37588. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37589. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37590. * 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;
  37591. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37592. */
  37593. set: function (value) {
  37594. this._imageProcessingConfiguration.colorCurves = value;
  37595. },
  37596. enumerable: true,
  37597. configurable: true
  37598. });
  37599. PBRMaterial.prototype.getClassName = function () {
  37600. return "PBRMaterial";
  37601. };
  37602. PBRMaterial.prototype.getActiveTextures = function () {
  37603. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37604. if (this._albedoTexture) {
  37605. activeTextures.push(this._albedoTexture);
  37606. }
  37607. if (this._ambientTexture) {
  37608. activeTextures.push(this._ambientTexture);
  37609. }
  37610. if (this._opacityTexture) {
  37611. activeTextures.push(this._opacityTexture);
  37612. }
  37613. if (this._reflectionTexture) {
  37614. activeTextures.push(this._reflectionTexture);
  37615. }
  37616. if (this._emissiveTexture) {
  37617. activeTextures.push(this._emissiveTexture);
  37618. }
  37619. if (this._reflectivityTexture) {
  37620. activeTextures.push(this._reflectivityTexture);
  37621. }
  37622. if (this._metallicTexture) {
  37623. activeTextures.push(this._metallicTexture);
  37624. }
  37625. if (this._microSurfaceTexture) {
  37626. activeTextures.push(this._microSurfaceTexture);
  37627. }
  37628. if (this._bumpTexture) {
  37629. activeTextures.push(this._bumpTexture);
  37630. }
  37631. if (this._lightmapTexture) {
  37632. activeTextures.push(this._lightmapTexture);
  37633. }
  37634. if (this._refractionTexture) {
  37635. activeTextures.push(this._refractionTexture);
  37636. }
  37637. return activeTextures;
  37638. };
  37639. PBRMaterial.prototype.hasTexture = function (texture) {
  37640. if (_super.prototype.hasTexture.call(this, texture)) {
  37641. return true;
  37642. }
  37643. if (this._albedoTexture === texture) {
  37644. return true;
  37645. }
  37646. if (this._ambientTexture === texture) {
  37647. return true;
  37648. }
  37649. if (this._opacityTexture === texture) {
  37650. return true;
  37651. }
  37652. if (this._reflectionTexture === texture) {
  37653. return true;
  37654. }
  37655. if (this._reflectivityTexture === texture) {
  37656. return true;
  37657. }
  37658. if (this._metallicTexture === texture) {
  37659. return true;
  37660. }
  37661. if (this._microSurfaceTexture === texture) {
  37662. return true;
  37663. }
  37664. if (this._bumpTexture === texture) {
  37665. return true;
  37666. }
  37667. if (this._lightmapTexture === texture) {
  37668. return true;
  37669. }
  37670. if (this._refractionTexture === texture) {
  37671. return true;
  37672. }
  37673. return false;
  37674. };
  37675. PBRMaterial.prototype.clone = function (name) {
  37676. var _this = this;
  37677. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  37678. clone.id = name;
  37679. clone.name = name;
  37680. return clone;
  37681. };
  37682. PBRMaterial.prototype.serialize = function () {
  37683. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  37684. serializationObject.customType = "BABYLON.PBRMaterial";
  37685. return serializationObject;
  37686. };
  37687. // Statics
  37688. PBRMaterial.Parse = function (source, scene, rootUrl) {
  37689. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  37690. };
  37691. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  37692. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  37693. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  37694. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  37695. __decorate([
  37696. BABYLON.serialize(),
  37697. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37698. ], PBRMaterial.prototype, "directIntensity", void 0);
  37699. __decorate([
  37700. BABYLON.serialize(),
  37701. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37702. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  37703. __decorate([
  37704. BABYLON.serialize(),
  37705. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37706. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  37707. __decorate([
  37708. BABYLON.serialize(),
  37709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37710. ], PBRMaterial.prototype, "specularIntensity", void 0);
  37711. __decorate([
  37712. BABYLON.serialize(),
  37713. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37714. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  37715. __decorate([
  37716. BABYLON.serializeAsTexture(),
  37717. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37718. ], PBRMaterial.prototype, "albedoTexture", void 0);
  37719. __decorate([
  37720. BABYLON.serializeAsTexture(),
  37721. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37722. ], PBRMaterial.prototype, "ambientTexture", void 0);
  37723. __decorate([
  37724. BABYLON.serialize(),
  37725. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37726. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  37727. __decorate([
  37728. BABYLON.serializeAsTexture(),
  37729. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37730. ], PBRMaterial.prototype, "opacityTexture", void 0);
  37731. __decorate([
  37732. BABYLON.serializeAsTexture(),
  37733. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37734. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  37735. __decorate([
  37736. BABYLON.serializeAsTexture(),
  37737. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37738. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  37739. __decorate([
  37740. BABYLON.serializeAsTexture(),
  37741. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37742. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  37743. __decorate([
  37744. BABYLON.serializeAsTexture(),
  37745. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37746. ], PBRMaterial.prototype, "metallicTexture", void 0);
  37747. __decorate([
  37748. BABYLON.serialize(),
  37749. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37750. ], PBRMaterial.prototype, "metallic", void 0);
  37751. __decorate([
  37752. BABYLON.serialize(),
  37753. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37754. ], PBRMaterial.prototype, "roughness", void 0);
  37755. __decorate([
  37756. BABYLON.serializeAsTexture(),
  37757. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37758. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  37759. __decorate([
  37760. BABYLON.serializeAsTexture(),
  37761. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37762. ], PBRMaterial.prototype, "bumpTexture", void 0);
  37763. __decorate([
  37764. BABYLON.serializeAsTexture(),
  37765. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  37766. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  37767. __decorate([
  37768. BABYLON.serializeAsTexture(),
  37769. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37770. ], PBRMaterial.prototype, "refractionTexture", void 0);
  37771. __decorate([
  37772. BABYLON.serializeAsColor3("ambient"),
  37773. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37774. ], PBRMaterial.prototype, "ambientColor", void 0);
  37775. __decorate([
  37776. BABYLON.serializeAsColor3("albedo"),
  37777. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37778. ], PBRMaterial.prototype, "albedoColor", void 0);
  37779. __decorate([
  37780. BABYLON.serializeAsColor3("reflectivity"),
  37781. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37782. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  37783. __decorate([
  37784. BABYLON.serializeAsColor3("reflection"),
  37785. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37786. ], PBRMaterial.prototype, "reflectionColor", void 0);
  37787. __decorate([
  37788. BABYLON.serializeAsColor3("emissive"),
  37789. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37790. ], PBRMaterial.prototype, "emissiveColor", void 0);
  37791. __decorate([
  37792. BABYLON.serialize(),
  37793. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37794. ], PBRMaterial.prototype, "microSurface", void 0);
  37795. __decorate([
  37796. BABYLON.serialize(),
  37797. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37798. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  37799. __decorate([
  37800. BABYLON.serialize(),
  37801. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37802. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  37803. __decorate([
  37804. BABYLON.serialize(),
  37805. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37806. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  37807. __decorate([
  37808. BABYLON.serialize(),
  37809. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37810. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  37811. __decorate([
  37812. BABYLON.serialize(),
  37813. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37814. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  37815. __decorate([
  37816. BABYLON.serialize(),
  37817. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37818. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  37819. __decorate([
  37820. BABYLON.serialize(),
  37821. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37822. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  37823. __decorate([
  37824. BABYLON.serialize(),
  37825. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37826. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  37827. __decorate([
  37828. BABYLON.serialize(),
  37829. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37830. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  37831. __decorate([
  37832. BABYLON.serialize(),
  37833. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37834. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  37835. __decorate([
  37836. BABYLON.serialize(),
  37837. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37838. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  37839. __decorate([
  37840. BABYLON.serialize(),
  37841. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37842. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  37843. __decorate([
  37844. BABYLON.serialize(),
  37845. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37846. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  37847. __decorate([
  37848. BABYLON.serialize(),
  37849. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37850. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  37851. __decorate([
  37852. BABYLON.serialize(),
  37853. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37854. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  37855. __decorate([
  37856. BABYLON.serialize(),
  37857. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37858. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  37859. __decorate([
  37860. BABYLON.serialize(),
  37861. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37862. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  37863. __decorate([
  37864. BABYLON.serialize(),
  37865. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37866. ], PBRMaterial.prototype, "useParallax", void 0);
  37867. __decorate([
  37868. BABYLON.serialize(),
  37869. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37870. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  37871. __decorate([
  37872. BABYLON.serialize(),
  37873. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37874. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  37875. __decorate([
  37876. BABYLON.serialize(),
  37877. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37878. ], PBRMaterial.prototype, "disableLighting", void 0);
  37879. __decorate([
  37880. BABYLON.serialize(),
  37881. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37882. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  37883. __decorate([
  37884. BABYLON.serialize(),
  37885. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37886. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  37887. __decorate([
  37888. BABYLON.serialize(),
  37889. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37890. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  37891. __decorate([
  37892. BABYLON.serialize(),
  37893. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37894. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  37895. __decorate([
  37896. BABYLON.serialize(),
  37897. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37898. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  37899. __decorate([
  37900. BABYLON.serialize(),
  37901. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37902. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  37903. __decorate([
  37904. BABYLON.serialize(),
  37905. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37906. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  37907. __decorate([
  37908. BABYLON.serializeAsTexture(),
  37909. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37910. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  37911. __decorate([
  37912. BABYLON.serialize(),
  37913. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37914. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  37915. __decorate([
  37916. BABYLON.serialize(),
  37917. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37918. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  37919. __decorate([
  37920. BABYLON.serialize(),
  37921. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37922. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  37923. return PBRMaterial;
  37924. }(BABYLON.PBRBaseMaterial));
  37925. BABYLON.PBRMaterial = PBRMaterial;
  37926. })(BABYLON || (BABYLON = {}));
  37927. //# sourceMappingURL=babylon.pbrMaterial.js.map
  37928. var BABYLON;
  37929. (function (BABYLON) {
  37930. /**
  37931. * The PBR material of BJS following the metal roughness convention.
  37932. *
  37933. * This fits to the PBR convention in the GLTF definition:
  37934. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  37935. */
  37936. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  37937. __extends(PBRMetallicRoughnessMaterial, _super);
  37938. /**
  37939. * Instantiates a new PBRMetalRoughnessMaterial instance.
  37940. *
  37941. * @param name The material name
  37942. * @param scene The scene the material will be use in.
  37943. */
  37944. function PBRMetallicRoughnessMaterial(name, scene) {
  37945. var _this = _super.call(this, name, scene) || this;
  37946. _this._useRoughnessFromMetallicTextureAlpha = false;
  37947. _this._useRoughnessFromMetallicTextureGreen = true;
  37948. _this._useMetallnessFromMetallicTextureBlue = true;
  37949. return _this;
  37950. }
  37951. /**
  37952. * Return the currrent class name of the material.
  37953. */
  37954. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  37955. return "PBRMetallicRoughnessMaterial";
  37956. };
  37957. /**
  37958. * Return the active textures of the material.
  37959. */
  37960. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  37961. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37962. if (this.baseTexture) {
  37963. activeTextures.push(this.baseTexture);
  37964. }
  37965. if (this.metallicRoughnessTexture) {
  37966. activeTextures.push(this.metallicRoughnessTexture);
  37967. }
  37968. return activeTextures;
  37969. };
  37970. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  37971. if (_super.prototype.hasTexture.call(this, texture)) {
  37972. return true;
  37973. }
  37974. if (this.baseTexture === texture) {
  37975. return true;
  37976. }
  37977. if (this.metallicRoughnessTexture === texture) {
  37978. return true;
  37979. }
  37980. return false;
  37981. };
  37982. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  37983. var _this = this;
  37984. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  37985. clone.id = name;
  37986. clone.name = name;
  37987. return clone;
  37988. };
  37989. /**
  37990. * Serialize the material to a parsable JSON object.
  37991. */
  37992. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  37993. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  37994. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  37995. return serializationObject;
  37996. };
  37997. /**
  37998. * Parses a JSON object correponding to the serialize function.
  37999. */
  38000. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  38001. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  38002. };
  38003. __decorate([
  38004. BABYLON.serializeAsColor3(),
  38005. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  38006. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  38007. __decorate([
  38008. BABYLON.serializeAsTexture(),
  38009. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  38010. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  38011. __decorate([
  38012. BABYLON.serialize(),
  38013. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38014. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  38015. __decorate([
  38016. BABYLON.serialize(),
  38017. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38018. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  38019. __decorate([
  38020. BABYLON.serializeAsTexture(),
  38021. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  38022. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  38023. return PBRMetallicRoughnessMaterial;
  38024. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  38025. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  38026. })(BABYLON || (BABYLON = {}));
  38027. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  38028. var BABYLON;
  38029. (function (BABYLON) {
  38030. /**
  38031. * The PBR material of BJS following the specular glossiness convention.
  38032. *
  38033. * This fits to the PBR convention in the GLTF definition:
  38034. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  38035. */
  38036. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  38037. __extends(PBRSpecularGlossinessMaterial, _super);
  38038. /**
  38039. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  38040. *
  38041. * @param name The material name
  38042. * @param scene The scene the material will be use in.
  38043. */
  38044. function PBRSpecularGlossinessMaterial(name, scene) {
  38045. var _this = _super.call(this, name, scene) || this;
  38046. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  38047. return _this;
  38048. }
  38049. /**
  38050. * Return the currrent class name of the material.
  38051. */
  38052. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  38053. return "PBRSpecularGlossinessMaterial";
  38054. };
  38055. /**
  38056. * Return the active textures of the material.
  38057. */
  38058. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  38059. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38060. if (this.diffuseTexture) {
  38061. activeTextures.push(this.diffuseTexture);
  38062. }
  38063. if (this.specularGlossinessTexture) {
  38064. activeTextures.push(this.specularGlossinessTexture);
  38065. }
  38066. return activeTextures;
  38067. };
  38068. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  38069. if (_super.prototype.hasTexture.call(this, texture)) {
  38070. return true;
  38071. }
  38072. if (this.diffuseTexture === texture) {
  38073. return true;
  38074. }
  38075. if (this.specularGlossinessTexture === texture) {
  38076. return true;
  38077. }
  38078. return false;
  38079. };
  38080. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  38081. var _this = this;
  38082. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  38083. clone.id = name;
  38084. clone.name = name;
  38085. return clone;
  38086. };
  38087. /**
  38088. * Serialize the material to a parsable JSON object.
  38089. */
  38090. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  38091. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38092. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  38093. return serializationObject;
  38094. };
  38095. /**
  38096. * Parses a JSON object correponding to the serialize function.
  38097. */
  38098. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  38099. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  38100. };
  38101. __decorate([
  38102. BABYLON.serializeAsColor3("diffuse"),
  38103. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  38104. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  38105. __decorate([
  38106. BABYLON.serializeAsTexture(),
  38107. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  38108. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  38109. __decorate([
  38110. BABYLON.serializeAsColor3("specular"),
  38111. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  38112. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  38113. __decorate([
  38114. BABYLON.serialize(),
  38115. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  38116. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  38117. __decorate([
  38118. BABYLON.serializeAsTexture(),
  38119. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  38120. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  38121. return PBRSpecularGlossinessMaterial;
  38122. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  38123. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  38124. })(BABYLON || (BABYLON = {}));
  38125. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  38126. var BABYLON;
  38127. (function (BABYLON) {
  38128. BABYLON.CameraInputTypes = {};
  38129. var CameraInputsManager = /** @class */ (function () {
  38130. function CameraInputsManager(camera) {
  38131. this.attached = {};
  38132. this.camera = camera;
  38133. this.checkInputs = function () { };
  38134. }
  38135. CameraInputsManager.prototype.add = function (input) {
  38136. var type = input.getSimpleName();
  38137. if (this.attached[type]) {
  38138. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  38139. return;
  38140. }
  38141. this.attached[type] = input;
  38142. input.camera = this.camera;
  38143. //for checkInputs, we are dynamically creating a function
  38144. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  38145. if (input.checkInputs) {
  38146. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  38147. }
  38148. if (this.attachedElement) {
  38149. input.attachControl(this.attachedElement);
  38150. }
  38151. };
  38152. CameraInputsManager.prototype.remove = function (inputToRemove) {
  38153. for (var cam in this.attached) {
  38154. var input = this.attached[cam];
  38155. if (input === inputToRemove) {
  38156. input.detachControl(this.attachedElement);
  38157. input.camera = null;
  38158. delete this.attached[cam];
  38159. this.rebuildInputCheck();
  38160. }
  38161. }
  38162. };
  38163. CameraInputsManager.prototype.removeByType = function (inputType) {
  38164. for (var cam in this.attached) {
  38165. var input = this.attached[cam];
  38166. if (input.getClassName() === inputType) {
  38167. input.detachControl(this.attachedElement);
  38168. input.camera = null;
  38169. delete this.attached[cam];
  38170. this.rebuildInputCheck();
  38171. }
  38172. }
  38173. };
  38174. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  38175. var current = this.checkInputs;
  38176. return function () {
  38177. current();
  38178. fn();
  38179. };
  38180. };
  38181. CameraInputsManager.prototype.attachInput = function (input) {
  38182. if (this.attachedElement) {
  38183. input.attachControl(this.attachedElement, this.noPreventDefault);
  38184. }
  38185. };
  38186. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  38187. if (noPreventDefault === void 0) { noPreventDefault = false; }
  38188. if (this.attachedElement) {
  38189. return;
  38190. }
  38191. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  38192. this.attachedElement = element;
  38193. this.noPreventDefault = noPreventDefault;
  38194. for (var cam in this.attached) {
  38195. this.attached[cam].attachControl(element, noPreventDefault);
  38196. }
  38197. };
  38198. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  38199. if (disconnect === void 0) { disconnect = false; }
  38200. if (this.attachedElement !== element) {
  38201. return;
  38202. }
  38203. for (var cam in this.attached) {
  38204. this.attached[cam].detachControl(element);
  38205. if (disconnect) {
  38206. this.attached[cam].camera = null;
  38207. }
  38208. }
  38209. this.attachedElement = null;
  38210. };
  38211. CameraInputsManager.prototype.rebuildInputCheck = function () {
  38212. this.checkInputs = function () { };
  38213. for (var cam in this.attached) {
  38214. var input = this.attached[cam];
  38215. if (input.checkInputs) {
  38216. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  38217. }
  38218. }
  38219. };
  38220. CameraInputsManager.prototype.clear = function () {
  38221. if (this.attachedElement) {
  38222. this.detachElement(this.attachedElement, true);
  38223. }
  38224. this.attached = {};
  38225. this.attachedElement = null;
  38226. this.checkInputs = function () { };
  38227. };
  38228. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  38229. var inputs = {};
  38230. for (var cam in this.attached) {
  38231. var input = this.attached[cam];
  38232. var res = BABYLON.SerializationHelper.Serialize(input);
  38233. inputs[input.getClassName()] = res;
  38234. }
  38235. serializedCamera.inputsmgr = inputs;
  38236. };
  38237. CameraInputsManager.prototype.parse = function (parsedCamera) {
  38238. var parsedInputs = parsedCamera.inputsmgr;
  38239. if (parsedInputs) {
  38240. this.clear();
  38241. for (var n in parsedInputs) {
  38242. var construct = BABYLON.CameraInputTypes[n];
  38243. if (construct) {
  38244. var parsedinput = parsedInputs[n];
  38245. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  38246. this.add(input);
  38247. }
  38248. }
  38249. }
  38250. else {
  38251. //2016-03-08 this part is for managing backward compatibility
  38252. for (var n in this.attached) {
  38253. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  38254. if (construct) {
  38255. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  38256. this.remove(this.attached[n]);
  38257. this.add(input);
  38258. }
  38259. }
  38260. }
  38261. };
  38262. return CameraInputsManager;
  38263. }());
  38264. BABYLON.CameraInputsManager = CameraInputsManager;
  38265. })(BABYLON || (BABYLON = {}));
  38266. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  38267. var BABYLON;
  38268. (function (BABYLON) {
  38269. var FreeCameraMouseInput = /** @class */ (function () {
  38270. function FreeCameraMouseInput(touchEnabled) {
  38271. if (touchEnabled === void 0) { touchEnabled = true; }
  38272. this.touchEnabled = touchEnabled;
  38273. this.buttons = [0, 1, 2];
  38274. this.angularSensibility = 2000.0;
  38275. this.previousPosition = null;
  38276. }
  38277. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  38278. var _this = this;
  38279. var engine = this.camera.getEngine();
  38280. if (!this._pointerInput) {
  38281. this._pointerInput = function (p, s) {
  38282. var evt = p.event;
  38283. if (engine.isInVRExclusivePointerMode) {
  38284. return;
  38285. }
  38286. if (!_this.touchEnabled && evt.pointerType === "touch") {
  38287. return;
  38288. }
  38289. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  38290. return;
  38291. }
  38292. var srcElement = (evt.srcElement || evt.target);
  38293. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  38294. try {
  38295. srcElement.setPointerCapture(evt.pointerId);
  38296. }
  38297. catch (e) {
  38298. //Nothing to do with the error. Execution will continue.
  38299. }
  38300. _this.previousPosition = {
  38301. x: evt.clientX,
  38302. y: evt.clientY
  38303. };
  38304. if (!noPreventDefault) {
  38305. evt.preventDefault();
  38306. element.focus();
  38307. }
  38308. }
  38309. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  38310. try {
  38311. srcElement.releasePointerCapture(evt.pointerId);
  38312. }
  38313. catch (e) {
  38314. //Nothing to do with the error.
  38315. }
  38316. _this.previousPosition = null;
  38317. if (!noPreventDefault) {
  38318. evt.preventDefault();
  38319. }
  38320. }
  38321. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  38322. if (!_this.previousPosition || engine.isPointerLock) {
  38323. return;
  38324. }
  38325. var offsetX = evt.clientX - _this.previousPosition.x;
  38326. var offsetY = evt.clientY - _this.previousPosition.y;
  38327. if (_this.camera.getScene().useRightHandedSystem) {
  38328. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  38329. }
  38330. else {
  38331. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  38332. }
  38333. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  38334. _this.previousPosition = {
  38335. x: evt.clientX,
  38336. y: evt.clientY
  38337. };
  38338. if (!noPreventDefault) {
  38339. evt.preventDefault();
  38340. }
  38341. }
  38342. };
  38343. }
  38344. this._onMouseMove = function (evt) {
  38345. if (!engine.isPointerLock) {
  38346. return;
  38347. }
  38348. if (engine.isInVRExclusivePointerMode) {
  38349. return;
  38350. }
  38351. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  38352. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  38353. if (_this.camera.getScene().useRightHandedSystem) {
  38354. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  38355. }
  38356. else {
  38357. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  38358. }
  38359. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  38360. _this.previousPosition = null;
  38361. if (!noPreventDefault) {
  38362. evt.preventDefault();
  38363. }
  38364. };
  38365. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  38366. element.addEventListener("mousemove", this._onMouseMove, false);
  38367. };
  38368. FreeCameraMouseInput.prototype.detachControl = function (element) {
  38369. if (this._observer && element) {
  38370. this.camera.getScene().onPointerObservable.remove(this._observer);
  38371. if (this._onMouseMove) {
  38372. element.removeEventListener("mousemove", this._onMouseMove);
  38373. }
  38374. this._observer = null;
  38375. this._onMouseMove = null;
  38376. this.previousPosition = null;
  38377. }
  38378. };
  38379. FreeCameraMouseInput.prototype.getClassName = function () {
  38380. return "FreeCameraMouseInput";
  38381. };
  38382. FreeCameraMouseInput.prototype.getSimpleName = function () {
  38383. return "mouse";
  38384. };
  38385. __decorate([
  38386. BABYLON.serialize()
  38387. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  38388. __decorate([
  38389. BABYLON.serialize()
  38390. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  38391. return FreeCameraMouseInput;
  38392. }());
  38393. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  38394. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  38395. })(BABYLON || (BABYLON = {}));
  38396. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  38397. var BABYLON;
  38398. (function (BABYLON) {
  38399. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  38400. function FreeCameraKeyboardMoveInput() {
  38401. this._keys = new Array();
  38402. this.keysUp = [38];
  38403. this.keysDown = [40];
  38404. this.keysLeft = [37];
  38405. this.keysRight = [39];
  38406. }
  38407. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  38408. var _this = this;
  38409. if (this._onCanvasBlurObserver) {
  38410. return;
  38411. }
  38412. this._scene = this.camera.getScene();
  38413. this._engine = this._scene.getEngine();
  38414. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  38415. _this._keys = [];
  38416. });
  38417. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  38418. var evt = info.event;
  38419. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  38420. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  38421. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  38422. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  38423. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  38424. var index = _this._keys.indexOf(evt.keyCode);
  38425. if (index === -1) {
  38426. _this._keys.push(evt.keyCode);
  38427. }
  38428. if (!noPreventDefault) {
  38429. evt.preventDefault();
  38430. }
  38431. }
  38432. }
  38433. else {
  38434. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  38435. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  38436. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  38437. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  38438. var index = _this._keys.indexOf(evt.keyCode);
  38439. if (index >= 0) {
  38440. _this._keys.splice(index, 1);
  38441. }
  38442. if (!noPreventDefault) {
  38443. evt.preventDefault();
  38444. }
  38445. }
  38446. }
  38447. });
  38448. };
  38449. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  38450. if (this._scene) {
  38451. if (this._onKeyboardObserver) {
  38452. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  38453. }
  38454. if (this._onCanvasBlurObserver) {
  38455. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  38456. }
  38457. this._onKeyboardObserver = null;
  38458. this._onCanvasBlurObserver = null;
  38459. }
  38460. this._keys = [];
  38461. };
  38462. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  38463. if (this._onKeyboardObserver) {
  38464. var camera = this.camera;
  38465. // Keyboard
  38466. for (var index = 0; index < this._keys.length; index++) {
  38467. var keyCode = this._keys[index];
  38468. var speed = camera._computeLocalCameraSpeed();
  38469. if (this.keysLeft.indexOf(keyCode) !== -1) {
  38470. camera._localDirection.copyFromFloats(-speed, 0, 0);
  38471. }
  38472. else if (this.keysUp.indexOf(keyCode) !== -1) {
  38473. camera._localDirection.copyFromFloats(0, 0, speed);
  38474. }
  38475. else if (this.keysRight.indexOf(keyCode) !== -1) {
  38476. camera._localDirection.copyFromFloats(speed, 0, 0);
  38477. }
  38478. else if (this.keysDown.indexOf(keyCode) !== -1) {
  38479. camera._localDirection.copyFromFloats(0, 0, -speed);
  38480. }
  38481. if (camera.getScene().useRightHandedSystem) {
  38482. camera._localDirection.z *= -1;
  38483. }
  38484. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  38485. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  38486. camera.cameraDirection.addInPlace(camera._transformedDirection);
  38487. }
  38488. }
  38489. };
  38490. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  38491. return "FreeCameraKeyboardMoveInput";
  38492. };
  38493. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  38494. this._keys = [];
  38495. };
  38496. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  38497. return "keyboard";
  38498. };
  38499. __decorate([
  38500. BABYLON.serialize()
  38501. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  38502. __decorate([
  38503. BABYLON.serialize()
  38504. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  38505. __decorate([
  38506. BABYLON.serialize()
  38507. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  38508. __decorate([
  38509. BABYLON.serialize()
  38510. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  38511. return FreeCameraKeyboardMoveInput;
  38512. }());
  38513. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  38514. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  38515. })(BABYLON || (BABYLON = {}));
  38516. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  38517. var BABYLON;
  38518. (function (BABYLON) {
  38519. var FreeCameraInputsManager = /** @class */ (function (_super) {
  38520. __extends(FreeCameraInputsManager, _super);
  38521. function FreeCameraInputsManager(camera) {
  38522. return _super.call(this, camera) || this;
  38523. }
  38524. FreeCameraInputsManager.prototype.addKeyboard = function () {
  38525. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  38526. return this;
  38527. };
  38528. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  38529. if (touchEnabled === void 0) { touchEnabled = true; }
  38530. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  38531. return this;
  38532. };
  38533. FreeCameraInputsManager.prototype.addGamepad = function () {
  38534. this.add(new BABYLON.FreeCameraGamepadInput());
  38535. return this;
  38536. };
  38537. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  38538. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  38539. return this;
  38540. };
  38541. FreeCameraInputsManager.prototype.addTouch = function () {
  38542. this.add(new BABYLON.FreeCameraTouchInput());
  38543. return this;
  38544. };
  38545. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  38546. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  38547. return this;
  38548. };
  38549. return FreeCameraInputsManager;
  38550. }(BABYLON.CameraInputsManager));
  38551. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  38552. })(BABYLON || (BABYLON = {}));
  38553. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  38554. var BABYLON;
  38555. (function (BABYLON) {
  38556. var TargetCamera = /** @class */ (function (_super) {
  38557. __extends(TargetCamera, _super);
  38558. function TargetCamera(name, position, scene) {
  38559. var _this = _super.call(this, name, position, scene) || this;
  38560. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  38561. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  38562. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  38563. _this.speed = 2.0;
  38564. _this.noRotationConstraint = false;
  38565. _this.lockedTarget = null;
  38566. _this._currentTarget = BABYLON.Vector3.Zero();
  38567. _this._viewMatrix = BABYLON.Matrix.Zero();
  38568. _this._camMatrix = BABYLON.Matrix.Zero();
  38569. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  38570. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  38571. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  38572. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  38573. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  38574. _this._lookAtTemp = BABYLON.Matrix.Zero();
  38575. _this._tempMatrix = BABYLON.Matrix.Zero();
  38576. return _this;
  38577. }
  38578. TargetCamera.prototype.getFrontPosition = function (distance) {
  38579. var direction = this.getTarget().subtract(this.position);
  38580. direction.normalize();
  38581. direction.scaleInPlace(distance);
  38582. return this.globalPosition.add(direction);
  38583. };
  38584. TargetCamera.prototype._getLockedTargetPosition = function () {
  38585. if (!this.lockedTarget) {
  38586. return null;
  38587. }
  38588. if (this.lockedTarget.absolutePosition) {
  38589. this.lockedTarget.computeWorldMatrix();
  38590. }
  38591. return this.lockedTarget.absolutePosition || this.lockedTarget;
  38592. };
  38593. TargetCamera.prototype.storeState = function () {
  38594. this._storedPosition = this.position.clone();
  38595. this._storedRotation = this.rotation.clone();
  38596. if (this.rotationQuaternion) {
  38597. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  38598. }
  38599. return _super.prototype.storeState.call(this);
  38600. };
  38601. /**
  38602. * Restored camera state. You must call storeState() first
  38603. */
  38604. TargetCamera.prototype._restoreStateValues = function () {
  38605. if (!_super.prototype._restoreStateValues.call(this)) {
  38606. return false;
  38607. }
  38608. this.position = this._storedPosition.clone();
  38609. this.rotation = this._storedRotation.clone();
  38610. if (this.rotationQuaternion) {
  38611. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  38612. }
  38613. this.cameraDirection.copyFromFloats(0, 0, 0);
  38614. this.cameraRotation.copyFromFloats(0, 0);
  38615. return true;
  38616. };
  38617. // Cache
  38618. TargetCamera.prototype._initCache = function () {
  38619. _super.prototype._initCache.call(this);
  38620. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38621. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38622. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38623. };
  38624. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  38625. if (!ignoreParentClass) {
  38626. _super.prototype._updateCache.call(this);
  38627. }
  38628. var lockedTargetPosition = this._getLockedTargetPosition();
  38629. if (!lockedTargetPosition) {
  38630. this._cache.lockedTarget = null;
  38631. }
  38632. else {
  38633. if (!this._cache.lockedTarget) {
  38634. this._cache.lockedTarget = lockedTargetPosition.clone();
  38635. }
  38636. else {
  38637. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  38638. }
  38639. }
  38640. this._cache.rotation.copyFrom(this.rotation);
  38641. if (this.rotationQuaternion)
  38642. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  38643. };
  38644. // Synchronized
  38645. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  38646. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  38647. return false;
  38648. }
  38649. var lockedTargetPosition = this._getLockedTargetPosition();
  38650. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  38651. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  38652. };
  38653. // Methods
  38654. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  38655. var engine = this.getEngine();
  38656. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  38657. };
  38658. // Target
  38659. TargetCamera.prototype.setTarget = function (target) {
  38660. this.upVector.normalize();
  38661. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  38662. this._camMatrix.invert();
  38663. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  38664. var vDir = target.subtract(this.position);
  38665. if (vDir.x >= 0.0) {
  38666. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  38667. }
  38668. else {
  38669. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  38670. }
  38671. this.rotation.z = 0;
  38672. if (isNaN(this.rotation.x)) {
  38673. this.rotation.x = 0;
  38674. }
  38675. if (isNaN(this.rotation.y)) {
  38676. this.rotation.y = 0;
  38677. }
  38678. if (isNaN(this.rotation.z)) {
  38679. this.rotation.z = 0;
  38680. }
  38681. if (this.rotationQuaternion) {
  38682. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  38683. }
  38684. };
  38685. /**
  38686. * Return the current target position of the camera. This value is expressed in local space.
  38687. */
  38688. TargetCamera.prototype.getTarget = function () {
  38689. return this._currentTarget;
  38690. };
  38691. TargetCamera.prototype._decideIfNeedsToMove = function () {
  38692. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  38693. };
  38694. TargetCamera.prototype._updatePosition = function () {
  38695. if (this.parent) {
  38696. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  38697. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  38698. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  38699. return;
  38700. }
  38701. this.position.addInPlace(this.cameraDirection);
  38702. };
  38703. TargetCamera.prototype._checkInputs = function () {
  38704. var needToMove = this._decideIfNeedsToMove();
  38705. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  38706. // Move
  38707. if (needToMove) {
  38708. this._updatePosition();
  38709. }
  38710. // Rotate
  38711. if (needToRotate) {
  38712. this.rotation.x += this.cameraRotation.x;
  38713. this.rotation.y += this.cameraRotation.y;
  38714. //rotate, if quaternion is set and rotation was used
  38715. if (this.rotationQuaternion) {
  38716. var len = this.rotation.lengthSquared();
  38717. if (len) {
  38718. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  38719. }
  38720. }
  38721. if (!this.noRotationConstraint) {
  38722. var limit = (Math.PI / 2) * 0.95;
  38723. if (this.rotation.x > limit)
  38724. this.rotation.x = limit;
  38725. if (this.rotation.x < -limit)
  38726. this.rotation.x = -limit;
  38727. }
  38728. }
  38729. // Inertia
  38730. if (needToMove) {
  38731. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  38732. this.cameraDirection.x = 0;
  38733. }
  38734. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  38735. this.cameraDirection.y = 0;
  38736. }
  38737. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  38738. this.cameraDirection.z = 0;
  38739. }
  38740. this.cameraDirection.scaleInPlace(this.inertia);
  38741. }
  38742. if (needToRotate) {
  38743. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  38744. this.cameraRotation.x = 0;
  38745. }
  38746. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  38747. this.cameraRotation.y = 0;
  38748. }
  38749. this.cameraRotation.scaleInPlace(this.inertia);
  38750. }
  38751. _super.prototype._checkInputs.call(this);
  38752. };
  38753. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  38754. if (this.rotationQuaternion) {
  38755. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  38756. }
  38757. else {
  38758. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  38759. }
  38760. //update the up vector!
  38761. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  38762. };
  38763. TargetCamera.prototype._getViewMatrix = function () {
  38764. if (this.lockedTarget) {
  38765. this.setTarget(this._getLockedTargetPosition());
  38766. }
  38767. // Compute
  38768. this._updateCameraRotationMatrix();
  38769. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  38770. // Computing target and final matrix
  38771. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  38772. if (this.getScene().useRightHandedSystem) {
  38773. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  38774. }
  38775. else {
  38776. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  38777. }
  38778. return this._viewMatrix;
  38779. };
  38780. /**
  38781. * @override
  38782. * Override Camera.createRigCamera
  38783. */
  38784. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  38785. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  38786. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  38787. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  38788. if (!this.rotationQuaternion) {
  38789. this.rotationQuaternion = new BABYLON.Quaternion();
  38790. }
  38791. rigCamera._cameraRigParams = {};
  38792. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  38793. }
  38794. return rigCamera;
  38795. }
  38796. return null;
  38797. };
  38798. /**
  38799. * @override
  38800. * Override Camera._updateRigCameras
  38801. */
  38802. TargetCamera.prototype._updateRigCameras = function () {
  38803. var camLeft = this._rigCameras[0];
  38804. var camRight = this._rigCameras[1];
  38805. switch (this.cameraRigMode) {
  38806. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  38807. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  38808. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  38809. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  38810. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  38811. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  38812. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  38813. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  38814. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  38815. camLeft.setTarget(this.getTarget());
  38816. camRight.setTarget(this.getTarget());
  38817. break;
  38818. case BABYLON.Camera.RIG_MODE_VR:
  38819. if (camLeft.rotationQuaternion) {
  38820. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  38821. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  38822. }
  38823. else {
  38824. camLeft.rotation.copyFrom(this.rotation);
  38825. camRight.rotation.copyFrom(this.rotation);
  38826. }
  38827. camLeft.position.copyFrom(this.position);
  38828. camRight.position.copyFrom(this.position);
  38829. break;
  38830. }
  38831. _super.prototype._updateRigCameras.call(this);
  38832. };
  38833. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  38834. if (!this._rigCamTransformMatrix) {
  38835. this._rigCamTransformMatrix = new BABYLON.Matrix();
  38836. }
  38837. var target = this.getTarget();
  38838. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  38839. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  38840. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  38841. };
  38842. TargetCamera.prototype.getClassName = function () {
  38843. return "TargetCamera";
  38844. };
  38845. __decorate([
  38846. BABYLON.serializeAsVector3()
  38847. ], TargetCamera.prototype, "rotation", void 0);
  38848. __decorate([
  38849. BABYLON.serialize()
  38850. ], TargetCamera.prototype, "speed", void 0);
  38851. __decorate([
  38852. BABYLON.serializeAsMeshReference("lockedTargetId")
  38853. ], TargetCamera.prototype, "lockedTarget", void 0);
  38854. return TargetCamera;
  38855. }(BABYLON.Camera));
  38856. BABYLON.TargetCamera = TargetCamera;
  38857. })(BABYLON || (BABYLON = {}));
  38858. //# sourceMappingURL=babylon.targetCamera.js.map
  38859. var BABYLON;
  38860. (function (BABYLON) {
  38861. var FreeCamera = /** @class */ (function (_super) {
  38862. __extends(FreeCamera, _super);
  38863. function FreeCamera(name, position, scene) {
  38864. var _this = _super.call(this, name, position, scene) || this;
  38865. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  38866. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  38867. _this.checkCollisions = false;
  38868. _this.applyGravity = false;
  38869. _this._needMoveForGravity = false;
  38870. _this._oldPosition = BABYLON.Vector3.Zero();
  38871. _this._diffPosition = BABYLON.Vector3.Zero();
  38872. _this._newPosition = BABYLON.Vector3.Zero();
  38873. // Collisions
  38874. _this._collisionMask = -1;
  38875. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  38876. if (collidedMesh === void 0) { collidedMesh = null; }
  38877. //TODO move this to the collision coordinator!
  38878. if (_this.getScene().workerCollisions)
  38879. newPosition.multiplyInPlace(_this._collider._radius);
  38880. var updatePosition = function (newPos) {
  38881. _this._newPosition.copyFrom(newPos);
  38882. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  38883. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  38884. _this.position.addInPlace(_this._diffPosition);
  38885. if (_this.onCollide && collidedMesh) {
  38886. _this.onCollide(collidedMesh);
  38887. }
  38888. }
  38889. };
  38890. updatePosition(newPosition);
  38891. };
  38892. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  38893. _this.inputs.addKeyboard().addMouse();
  38894. return _this;
  38895. }
  38896. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  38897. //-- begin properties for backward compatibility for inputs
  38898. get: function () {
  38899. var mouse = this.inputs.attached["mouse"];
  38900. if (mouse)
  38901. return mouse.angularSensibility;
  38902. return 0;
  38903. },
  38904. set: function (value) {
  38905. var mouse = this.inputs.attached["mouse"];
  38906. if (mouse)
  38907. mouse.angularSensibility = value;
  38908. },
  38909. enumerable: true,
  38910. configurable: true
  38911. });
  38912. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  38913. get: function () {
  38914. var keyboard = this.inputs.attached["keyboard"];
  38915. if (keyboard)
  38916. return keyboard.keysUp;
  38917. return [];
  38918. },
  38919. set: function (value) {
  38920. var keyboard = this.inputs.attached["keyboard"];
  38921. if (keyboard)
  38922. keyboard.keysUp = value;
  38923. },
  38924. enumerable: true,
  38925. configurable: true
  38926. });
  38927. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  38928. get: function () {
  38929. var keyboard = this.inputs.attached["keyboard"];
  38930. if (keyboard)
  38931. return keyboard.keysDown;
  38932. return [];
  38933. },
  38934. set: function (value) {
  38935. var keyboard = this.inputs.attached["keyboard"];
  38936. if (keyboard)
  38937. keyboard.keysDown = value;
  38938. },
  38939. enumerable: true,
  38940. configurable: true
  38941. });
  38942. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  38943. get: function () {
  38944. var keyboard = this.inputs.attached["keyboard"];
  38945. if (keyboard)
  38946. return keyboard.keysLeft;
  38947. return [];
  38948. },
  38949. set: function (value) {
  38950. var keyboard = this.inputs.attached["keyboard"];
  38951. if (keyboard)
  38952. keyboard.keysLeft = value;
  38953. },
  38954. enumerable: true,
  38955. configurable: true
  38956. });
  38957. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  38958. get: function () {
  38959. var keyboard = this.inputs.attached["keyboard"];
  38960. if (keyboard)
  38961. return keyboard.keysRight;
  38962. return [];
  38963. },
  38964. set: function (value) {
  38965. var keyboard = this.inputs.attached["keyboard"];
  38966. if (keyboard)
  38967. keyboard.keysRight = value;
  38968. },
  38969. enumerable: true,
  38970. configurable: true
  38971. });
  38972. // Controls
  38973. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  38974. this.inputs.attachElement(element, noPreventDefault);
  38975. };
  38976. FreeCamera.prototype.detachControl = function (element) {
  38977. this.inputs.detachElement(element);
  38978. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  38979. this.cameraRotation = new BABYLON.Vector2(0, 0);
  38980. };
  38981. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  38982. get: function () {
  38983. return this._collisionMask;
  38984. },
  38985. set: function (mask) {
  38986. this._collisionMask = !isNaN(mask) ? mask : -1;
  38987. },
  38988. enumerable: true,
  38989. configurable: true
  38990. });
  38991. FreeCamera.prototype._collideWithWorld = function (displacement) {
  38992. var globalPosition;
  38993. if (this.parent) {
  38994. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  38995. }
  38996. else {
  38997. globalPosition = this.position;
  38998. }
  38999. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  39000. this._oldPosition.addInPlace(this.ellipsoidOffset);
  39001. if (!this._collider) {
  39002. this._collider = new BABYLON.Collider();
  39003. }
  39004. this._collider._radius = this.ellipsoid;
  39005. this._collider.collisionMask = this._collisionMask;
  39006. //no need for clone, as long as gravity is not on.
  39007. var actualDisplacement = displacement;
  39008. //add gravity to the direction to prevent the dual-collision checking
  39009. if (this.applyGravity) {
  39010. //this prevents mending with cameraDirection, a global variable of the free camera class.
  39011. actualDisplacement = displacement.add(this.getScene().gravity);
  39012. }
  39013. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  39014. };
  39015. FreeCamera.prototype._checkInputs = function () {
  39016. if (!this._localDirection) {
  39017. this._localDirection = BABYLON.Vector3.Zero();
  39018. this._transformedDirection = BABYLON.Vector3.Zero();
  39019. }
  39020. this.inputs.checkInputs();
  39021. _super.prototype._checkInputs.call(this);
  39022. };
  39023. FreeCamera.prototype._decideIfNeedsToMove = function () {
  39024. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  39025. };
  39026. FreeCamera.prototype._updatePosition = function () {
  39027. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  39028. this._collideWithWorld(this.cameraDirection);
  39029. }
  39030. else {
  39031. _super.prototype._updatePosition.call(this);
  39032. }
  39033. };
  39034. FreeCamera.prototype.dispose = function () {
  39035. this.inputs.clear();
  39036. _super.prototype.dispose.call(this);
  39037. };
  39038. FreeCamera.prototype.getClassName = function () {
  39039. return "FreeCamera";
  39040. };
  39041. __decorate([
  39042. BABYLON.serializeAsVector3()
  39043. ], FreeCamera.prototype, "ellipsoid", void 0);
  39044. __decorate([
  39045. BABYLON.serializeAsVector3()
  39046. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  39047. __decorate([
  39048. BABYLON.serialize()
  39049. ], FreeCamera.prototype, "checkCollisions", void 0);
  39050. __decorate([
  39051. BABYLON.serialize()
  39052. ], FreeCamera.prototype, "applyGravity", void 0);
  39053. return FreeCamera;
  39054. }(BABYLON.TargetCamera));
  39055. BABYLON.FreeCamera = FreeCamera;
  39056. })(BABYLON || (BABYLON = {}));
  39057. //# sourceMappingURL=babylon.freeCamera.js.map
  39058. var BABYLON;
  39059. (function (BABYLON) {
  39060. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  39061. function ArcRotateCameraKeyboardMoveInput() {
  39062. this._keys = new Array();
  39063. this.keysUp = [38];
  39064. this.keysDown = [40];
  39065. this.keysLeft = [37];
  39066. this.keysRight = [39];
  39067. this.keysReset = [220];
  39068. this.panningSensibility = 50.0;
  39069. this.zoomingSensibility = 25.0;
  39070. this.useAltToZoom = true;
  39071. }
  39072. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  39073. var _this = this;
  39074. if (this._onCanvasBlurObserver) {
  39075. return;
  39076. }
  39077. this._scene = this.camera.getScene();
  39078. this._engine = this._scene.getEngine();
  39079. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  39080. _this._keys = [];
  39081. });
  39082. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  39083. var evt = info.event;
  39084. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  39085. _this._ctrlPressed = evt.ctrlKey;
  39086. _this._altPressed = evt.altKey;
  39087. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  39088. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  39089. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  39090. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  39091. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  39092. var index = _this._keys.indexOf(evt.keyCode);
  39093. if (index === -1) {
  39094. _this._keys.push(evt.keyCode);
  39095. }
  39096. if (evt.preventDefault) {
  39097. if (!noPreventDefault) {
  39098. evt.preventDefault();
  39099. }
  39100. }
  39101. }
  39102. }
  39103. else {
  39104. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  39105. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  39106. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  39107. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  39108. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  39109. var index = _this._keys.indexOf(evt.keyCode);
  39110. if (index >= 0) {
  39111. _this._keys.splice(index, 1);
  39112. }
  39113. if (evt.preventDefault) {
  39114. if (!noPreventDefault) {
  39115. evt.preventDefault();
  39116. }
  39117. }
  39118. }
  39119. }
  39120. });
  39121. };
  39122. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  39123. if (this._scene) {
  39124. if (this._onKeyboardObserver) {
  39125. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  39126. }
  39127. if (this._onCanvasBlurObserver) {
  39128. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  39129. }
  39130. this._onKeyboardObserver = null;
  39131. this._onCanvasBlurObserver = null;
  39132. }
  39133. this._keys = [];
  39134. };
  39135. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  39136. if (this._onKeyboardObserver) {
  39137. var camera = this.camera;
  39138. for (var index = 0; index < this._keys.length; index++) {
  39139. var keyCode = this._keys[index];
  39140. if (this.keysLeft.indexOf(keyCode) !== -1) {
  39141. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39142. camera.inertialPanningX -= 1 / this.panningSensibility;
  39143. }
  39144. else {
  39145. camera.inertialAlphaOffset -= 0.01;
  39146. }
  39147. }
  39148. else if (this.keysUp.indexOf(keyCode) !== -1) {
  39149. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39150. camera.inertialPanningY += 1 / this.panningSensibility;
  39151. }
  39152. else if (this._altPressed && this.useAltToZoom) {
  39153. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  39154. }
  39155. else {
  39156. camera.inertialBetaOffset -= 0.01;
  39157. }
  39158. }
  39159. else if (this.keysRight.indexOf(keyCode) !== -1) {
  39160. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39161. camera.inertialPanningX += 1 / this.panningSensibility;
  39162. }
  39163. else {
  39164. camera.inertialAlphaOffset += 0.01;
  39165. }
  39166. }
  39167. else if (this.keysDown.indexOf(keyCode) !== -1) {
  39168. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39169. camera.inertialPanningY -= 1 / this.panningSensibility;
  39170. }
  39171. else if (this._altPressed && this.useAltToZoom) {
  39172. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  39173. }
  39174. else {
  39175. camera.inertialBetaOffset += 0.01;
  39176. }
  39177. }
  39178. else if (this.keysReset.indexOf(keyCode) !== -1) {
  39179. camera.restoreState();
  39180. }
  39181. }
  39182. }
  39183. };
  39184. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  39185. return "ArcRotateCameraKeyboardMoveInput";
  39186. };
  39187. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  39188. return "keyboard";
  39189. };
  39190. __decorate([
  39191. BABYLON.serialize()
  39192. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  39193. __decorate([
  39194. BABYLON.serialize()
  39195. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  39196. __decorate([
  39197. BABYLON.serialize()
  39198. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  39199. __decorate([
  39200. BABYLON.serialize()
  39201. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  39202. __decorate([
  39203. BABYLON.serialize()
  39204. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  39205. __decorate([
  39206. BABYLON.serialize()
  39207. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  39208. __decorate([
  39209. BABYLON.serialize()
  39210. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  39211. __decorate([
  39212. BABYLON.serialize()
  39213. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  39214. return ArcRotateCameraKeyboardMoveInput;
  39215. }());
  39216. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  39217. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  39218. })(BABYLON || (BABYLON = {}));
  39219. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  39220. var BABYLON;
  39221. (function (BABYLON) {
  39222. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  39223. function ArcRotateCameraMouseWheelInput() {
  39224. this.wheelPrecision = 3.0;
  39225. /**
  39226. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  39227. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  39228. */
  39229. this.wheelDeltaPercentage = 0;
  39230. }
  39231. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  39232. var _this = this;
  39233. this._wheel = function (p, s) {
  39234. //sanity check - this should be a PointerWheel event.
  39235. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  39236. return;
  39237. var event = p.event;
  39238. var delta = 0;
  39239. if (event.wheelDelta) {
  39240. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  39241. }
  39242. else if (event.detail) {
  39243. delta = -event.detail / _this.wheelPrecision;
  39244. }
  39245. if (delta)
  39246. _this.camera.inertialRadiusOffset += delta;
  39247. if (event.preventDefault) {
  39248. if (!noPreventDefault) {
  39249. event.preventDefault();
  39250. }
  39251. }
  39252. };
  39253. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  39254. };
  39255. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  39256. if (this._observer && element) {
  39257. this.camera.getScene().onPointerObservable.remove(this._observer);
  39258. this._observer = null;
  39259. this._wheel = null;
  39260. }
  39261. };
  39262. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  39263. return "ArcRotateCameraMouseWheelInput";
  39264. };
  39265. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  39266. return "mousewheel";
  39267. };
  39268. __decorate([
  39269. BABYLON.serialize()
  39270. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  39271. __decorate([
  39272. BABYLON.serialize()
  39273. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  39274. return ArcRotateCameraMouseWheelInput;
  39275. }());
  39276. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  39277. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  39278. })(BABYLON || (BABYLON = {}));
  39279. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  39280. var BABYLON;
  39281. (function (BABYLON) {
  39282. var ArcRotateCameraPointersInput = /** @class */ (function () {
  39283. function ArcRotateCameraPointersInput() {
  39284. this.buttons = [0, 1, 2];
  39285. this.angularSensibilityX = 1000.0;
  39286. this.angularSensibilityY = 1000.0;
  39287. this.pinchPrecision = 12.0;
  39288. /**
  39289. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  39290. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  39291. */
  39292. this.pinchDeltaPercentage = 0;
  39293. this.panningSensibility = 1000.0;
  39294. this.multiTouchPanning = true;
  39295. this.multiTouchPanAndZoom = true;
  39296. this._isPanClick = false;
  39297. this.pinchInwards = true;
  39298. }
  39299. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  39300. var _this = this;
  39301. var engine = this.camera.getEngine();
  39302. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  39303. var pointA = null;
  39304. var pointB = null;
  39305. var previousPinchSquaredDistance = 0;
  39306. var initialDistance = 0;
  39307. var twoFingerActivityCount = 0;
  39308. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  39309. this._pointerInput = function (p, s) {
  39310. var evt = p.event;
  39311. var isTouch = p.event.pointerType === "touch";
  39312. if (engine.isInVRExclusivePointerMode) {
  39313. return;
  39314. }
  39315. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  39316. return;
  39317. }
  39318. var srcElement = (evt.srcElement || evt.target);
  39319. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  39320. try {
  39321. srcElement.setPointerCapture(evt.pointerId);
  39322. }
  39323. catch (e) {
  39324. //Nothing to do with the error. Execution will continue.
  39325. }
  39326. // Manage panning with pan button click
  39327. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  39328. // manage pointers
  39329. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  39330. if (pointA === null) {
  39331. pointA = cacheSoloPointer;
  39332. }
  39333. else if (pointB === null) {
  39334. pointB = cacheSoloPointer;
  39335. }
  39336. if (!noPreventDefault) {
  39337. evt.preventDefault();
  39338. element.focus();
  39339. }
  39340. }
  39341. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  39342. _this.camera.restoreState();
  39343. }
  39344. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  39345. try {
  39346. srcElement.releasePointerCapture(evt.pointerId);
  39347. }
  39348. catch (e) {
  39349. //Nothing to do with the error.
  39350. }
  39351. cacheSoloPointer = null;
  39352. previousPinchSquaredDistance = 0;
  39353. previousMultiTouchPanPosition.isPaning = false;
  39354. previousMultiTouchPanPosition.isPinching = false;
  39355. twoFingerActivityCount = 0;
  39356. initialDistance = 0;
  39357. if (!isTouch) {
  39358. pointB = null; // Mouse and pen are mono pointer
  39359. }
  39360. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  39361. //but emptying completly pointers collection is required to fix a bug on iPhone :
  39362. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  39363. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  39364. if (engine.badOS) {
  39365. pointA = pointB = null;
  39366. }
  39367. else {
  39368. //only remove the impacted pointer in case of multitouch allowing on most
  39369. //platforms switching from rotate to zoom and pan seamlessly.
  39370. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  39371. pointA = pointB;
  39372. pointB = null;
  39373. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  39374. }
  39375. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  39376. pointB = null;
  39377. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  39378. }
  39379. else {
  39380. pointA = pointB = null;
  39381. }
  39382. }
  39383. if (!noPreventDefault) {
  39384. evt.preventDefault();
  39385. }
  39386. }
  39387. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  39388. if (!noPreventDefault) {
  39389. evt.preventDefault();
  39390. }
  39391. // One button down
  39392. if (pointA && pointB === null && cacheSoloPointer) {
  39393. if (_this.panningSensibility !== 0 &&
  39394. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  39395. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  39396. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  39397. }
  39398. else {
  39399. var offsetX = evt.clientX - cacheSoloPointer.x;
  39400. var offsetY = evt.clientY - cacheSoloPointer.y;
  39401. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  39402. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  39403. }
  39404. cacheSoloPointer.x = evt.clientX;
  39405. cacheSoloPointer.y = evt.clientY;
  39406. }
  39407. else if (pointA && pointB) {
  39408. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  39409. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  39410. ed.x = evt.clientX;
  39411. ed.y = evt.clientY;
  39412. var direction = _this.pinchInwards ? 1 : -1;
  39413. var distX = pointA.x - pointB.x;
  39414. var distY = pointA.y - pointB.y;
  39415. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  39416. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  39417. if (previousPinchSquaredDistance === 0) {
  39418. initialDistance = pinchDistance;
  39419. previousPinchSquaredDistance = pinchSquaredDistance;
  39420. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  39421. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  39422. return;
  39423. }
  39424. if (_this.multiTouchPanAndZoom) {
  39425. if (_this.pinchDeltaPercentage) {
  39426. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  39427. }
  39428. else {
  39429. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  39430. (_this.pinchPrecision *
  39431. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  39432. direction);
  39433. }
  39434. if (_this.panningSensibility !== 0) {
  39435. var pointersCenterX = (pointA.x + pointB.x) / 2;
  39436. var pointersCenterY = (pointA.y + pointB.y) / 2;
  39437. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  39438. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  39439. previousMultiTouchPanPosition.x = pointersCenterX;
  39440. previousMultiTouchPanPosition.y = pointersCenterY;
  39441. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  39442. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  39443. }
  39444. }
  39445. else {
  39446. twoFingerActivityCount++;
  39447. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  39448. if (_this.pinchDeltaPercentage) {
  39449. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  39450. }
  39451. else {
  39452. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  39453. (_this.pinchPrecision *
  39454. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  39455. direction);
  39456. }
  39457. previousMultiTouchPanPosition.isPaning = false;
  39458. previousMultiTouchPanPosition.isPinching = true;
  39459. }
  39460. else {
  39461. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  39462. if (!previousMultiTouchPanPosition.isPaning) {
  39463. previousMultiTouchPanPosition.isPaning = true;
  39464. previousMultiTouchPanPosition.isPinching = false;
  39465. previousMultiTouchPanPosition.x = ed.x;
  39466. previousMultiTouchPanPosition.y = ed.y;
  39467. return;
  39468. }
  39469. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  39470. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  39471. }
  39472. }
  39473. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  39474. previousMultiTouchPanPosition.x = ed.x;
  39475. previousMultiTouchPanPosition.y = ed.y;
  39476. }
  39477. }
  39478. previousPinchSquaredDistance = pinchSquaredDistance;
  39479. }
  39480. }
  39481. };
  39482. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  39483. this._onContextMenu = function (evt) {
  39484. evt.preventDefault();
  39485. };
  39486. if (!this.camera._useCtrlForPanning) {
  39487. element.addEventListener("contextmenu", this._onContextMenu, false);
  39488. }
  39489. this._onLostFocus = function () {
  39490. //this._keys = [];
  39491. pointA = pointB = null;
  39492. previousPinchSquaredDistance = 0;
  39493. previousMultiTouchPanPosition.isPaning = false;
  39494. previousMultiTouchPanPosition.isPinching = false;
  39495. twoFingerActivityCount = 0;
  39496. cacheSoloPointer = null;
  39497. initialDistance = 0;
  39498. };
  39499. this._onMouseMove = function (evt) {
  39500. if (!engine.isPointerLock) {
  39501. return;
  39502. }
  39503. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  39504. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  39505. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  39506. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  39507. if (!noPreventDefault) {
  39508. evt.preventDefault();
  39509. }
  39510. };
  39511. this._onGestureStart = function (e) {
  39512. if (window.MSGesture === undefined) {
  39513. return;
  39514. }
  39515. if (!_this._MSGestureHandler) {
  39516. _this._MSGestureHandler = new MSGesture();
  39517. _this._MSGestureHandler.target = element;
  39518. }
  39519. _this._MSGestureHandler.addPointer(e.pointerId);
  39520. };
  39521. this._onGesture = function (e) {
  39522. _this.camera.radius *= e.scale;
  39523. if (e.preventDefault) {
  39524. if (!noPreventDefault) {
  39525. e.stopPropagation();
  39526. e.preventDefault();
  39527. }
  39528. }
  39529. };
  39530. element.addEventListener("mousemove", this._onMouseMove, false);
  39531. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  39532. element.addEventListener("MSGestureChange", this._onGesture, false);
  39533. BABYLON.Tools.RegisterTopRootEvents([
  39534. { name: "blur", handler: this._onLostFocus }
  39535. ]);
  39536. };
  39537. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  39538. if (this._onLostFocus) {
  39539. BABYLON.Tools.UnregisterTopRootEvents([
  39540. { name: "blur", handler: this._onLostFocus }
  39541. ]);
  39542. }
  39543. if (element && this._observer) {
  39544. this.camera.getScene().onPointerObservable.remove(this._observer);
  39545. this._observer = null;
  39546. if (this._onContextMenu) {
  39547. element.removeEventListener("contextmenu", this._onContextMenu);
  39548. }
  39549. if (this._onMouseMove) {
  39550. element.removeEventListener("mousemove", this._onMouseMove);
  39551. }
  39552. if (this._onGestureStart) {
  39553. element.removeEventListener("MSPointerDown", this._onGestureStart);
  39554. }
  39555. if (this._onGesture) {
  39556. element.removeEventListener("MSGestureChange", this._onGesture);
  39557. }
  39558. this._isPanClick = false;
  39559. this.pinchInwards = true;
  39560. this._onMouseMove = null;
  39561. this._onGestureStart = null;
  39562. this._onGesture = null;
  39563. this._MSGestureHandler = null;
  39564. this._onLostFocus = null;
  39565. this._onContextMenu = null;
  39566. }
  39567. };
  39568. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  39569. return "ArcRotateCameraPointersInput";
  39570. };
  39571. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  39572. return "pointers";
  39573. };
  39574. __decorate([
  39575. BABYLON.serialize()
  39576. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  39577. __decorate([
  39578. BABYLON.serialize()
  39579. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  39580. __decorate([
  39581. BABYLON.serialize()
  39582. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  39583. __decorate([
  39584. BABYLON.serialize()
  39585. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  39586. __decorate([
  39587. BABYLON.serialize()
  39588. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  39589. __decorate([
  39590. BABYLON.serialize()
  39591. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  39592. __decorate([
  39593. BABYLON.serialize()
  39594. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  39595. __decorate([
  39596. BABYLON.serialize()
  39597. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  39598. return ArcRotateCameraPointersInput;
  39599. }());
  39600. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  39601. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  39602. })(BABYLON || (BABYLON = {}));
  39603. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  39604. var BABYLON;
  39605. (function (BABYLON) {
  39606. var ArcRotateCamera = /** @class */ (function (_super) {
  39607. __extends(ArcRotateCamera, _super);
  39608. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  39609. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  39610. _this.inertialAlphaOffset = 0;
  39611. _this.inertialBetaOffset = 0;
  39612. _this.inertialRadiusOffset = 0;
  39613. _this.lowerAlphaLimit = null;
  39614. _this.upperAlphaLimit = null;
  39615. _this.lowerBetaLimit = 0.01;
  39616. _this.upperBetaLimit = Math.PI;
  39617. _this.lowerRadiusLimit = null;
  39618. _this.upperRadiusLimit = null;
  39619. _this.inertialPanningX = 0;
  39620. _this.inertialPanningY = 0;
  39621. _this.pinchToPanMaxDistance = 20;
  39622. _this.panningDistanceLimit = null;
  39623. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  39624. _this.panningInertia = 0.9;
  39625. //-- end properties for backward compatibility for inputs
  39626. _this.zoomOnFactor = 1;
  39627. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  39628. _this.allowUpsideDown = true;
  39629. _this._viewMatrix = new BABYLON.Matrix();
  39630. // Panning
  39631. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  39632. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  39633. _this.checkCollisions = false;
  39634. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  39635. _this._previousPosition = BABYLON.Vector3.Zero();
  39636. _this._collisionVelocity = BABYLON.Vector3.Zero();
  39637. _this._newPosition = BABYLON.Vector3.Zero();
  39638. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  39639. if (collidedMesh === void 0) { collidedMesh = null; }
  39640. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  39641. newPosition.multiplyInPlace(_this._collider._radius);
  39642. }
  39643. if (!collidedMesh) {
  39644. _this._previousPosition.copyFrom(_this.position);
  39645. }
  39646. else {
  39647. _this.setPosition(newPosition);
  39648. if (_this.onCollide) {
  39649. _this.onCollide(collidedMesh);
  39650. }
  39651. }
  39652. // Recompute because of constraints
  39653. var cosa = Math.cos(_this.alpha);
  39654. var sina = Math.sin(_this.alpha);
  39655. var cosb = Math.cos(_this.beta);
  39656. var sinb = Math.sin(_this.beta);
  39657. if (sinb === 0) {
  39658. sinb = 0.0001;
  39659. }
  39660. var target = _this._getTargetPosition();
  39661. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  39662. _this.position.copyFrom(_this._newPosition);
  39663. var up = _this.upVector;
  39664. if (_this.allowUpsideDown && _this.beta < 0) {
  39665. up = up.clone();
  39666. up = up.negate();
  39667. }
  39668. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  39669. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  39670. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  39671. _this._collisionTriggered = false;
  39672. };
  39673. _this._target = BABYLON.Vector3.Zero();
  39674. if (target) {
  39675. _this.setTarget(target);
  39676. }
  39677. _this.alpha = alpha;
  39678. _this.beta = beta;
  39679. _this.radius = radius;
  39680. _this.getViewMatrix();
  39681. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  39682. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  39683. return _this;
  39684. }
  39685. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  39686. get: function () {
  39687. return this._target;
  39688. },
  39689. set: function (value) {
  39690. this.setTarget(value);
  39691. },
  39692. enumerable: true,
  39693. configurable: true
  39694. });
  39695. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  39696. //-- begin properties for backward compatibility for inputs
  39697. get: function () {
  39698. var pointers = this.inputs.attached["pointers"];
  39699. if (pointers)
  39700. return pointers.angularSensibilityX;
  39701. return 0;
  39702. },
  39703. set: function (value) {
  39704. var pointers = this.inputs.attached["pointers"];
  39705. if (pointers) {
  39706. pointers.angularSensibilityX = value;
  39707. }
  39708. },
  39709. enumerable: true,
  39710. configurable: true
  39711. });
  39712. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  39713. get: function () {
  39714. var pointers = this.inputs.attached["pointers"];
  39715. if (pointers)
  39716. return pointers.angularSensibilityY;
  39717. return 0;
  39718. },
  39719. set: function (value) {
  39720. var pointers = this.inputs.attached["pointers"];
  39721. if (pointers) {
  39722. pointers.angularSensibilityY = value;
  39723. }
  39724. },
  39725. enumerable: true,
  39726. configurable: true
  39727. });
  39728. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  39729. get: function () {
  39730. var pointers = this.inputs.attached["pointers"];
  39731. if (pointers)
  39732. return pointers.pinchPrecision;
  39733. return 0;
  39734. },
  39735. set: function (value) {
  39736. var pointers = this.inputs.attached["pointers"];
  39737. if (pointers) {
  39738. pointers.pinchPrecision = value;
  39739. }
  39740. },
  39741. enumerable: true,
  39742. configurable: true
  39743. });
  39744. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  39745. get: function () {
  39746. var pointers = this.inputs.attached["pointers"];
  39747. if (pointers)
  39748. return pointers.pinchDeltaPercentage;
  39749. return 0;
  39750. },
  39751. set: function (value) {
  39752. var pointers = this.inputs.attached["pointers"];
  39753. if (pointers) {
  39754. pointers.pinchDeltaPercentage = value;
  39755. }
  39756. },
  39757. enumerable: true,
  39758. configurable: true
  39759. });
  39760. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  39761. get: function () {
  39762. var pointers = this.inputs.attached["pointers"];
  39763. if (pointers)
  39764. return pointers.panningSensibility;
  39765. return 0;
  39766. },
  39767. set: function (value) {
  39768. var pointers = this.inputs.attached["pointers"];
  39769. if (pointers) {
  39770. pointers.panningSensibility = value;
  39771. }
  39772. },
  39773. enumerable: true,
  39774. configurable: true
  39775. });
  39776. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  39777. get: function () {
  39778. var keyboard = this.inputs.attached["keyboard"];
  39779. if (keyboard)
  39780. return keyboard.keysUp;
  39781. return [];
  39782. },
  39783. set: function (value) {
  39784. var keyboard = this.inputs.attached["keyboard"];
  39785. if (keyboard)
  39786. keyboard.keysUp = value;
  39787. },
  39788. enumerable: true,
  39789. configurable: true
  39790. });
  39791. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  39792. get: function () {
  39793. var keyboard = this.inputs.attached["keyboard"];
  39794. if (keyboard)
  39795. return keyboard.keysDown;
  39796. return [];
  39797. },
  39798. set: function (value) {
  39799. var keyboard = this.inputs.attached["keyboard"];
  39800. if (keyboard)
  39801. keyboard.keysDown = value;
  39802. },
  39803. enumerable: true,
  39804. configurable: true
  39805. });
  39806. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  39807. get: function () {
  39808. var keyboard = this.inputs.attached["keyboard"];
  39809. if (keyboard)
  39810. return keyboard.keysLeft;
  39811. return [];
  39812. },
  39813. set: function (value) {
  39814. var keyboard = this.inputs.attached["keyboard"];
  39815. if (keyboard)
  39816. keyboard.keysLeft = value;
  39817. },
  39818. enumerable: true,
  39819. configurable: true
  39820. });
  39821. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  39822. get: function () {
  39823. var keyboard = this.inputs.attached["keyboard"];
  39824. if (keyboard)
  39825. return keyboard.keysRight;
  39826. return [];
  39827. },
  39828. set: function (value) {
  39829. var keyboard = this.inputs.attached["keyboard"];
  39830. if (keyboard)
  39831. keyboard.keysRight = value;
  39832. },
  39833. enumerable: true,
  39834. configurable: true
  39835. });
  39836. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  39837. get: function () {
  39838. var mousewheel = this.inputs.attached["mousewheel"];
  39839. if (mousewheel)
  39840. return mousewheel.wheelPrecision;
  39841. return 0;
  39842. },
  39843. set: function (value) {
  39844. var mousewheel = this.inputs.attached["mousewheel"];
  39845. if (mousewheel)
  39846. mousewheel.wheelPrecision = value;
  39847. },
  39848. enumerable: true,
  39849. configurable: true
  39850. });
  39851. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  39852. get: function () {
  39853. var mousewheel = this.inputs.attached["mousewheel"];
  39854. if (mousewheel)
  39855. return mousewheel.wheelDeltaPercentage;
  39856. return 0;
  39857. },
  39858. set: function (value) {
  39859. var mousewheel = this.inputs.attached["mousewheel"];
  39860. if (mousewheel)
  39861. mousewheel.wheelDeltaPercentage = value;
  39862. },
  39863. enumerable: true,
  39864. configurable: true
  39865. });
  39866. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  39867. get: function () {
  39868. return this._bouncingBehavior;
  39869. },
  39870. enumerable: true,
  39871. configurable: true
  39872. });
  39873. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  39874. get: function () {
  39875. return this._bouncingBehavior != null;
  39876. },
  39877. set: function (value) {
  39878. if (value === this.useBouncingBehavior) {
  39879. return;
  39880. }
  39881. if (value) {
  39882. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  39883. this.addBehavior(this._bouncingBehavior);
  39884. }
  39885. else if (this._bouncingBehavior) {
  39886. this.removeBehavior(this._bouncingBehavior);
  39887. this._bouncingBehavior = null;
  39888. }
  39889. },
  39890. enumerable: true,
  39891. configurable: true
  39892. });
  39893. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  39894. get: function () {
  39895. return this._framingBehavior;
  39896. },
  39897. enumerable: true,
  39898. configurable: true
  39899. });
  39900. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  39901. get: function () {
  39902. return this._framingBehavior != null;
  39903. },
  39904. set: function (value) {
  39905. if (value === this.useFramingBehavior) {
  39906. return;
  39907. }
  39908. if (value) {
  39909. this._framingBehavior = new BABYLON.FramingBehavior();
  39910. this.addBehavior(this._framingBehavior);
  39911. }
  39912. else if (this._framingBehavior) {
  39913. this.removeBehavior(this._framingBehavior);
  39914. this._framingBehavior = null;
  39915. }
  39916. },
  39917. enumerable: true,
  39918. configurable: true
  39919. });
  39920. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  39921. get: function () {
  39922. return this._autoRotationBehavior;
  39923. },
  39924. enumerable: true,
  39925. configurable: true
  39926. });
  39927. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  39928. get: function () {
  39929. return this._autoRotationBehavior != null;
  39930. },
  39931. set: function (value) {
  39932. if (value === this.useAutoRotationBehavior) {
  39933. return;
  39934. }
  39935. if (value) {
  39936. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  39937. this.addBehavior(this._autoRotationBehavior);
  39938. }
  39939. else if (this._autoRotationBehavior) {
  39940. this.removeBehavior(this._autoRotationBehavior);
  39941. this._autoRotationBehavior = null;
  39942. }
  39943. },
  39944. enumerable: true,
  39945. configurable: true
  39946. });
  39947. // Cache
  39948. ArcRotateCamera.prototype._initCache = function () {
  39949. _super.prototype._initCache.call(this);
  39950. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  39951. this._cache.alpha = undefined;
  39952. this._cache.beta = undefined;
  39953. this._cache.radius = undefined;
  39954. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  39955. };
  39956. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  39957. if (!ignoreParentClass) {
  39958. _super.prototype._updateCache.call(this);
  39959. }
  39960. this._cache._target.copyFrom(this._getTargetPosition());
  39961. this._cache.alpha = this.alpha;
  39962. this._cache.beta = this.beta;
  39963. this._cache.radius = this.radius;
  39964. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  39965. };
  39966. ArcRotateCamera.prototype._getTargetPosition = function () {
  39967. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  39968. var pos = this._targetHost.getAbsolutePosition();
  39969. if (this._targetBoundingCenter) {
  39970. pos.addToRef(this._targetBoundingCenter, this._target);
  39971. }
  39972. else {
  39973. this._target.copyFrom(pos);
  39974. }
  39975. }
  39976. var lockedTargetPosition = this._getLockedTargetPosition();
  39977. if (lockedTargetPosition) {
  39978. return lockedTargetPosition;
  39979. }
  39980. return this._target;
  39981. };
  39982. ArcRotateCamera.prototype.storeState = function () {
  39983. this._storedAlpha = this.alpha;
  39984. this._storedBeta = this.beta;
  39985. this._storedRadius = this.radius;
  39986. this._storedTarget = this._getTargetPosition().clone();
  39987. return _super.prototype.storeState.call(this);
  39988. };
  39989. /**
  39990. * Restored camera state. You must call storeState() first
  39991. */
  39992. ArcRotateCamera.prototype._restoreStateValues = function () {
  39993. if (!_super.prototype._restoreStateValues.call(this)) {
  39994. return false;
  39995. }
  39996. this.alpha = this._storedAlpha;
  39997. this.beta = this._storedBeta;
  39998. this.radius = this._storedRadius;
  39999. this.setTarget(this._storedTarget.clone());
  40000. this.inertialAlphaOffset = 0;
  40001. this.inertialBetaOffset = 0;
  40002. this.inertialRadiusOffset = 0;
  40003. this.inertialPanningX = 0;
  40004. this.inertialPanningY = 0;
  40005. return true;
  40006. };
  40007. // Synchronized
  40008. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  40009. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  40010. return false;
  40011. return this._cache._target.equals(this._getTargetPosition())
  40012. && this._cache.alpha === this.alpha
  40013. && this._cache.beta === this.beta
  40014. && this._cache.radius === this.radius
  40015. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  40016. };
  40017. // Methods
  40018. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  40019. var _this = this;
  40020. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  40021. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  40022. this._useCtrlForPanning = useCtrlForPanning;
  40023. this._panningMouseButton = panningMouseButton;
  40024. this.inputs.attachElement(element, noPreventDefault);
  40025. this._reset = function () {
  40026. _this.inertialAlphaOffset = 0;
  40027. _this.inertialBetaOffset = 0;
  40028. _this.inertialRadiusOffset = 0;
  40029. _this.inertialPanningX = 0;
  40030. _this.inertialPanningY = 0;
  40031. };
  40032. };
  40033. ArcRotateCamera.prototype.detachControl = function (element) {
  40034. this.inputs.detachElement(element);
  40035. if (this._reset) {
  40036. this._reset();
  40037. }
  40038. };
  40039. ArcRotateCamera.prototype._checkInputs = function () {
  40040. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  40041. if (this._collisionTriggered) {
  40042. return;
  40043. }
  40044. this.inputs.checkInputs();
  40045. // Inertia
  40046. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  40047. if (this.getScene().useRightHandedSystem) {
  40048. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  40049. }
  40050. else {
  40051. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  40052. }
  40053. this.beta += this.inertialBetaOffset;
  40054. this.radius -= this.inertialRadiusOffset;
  40055. this.inertialAlphaOffset *= this.inertia;
  40056. this.inertialBetaOffset *= this.inertia;
  40057. this.inertialRadiusOffset *= this.inertia;
  40058. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  40059. this.inertialAlphaOffset = 0;
  40060. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  40061. this.inertialBetaOffset = 0;
  40062. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  40063. this.inertialRadiusOffset = 0;
  40064. }
  40065. // Panning inertia
  40066. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  40067. if (!this._localDirection) {
  40068. this._localDirection = BABYLON.Vector3.Zero();
  40069. this._transformedDirection = BABYLON.Vector3.Zero();
  40070. }
  40071. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  40072. this._localDirection.multiplyInPlace(this.panningAxis);
  40073. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  40074. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  40075. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  40076. if (!this.panningAxis.y) {
  40077. this._transformedDirection.y = 0;
  40078. }
  40079. if (!this._targetHost) {
  40080. if (this.panningDistanceLimit) {
  40081. this._transformedDirection.addInPlace(this._target);
  40082. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  40083. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  40084. this._target.copyFrom(this._transformedDirection);
  40085. }
  40086. }
  40087. else {
  40088. this._target.addInPlace(this._transformedDirection);
  40089. }
  40090. }
  40091. this.inertialPanningX *= this.panningInertia;
  40092. this.inertialPanningY *= this.panningInertia;
  40093. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  40094. this.inertialPanningX = 0;
  40095. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  40096. this.inertialPanningY = 0;
  40097. }
  40098. // Limits
  40099. this._checkLimits();
  40100. _super.prototype._checkInputs.call(this);
  40101. };
  40102. ArcRotateCamera.prototype._checkLimits = function () {
  40103. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  40104. if (this.allowUpsideDown && this.beta > Math.PI) {
  40105. this.beta = this.beta - (2 * Math.PI);
  40106. }
  40107. }
  40108. else {
  40109. if (this.beta < this.lowerBetaLimit) {
  40110. this.beta = this.lowerBetaLimit;
  40111. }
  40112. }
  40113. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  40114. if (this.allowUpsideDown && this.beta < -Math.PI) {
  40115. this.beta = this.beta + (2 * Math.PI);
  40116. }
  40117. }
  40118. else {
  40119. if (this.beta > this.upperBetaLimit) {
  40120. this.beta = this.upperBetaLimit;
  40121. }
  40122. }
  40123. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  40124. this.alpha = this.lowerAlphaLimit;
  40125. }
  40126. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  40127. this.alpha = this.upperAlphaLimit;
  40128. }
  40129. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  40130. this.radius = this.lowerRadiusLimit;
  40131. }
  40132. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  40133. this.radius = this.upperRadiusLimit;
  40134. }
  40135. };
  40136. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  40137. var radiusv3 = this.position.subtract(this._getTargetPosition());
  40138. this.radius = radiusv3.length();
  40139. if (this.radius === 0) {
  40140. this.radius = 0.0001; // Just to avoid division by zero
  40141. }
  40142. // Alpha
  40143. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  40144. if (radiusv3.z < 0) {
  40145. this.alpha = 2 * Math.PI - this.alpha;
  40146. }
  40147. // Beta
  40148. this.beta = Math.acos(radiusv3.y / this.radius);
  40149. this._checkLimits();
  40150. };
  40151. ArcRotateCamera.prototype.setPosition = function (position) {
  40152. if (this.position.equals(position)) {
  40153. return;
  40154. }
  40155. this.position.copyFrom(position);
  40156. this.rebuildAnglesAndRadius();
  40157. };
  40158. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  40159. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  40160. if (allowSamePosition === void 0) { allowSamePosition = false; }
  40161. if (target.getBoundingInfo) {
  40162. if (toBoundingCenter) {
  40163. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  40164. }
  40165. else {
  40166. this._targetBoundingCenter = null;
  40167. }
  40168. this._targetHost = target;
  40169. this._target = this._getTargetPosition();
  40170. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  40171. }
  40172. else {
  40173. var newTarget = target;
  40174. var currentTarget = this._getTargetPosition();
  40175. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  40176. return;
  40177. }
  40178. this._targetHost = null;
  40179. this._target = newTarget;
  40180. this._targetBoundingCenter = null;
  40181. this.onMeshTargetChangedObservable.notifyObservers(null);
  40182. }
  40183. this.rebuildAnglesAndRadius();
  40184. };
  40185. ArcRotateCamera.prototype._getViewMatrix = function () {
  40186. // Compute
  40187. var cosa = Math.cos(this.alpha);
  40188. var sina = Math.sin(this.alpha);
  40189. var cosb = Math.cos(this.beta);
  40190. var sinb = Math.sin(this.beta);
  40191. if (sinb === 0) {
  40192. sinb = 0.0001;
  40193. }
  40194. var target = this._getTargetPosition();
  40195. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  40196. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  40197. if (!this._collider) {
  40198. this._collider = new BABYLON.Collider();
  40199. }
  40200. this._collider._radius = this.collisionRadius;
  40201. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  40202. this._collisionTriggered = true;
  40203. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  40204. }
  40205. else {
  40206. this.position.copyFrom(this._newPosition);
  40207. var up = this.upVector;
  40208. if (this.allowUpsideDown && sinb < 0) {
  40209. up = up.clone();
  40210. up = up.negate();
  40211. }
  40212. if (this.getScene().useRightHandedSystem) {
  40213. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  40214. }
  40215. else {
  40216. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  40217. }
  40218. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  40219. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  40220. }
  40221. this._currentTarget = target;
  40222. return this._viewMatrix;
  40223. };
  40224. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  40225. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  40226. meshes = meshes || this.getScene().meshes;
  40227. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  40228. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  40229. this.radius = distance * this.zoomOnFactor;
  40230. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  40231. };
  40232. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  40233. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  40234. var meshesOrMinMaxVector;
  40235. var distance;
  40236. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  40237. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  40238. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  40239. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  40240. }
  40241. else {
  40242. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  40243. meshesOrMinMaxVector = minMaxVectorAndDistance;
  40244. distance = minMaxVectorAndDistance.distance;
  40245. }
  40246. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  40247. if (!doNotUpdateMaxZ) {
  40248. this.maxZ = distance * 2;
  40249. }
  40250. };
  40251. /**
  40252. * @override
  40253. * Override Camera.createRigCamera
  40254. */
  40255. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  40256. var alphaShift = 0;
  40257. switch (this.cameraRigMode) {
  40258. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  40259. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  40260. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  40261. case BABYLON.Camera.RIG_MODE_VR:
  40262. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  40263. break;
  40264. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  40265. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  40266. break;
  40267. }
  40268. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  40269. rigCam._cameraRigParams = {};
  40270. return rigCam;
  40271. };
  40272. /**
  40273. * @override
  40274. * Override Camera._updateRigCameras
  40275. */
  40276. ArcRotateCamera.prototype._updateRigCameras = function () {
  40277. var camLeft = this._rigCameras[0];
  40278. var camRight = this._rigCameras[1];
  40279. camLeft.beta = camRight.beta = this.beta;
  40280. camLeft.radius = camRight.radius = this.radius;
  40281. switch (this.cameraRigMode) {
  40282. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  40283. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  40284. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  40285. case BABYLON.Camera.RIG_MODE_VR:
  40286. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  40287. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  40288. break;
  40289. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  40290. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  40291. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  40292. break;
  40293. }
  40294. _super.prototype._updateRigCameras.call(this);
  40295. };
  40296. ArcRotateCamera.prototype.dispose = function () {
  40297. this.inputs.clear();
  40298. _super.prototype.dispose.call(this);
  40299. };
  40300. ArcRotateCamera.prototype.getClassName = function () {
  40301. return "ArcRotateCamera";
  40302. };
  40303. __decorate([
  40304. BABYLON.serialize()
  40305. ], ArcRotateCamera.prototype, "alpha", void 0);
  40306. __decorate([
  40307. BABYLON.serialize()
  40308. ], ArcRotateCamera.prototype, "beta", void 0);
  40309. __decorate([
  40310. BABYLON.serialize()
  40311. ], ArcRotateCamera.prototype, "radius", void 0);
  40312. __decorate([
  40313. BABYLON.serializeAsVector3("target")
  40314. ], ArcRotateCamera.prototype, "_target", void 0);
  40315. __decorate([
  40316. BABYLON.serialize()
  40317. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  40318. __decorate([
  40319. BABYLON.serialize()
  40320. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  40321. __decorate([
  40322. BABYLON.serialize()
  40323. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  40324. __decorate([
  40325. BABYLON.serialize()
  40326. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  40327. __decorate([
  40328. BABYLON.serialize()
  40329. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  40330. __decorate([
  40331. BABYLON.serialize()
  40332. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  40333. __decorate([
  40334. BABYLON.serialize()
  40335. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  40336. __decorate([
  40337. BABYLON.serialize()
  40338. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  40339. __decorate([
  40340. BABYLON.serialize()
  40341. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  40342. __decorate([
  40343. BABYLON.serialize()
  40344. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  40345. __decorate([
  40346. BABYLON.serialize()
  40347. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  40348. __decorate([
  40349. BABYLON.serialize()
  40350. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  40351. __decorate([
  40352. BABYLON.serialize()
  40353. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  40354. __decorate([
  40355. BABYLON.serializeAsVector3()
  40356. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  40357. __decorate([
  40358. BABYLON.serialize()
  40359. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  40360. __decorate([
  40361. BABYLON.serialize()
  40362. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  40363. __decorate([
  40364. BABYLON.serialize()
  40365. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  40366. return ArcRotateCamera;
  40367. }(BABYLON.TargetCamera));
  40368. BABYLON.ArcRotateCamera = ArcRotateCamera;
  40369. })(BABYLON || (BABYLON = {}));
  40370. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  40371. var BABYLON;
  40372. (function (BABYLON) {
  40373. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  40374. __extends(ArcRotateCameraInputsManager, _super);
  40375. function ArcRotateCameraInputsManager(camera) {
  40376. return _super.call(this, camera) || this;
  40377. }
  40378. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  40379. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  40380. return this;
  40381. };
  40382. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  40383. this.add(new BABYLON.ArcRotateCameraPointersInput());
  40384. return this;
  40385. };
  40386. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  40387. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  40388. return this;
  40389. };
  40390. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  40391. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  40392. return this;
  40393. };
  40394. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  40395. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  40396. return this;
  40397. };
  40398. return ArcRotateCameraInputsManager;
  40399. }(BABYLON.CameraInputsManager));
  40400. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  40401. })(BABYLON || (BABYLON = {}));
  40402. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  40403. var BABYLON;
  40404. (function (BABYLON) {
  40405. var HemisphericLight = /** @class */ (function (_super) {
  40406. __extends(HemisphericLight, _super);
  40407. /**
  40408. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  40409. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  40410. * The HemisphericLight can't cast shadows.
  40411. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40412. */
  40413. function HemisphericLight(name, direction, scene) {
  40414. var _this = _super.call(this, name, scene) || this;
  40415. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  40416. _this.direction = direction || BABYLON.Vector3.Up();
  40417. return _this;
  40418. }
  40419. HemisphericLight.prototype._buildUniformLayout = function () {
  40420. this._uniformBuffer.addUniform("vLightData", 4);
  40421. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40422. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40423. this._uniformBuffer.addUniform("vLightGround", 3);
  40424. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40425. this._uniformBuffer.addUniform("depthValues", 2);
  40426. this._uniformBuffer.create();
  40427. };
  40428. /**
  40429. * Returns the string "HemisphericLight".
  40430. */
  40431. HemisphericLight.prototype.getClassName = function () {
  40432. return "HemisphericLight";
  40433. };
  40434. /**
  40435. * Sets the HemisphericLight direction towards the passed target (Vector3).
  40436. * Returns the updated direction.
  40437. */
  40438. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  40439. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  40440. return this.direction;
  40441. };
  40442. HemisphericLight.prototype.getShadowGenerator = function () {
  40443. return null;
  40444. };
  40445. /**
  40446. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  40447. * Returns the HemisphericLight.
  40448. */
  40449. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  40450. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  40451. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  40452. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  40453. return this;
  40454. };
  40455. HemisphericLight.prototype._getWorldMatrix = function () {
  40456. if (!this._worldMatrix) {
  40457. this._worldMatrix = BABYLON.Matrix.Identity();
  40458. }
  40459. return this._worldMatrix;
  40460. };
  40461. /**
  40462. * Returns the integer 3.
  40463. */
  40464. HemisphericLight.prototype.getTypeID = function () {
  40465. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  40466. };
  40467. __decorate([
  40468. BABYLON.serializeAsColor3()
  40469. ], HemisphericLight.prototype, "groundColor", void 0);
  40470. __decorate([
  40471. BABYLON.serializeAsVector3()
  40472. ], HemisphericLight.prototype, "direction", void 0);
  40473. return HemisphericLight;
  40474. }(BABYLON.Light));
  40475. BABYLON.HemisphericLight = HemisphericLight;
  40476. })(BABYLON || (BABYLON = {}));
  40477. //# sourceMappingURL=babylon.hemisphericLight.js.map
  40478. var BABYLON;
  40479. (function (BABYLON) {
  40480. var ShadowLight = /** @class */ (function (_super) {
  40481. __extends(ShadowLight, _super);
  40482. function ShadowLight() {
  40483. var _this = _super !== null && _super.apply(this, arguments) || this;
  40484. _this._needProjectionMatrixCompute = true;
  40485. return _this;
  40486. }
  40487. Object.defineProperty(ShadowLight.prototype, "direction", {
  40488. get: function () {
  40489. return this._direction;
  40490. },
  40491. set: function (value) {
  40492. this._direction = value;
  40493. },
  40494. enumerable: true,
  40495. configurable: true
  40496. });
  40497. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  40498. get: function () {
  40499. return this._shadowMinZ;
  40500. },
  40501. set: function (value) {
  40502. this._shadowMinZ = value;
  40503. this.forceProjectionMatrixCompute();
  40504. },
  40505. enumerable: true,
  40506. configurable: true
  40507. });
  40508. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  40509. get: function () {
  40510. return this._shadowMaxZ;
  40511. },
  40512. set: function (value) {
  40513. this._shadowMaxZ = value;
  40514. this.forceProjectionMatrixCompute();
  40515. },
  40516. enumerable: true,
  40517. configurable: true
  40518. });
  40519. /**
  40520. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  40521. */
  40522. ShadowLight.prototype.computeTransformedInformation = function () {
  40523. if (this.parent && this.parent.getWorldMatrix) {
  40524. if (!this.transformedPosition) {
  40525. this.transformedPosition = BABYLON.Vector3.Zero();
  40526. }
  40527. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  40528. // In case the direction is present.
  40529. if (this.direction) {
  40530. if (!this.transformedDirection) {
  40531. this.transformedDirection = BABYLON.Vector3.Zero();
  40532. }
  40533. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  40534. }
  40535. return true;
  40536. }
  40537. return false;
  40538. };
  40539. /**
  40540. * Return the depth scale used for the shadow map.
  40541. */
  40542. ShadowLight.prototype.getDepthScale = function () {
  40543. return 50.0;
  40544. };
  40545. /**
  40546. * Returns the light direction (Vector3) for any passed face index.
  40547. */
  40548. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  40549. return this.transformedDirection ? this.transformedDirection : this.direction;
  40550. };
  40551. /**
  40552. * Returns the DirectionalLight absolute position in the World.
  40553. */
  40554. ShadowLight.prototype.getAbsolutePosition = function () {
  40555. return this.transformedPosition ? this.transformedPosition : this.position;
  40556. };
  40557. /**
  40558. * Sets the DirectionalLight direction toward the passed target (Vector3).
  40559. * Returns the updated DirectionalLight direction (Vector3).
  40560. */
  40561. ShadowLight.prototype.setDirectionToTarget = function (target) {
  40562. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  40563. return this.direction;
  40564. };
  40565. /**
  40566. * Returns the light rotation (Vector3).
  40567. */
  40568. ShadowLight.prototype.getRotation = function () {
  40569. this.direction.normalize();
  40570. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  40571. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  40572. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  40573. };
  40574. /**
  40575. * Boolean : false by default.
  40576. */
  40577. ShadowLight.prototype.needCube = function () {
  40578. return false;
  40579. };
  40580. /**
  40581. * Specifies wether or not the projection matrix should be recomputed this frame.
  40582. */
  40583. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  40584. return this._needProjectionMatrixCompute;
  40585. };
  40586. /**
  40587. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  40588. */
  40589. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  40590. this._needProjectionMatrixCompute = true;
  40591. };
  40592. /**
  40593. * Get the world matrix of the sahdow lights.
  40594. */
  40595. ShadowLight.prototype._getWorldMatrix = function () {
  40596. if (!this._worldMatrix) {
  40597. this._worldMatrix = BABYLON.Matrix.Identity();
  40598. }
  40599. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  40600. return this._worldMatrix;
  40601. };
  40602. /**
  40603. * Gets the minZ used for shadow according to both the scene and the light.
  40604. * @param activeCamera
  40605. */
  40606. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  40607. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  40608. };
  40609. /**
  40610. * Gets the maxZ used for shadow according to both the scene and the light.
  40611. * @param activeCamera
  40612. */
  40613. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  40614. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  40615. };
  40616. /**
  40617. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  40618. * Returns the light.
  40619. */
  40620. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40621. if (this.customProjectionMatrixBuilder) {
  40622. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  40623. }
  40624. else {
  40625. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  40626. }
  40627. return this;
  40628. };
  40629. __decorate([
  40630. BABYLON.serializeAsVector3()
  40631. ], ShadowLight.prototype, "position", void 0);
  40632. __decorate([
  40633. BABYLON.serializeAsVector3()
  40634. ], ShadowLight.prototype, "direction", null);
  40635. __decorate([
  40636. BABYLON.serialize()
  40637. ], ShadowLight.prototype, "shadowMinZ", null);
  40638. __decorate([
  40639. BABYLON.serialize()
  40640. ], ShadowLight.prototype, "shadowMaxZ", null);
  40641. return ShadowLight;
  40642. }(BABYLON.Light));
  40643. BABYLON.ShadowLight = ShadowLight;
  40644. })(BABYLON || (BABYLON = {}));
  40645. //# sourceMappingURL=babylon.shadowLight.js.map
  40646. var BABYLON;
  40647. (function (BABYLON) {
  40648. var PointLight = /** @class */ (function (_super) {
  40649. __extends(PointLight, _super);
  40650. /**
  40651. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  40652. * A PointLight emits the light in every direction.
  40653. * It can cast shadows.
  40654. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  40655. * ```javascript
  40656. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  40657. * ```
  40658. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40659. */
  40660. function PointLight(name, position, scene) {
  40661. var _this = _super.call(this, name, scene) || this;
  40662. _this._shadowAngle = Math.PI / 2;
  40663. _this.position = position;
  40664. return _this;
  40665. }
  40666. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  40667. /**
  40668. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40669. * This specifies what angle the shadow will use to be created.
  40670. *
  40671. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  40672. */
  40673. get: function () {
  40674. return this._shadowAngle;
  40675. },
  40676. /**
  40677. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40678. * This specifies what angle the shadow will use to be created.
  40679. *
  40680. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  40681. */
  40682. set: function (value) {
  40683. this._shadowAngle = value;
  40684. this.forceProjectionMatrixCompute();
  40685. },
  40686. enumerable: true,
  40687. configurable: true
  40688. });
  40689. Object.defineProperty(PointLight.prototype, "direction", {
  40690. get: function () {
  40691. return this._direction;
  40692. },
  40693. /**
  40694. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40695. */
  40696. set: function (value) {
  40697. var previousNeedCube = this.needCube();
  40698. this._direction = value;
  40699. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  40700. this._shadowGenerator.recreateShadowMap();
  40701. }
  40702. },
  40703. enumerable: true,
  40704. configurable: true
  40705. });
  40706. /**
  40707. * Returns the string "PointLight"
  40708. */
  40709. PointLight.prototype.getClassName = function () {
  40710. return "PointLight";
  40711. };
  40712. /**
  40713. * Returns the integer 0.
  40714. */
  40715. PointLight.prototype.getTypeID = function () {
  40716. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  40717. };
  40718. /**
  40719. * Specifies wether or not the shadowmap should be a cube texture.
  40720. */
  40721. PointLight.prototype.needCube = function () {
  40722. return !this.direction;
  40723. };
  40724. /**
  40725. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  40726. */
  40727. PointLight.prototype.getShadowDirection = function (faceIndex) {
  40728. if (this.direction) {
  40729. return _super.prototype.getShadowDirection.call(this, faceIndex);
  40730. }
  40731. else {
  40732. switch (faceIndex) {
  40733. case 0:
  40734. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  40735. case 1:
  40736. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  40737. case 2:
  40738. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  40739. case 3:
  40740. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  40741. case 4:
  40742. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  40743. case 5:
  40744. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  40745. }
  40746. }
  40747. return BABYLON.Vector3.Zero();
  40748. };
  40749. /**
  40750. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  40751. * - fov = PI / 2
  40752. * - aspect ratio : 1.0
  40753. * - z-near and far equal to the active camera minZ and maxZ.
  40754. * Returns the PointLight.
  40755. */
  40756. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40757. var activeCamera = this.getScene().activeCamera;
  40758. if (!activeCamera) {
  40759. return;
  40760. }
  40761. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  40762. };
  40763. PointLight.prototype._buildUniformLayout = function () {
  40764. this._uniformBuffer.addUniform("vLightData", 4);
  40765. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40766. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40767. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40768. this._uniformBuffer.addUniform("depthValues", 2);
  40769. this._uniformBuffer.create();
  40770. };
  40771. /**
  40772. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  40773. * Returns the PointLight.
  40774. */
  40775. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  40776. if (this.computeTransformedInformation()) {
  40777. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  40778. return this;
  40779. }
  40780. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  40781. return this;
  40782. };
  40783. __decorate([
  40784. BABYLON.serialize()
  40785. ], PointLight.prototype, "shadowAngle", null);
  40786. return PointLight;
  40787. }(BABYLON.ShadowLight));
  40788. BABYLON.PointLight = PointLight;
  40789. })(BABYLON || (BABYLON = {}));
  40790. //# sourceMappingURL=babylon.pointLight.js.map
  40791. var BABYLON;
  40792. (function (BABYLON) {
  40793. var DirectionalLight = /** @class */ (function (_super) {
  40794. __extends(DirectionalLight, _super);
  40795. /**
  40796. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  40797. * The directional light is emitted from everywhere in the given direction.
  40798. * It can cast shawdows.
  40799. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40800. */
  40801. function DirectionalLight(name, direction, scene) {
  40802. var _this = _super.call(this, name, scene) || this;
  40803. _this._shadowFrustumSize = 0;
  40804. _this._shadowOrthoScale = 0.5;
  40805. _this.autoUpdateExtends = true;
  40806. // Cache
  40807. _this._orthoLeft = Number.MAX_VALUE;
  40808. _this._orthoRight = Number.MIN_VALUE;
  40809. _this._orthoTop = Number.MIN_VALUE;
  40810. _this._orthoBottom = Number.MAX_VALUE;
  40811. _this.position = direction.scale(-1.0);
  40812. _this.direction = direction;
  40813. return _this;
  40814. }
  40815. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  40816. /**
  40817. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  40818. */
  40819. get: function () {
  40820. return this._shadowFrustumSize;
  40821. },
  40822. /**
  40823. * Specifies a fix frustum size for the shadow generation.
  40824. */
  40825. set: function (value) {
  40826. this._shadowFrustumSize = value;
  40827. this.forceProjectionMatrixCompute();
  40828. },
  40829. enumerable: true,
  40830. configurable: true
  40831. });
  40832. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  40833. get: function () {
  40834. return this._shadowOrthoScale;
  40835. },
  40836. set: function (value) {
  40837. this._shadowOrthoScale = value;
  40838. this.forceProjectionMatrixCompute();
  40839. },
  40840. enumerable: true,
  40841. configurable: true
  40842. });
  40843. /**
  40844. * Returns the string "DirectionalLight".
  40845. */
  40846. DirectionalLight.prototype.getClassName = function () {
  40847. return "DirectionalLight";
  40848. };
  40849. /**
  40850. * Returns the integer 1.
  40851. */
  40852. DirectionalLight.prototype.getTypeID = function () {
  40853. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  40854. };
  40855. /**
  40856. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  40857. * Returns the DirectionalLight Shadow projection matrix.
  40858. */
  40859. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40860. if (this.shadowFrustumSize > 0) {
  40861. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  40862. }
  40863. else {
  40864. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  40865. }
  40866. };
  40867. /**
  40868. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  40869. * Returns the DirectionalLight Shadow projection matrix.
  40870. */
  40871. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  40872. var activeCamera = this.getScene().activeCamera;
  40873. if (!activeCamera) {
  40874. return;
  40875. }
  40876. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  40877. };
  40878. /**
  40879. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  40880. * Returns the DirectionalLight Shadow projection matrix.
  40881. */
  40882. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40883. var activeCamera = this.getScene().activeCamera;
  40884. if (!activeCamera) {
  40885. return;
  40886. }
  40887. // Check extends
  40888. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  40889. var tempVector3 = BABYLON.Vector3.Zero();
  40890. this._orthoLeft = Number.MAX_VALUE;
  40891. this._orthoRight = Number.MIN_VALUE;
  40892. this._orthoTop = Number.MIN_VALUE;
  40893. this._orthoBottom = Number.MAX_VALUE;
  40894. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  40895. var mesh = renderList[meshIndex];
  40896. if (!mesh) {
  40897. continue;
  40898. }
  40899. var boundingInfo = mesh.getBoundingInfo();
  40900. var boundingBox = boundingInfo.boundingBox;
  40901. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  40902. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  40903. if (tempVector3.x < this._orthoLeft)
  40904. this._orthoLeft = tempVector3.x;
  40905. if (tempVector3.y < this._orthoBottom)
  40906. this._orthoBottom = tempVector3.y;
  40907. if (tempVector3.x > this._orthoRight)
  40908. this._orthoRight = tempVector3.x;
  40909. if (tempVector3.y > this._orthoTop)
  40910. this._orthoTop = tempVector3.y;
  40911. }
  40912. }
  40913. }
  40914. var xOffset = this._orthoRight - this._orthoLeft;
  40915. var yOffset = this._orthoTop - this._orthoBottom;
  40916. 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);
  40917. };
  40918. DirectionalLight.prototype._buildUniformLayout = function () {
  40919. this._uniformBuffer.addUniform("vLightData", 4);
  40920. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40921. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40922. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40923. this._uniformBuffer.addUniform("depthValues", 2);
  40924. this._uniformBuffer.create();
  40925. };
  40926. /**
  40927. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  40928. * Returns the DirectionalLight.
  40929. */
  40930. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  40931. if (this.computeTransformedInformation()) {
  40932. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  40933. return this;
  40934. }
  40935. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  40936. return this;
  40937. };
  40938. /**
  40939. * Gets the minZ used for shadow according to both the scene and the light.
  40940. *
  40941. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  40942. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  40943. * @param activeCamera
  40944. */
  40945. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  40946. return 1;
  40947. };
  40948. /**
  40949. * Gets the maxZ used for shadow according to both the scene and the light.
  40950. *
  40951. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  40952. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  40953. * @param activeCamera
  40954. */
  40955. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  40956. return 1;
  40957. };
  40958. __decorate([
  40959. BABYLON.serialize()
  40960. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  40961. __decorate([
  40962. BABYLON.serialize()
  40963. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  40964. __decorate([
  40965. BABYLON.serialize()
  40966. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  40967. return DirectionalLight;
  40968. }(BABYLON.ShadowLight));
  40969. BABYLON.DirectionalLight = DirectionalLight;
  40970. })(BABYLON || (BABYLON = {}));
  40971. //# sourceMappingURL=babylon.directionalLight.js.map
  40972. var BABYLON;
  40973. (function (BABYLON) {
  40974. var SpotLight = /** @class */ (function (_super) {
  40975. __extends(SpotLight, _super);
  40976. /**
  40977. * Creates a SpotLight object in the scene with the passed parameters :
  40978. * - `position` (Vector3) is the initial SpotLight position,
  40979. * - `direction` (Vector3) is the initial SpotLight direction,
  40980. * - `angle` (float, in radians) is the spot light cone angle,
  40981. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  40982. * A spot light is a simply light oriented cone.
  40983. * It can cast shadows.
  40984. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40985. */
  40986. function SpotLight(name, position, direction, angle, exponent, scene) {
  40987. var _this = _super.call(this, name, scene) || this;
  40988. _this.position = position;
  40989. _this.direction = direction;
  40990. _this.angle = angle;
  40991. _this.exponent = exponent;
  40992. return _this;
  40993. }
  40994. Object.defineProperty(SpotLight.prototype, "angle", {
  40995. get: function () {
  40996. return this._angle;
  40997. },
  40998. set: function (value) {
  40999. this._angle = value;
  41000. this.forceProjectionMatrixCompute();
  41001. },
  41002. enumerable: true,
  41003. configurable: true
  41004. });
  41005. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  41006. get: function () {
  41007. return this._shadowAngleScale;
  41008. },
  41009. /**
  41010. * Allows scaling the angle of the light for shadow generation only.
  41011. */
  41012. set: function (value) {
  41013. this._shadowAngleScale = value;
  41014. this.forceProjectionMatrixCompute();
  41015. },
  41016. enumerable: true,
  41017. configurable: true
  41018. });
  41019. /**
  41020. * Returns the string "SpotLight".
  41021. */
  41022. SpotLight.prototype.getClassName = function () {
  41023. return "SpotLight";
  41024. };
  41025. /**
  41026. * Returns the integer 2.
  41027. */
  41028. SpotLight.prototype.getTypeID = function () {
  41029. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  41030. };
  41031. /**
  41032. * 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.
  41033. * Returns the SpotLight.
  41034. */
  41035. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41036. var activeCamera = this.getScene().activeCamera;
  41037. if (!activeCamera) {
  41038. return;
  41039. }
  41040. this._shadowAngleScale = this._shadowAngleScale || 1;
  41041. var angle = this._shadowAngleScale * this._angle;
  41042. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  41043. };
  41044. SpotLight.prototype._buildUniformLayout = function () {
  41045. this._uniformBuffer.addUniform("vLightData", 4);
  41046. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  41047. this._uniformBuffer.addUniform("vLightSpecular", 3);
  41048. this._uniformBuffer.addUniform("vLightDirection", 3);
  41049. this._uniformBuffer.addUniform("shadowsInfo", 3);
  41050. this._uniformBuffer.addUniform("depthValues", 2);
  41051. this._uniformBuffer.create();
  41052. };
  41053. /**
  41054. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  41055. * Return the SpotLight.
  41056. */
  41057. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  41058. var normalizeDirection;
  41059. if (this.computeTransformedInformation()) {
  41060. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  41061. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  41062. }
  41063. else {
  41064. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  41065. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  41066. }
  41067. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  41068. return this;
  41069. };
  41070. __decorate([
  41071. BABYLON.serialize()
  41072. ], SpotLight.prototype, "angle", null);
  41073. __decorate([
  41074. BABYLON.serialize()
  41075. /**
  41076. * Allows scaling the angle of the light for shadow generation only.
  41077. */
  41078. ], SpotLight.prototype, "shadowAngleScale", null);
  41079. __decorate([
  41080. BABYLON.serialize()
  41081. ], SpotLight.prototype, "exponent", void 0);
  41082. return SpotLight;
  41083. }(BABYLON.ShadowLight));
  41084. BABYLON.SpotLight = SpotLight;
  41085. })(BABYLON || (BABYLON = {}));
  41086. //# sourceMappingURL=babylon.spotLight.js.map
  41087. var BABYLON;
  41088. (function (BABYLON) {
  41089. var AnimationRange = /** @class */ (function () {
  41090. function AnimationRange(name, from, to) {
  41091. this.name = name;
  41092. this.from = from;
  41093. this.to = to;
  41094. }
  41095. AnimationRange.prototype.clone = function () {
  41096. return new AnimationRange(this.name, this.from, this.to);
  41097. };
  41098. return AnimationRange;
  41099. }());
  41100. BABYLON.AnimationRange = AnimationRange;
  41101. /**
  41102. * Composed of a frame, and an action function
  41103. */
  41104. var AnimationEvent = /** @class */ (function () {
  41105. function AnimationEvent(frame, action, onlyOnce) {
  41106. this.frame = frame;
  41107. this.action = action;
  41108. this.onlyOnce = onlyOnce;
  41109. this.isDone = false;
  41110. }
  41111. return AnimationEvent;
  41112. }());
  41113. BABYLON.AnimationEvent = AnimationEvent;
  41114. var PathCursor = /** @class */ (function () {
  41115. function PathCursor(path) {
  41116. this.path = path;
  41117. this._onchange = new Array();
  41118. this.value = 0;
  41119. this.animations = new Array();
  41120. }
  41121. PathCursor.prototype.getPoint = function () {
  41122. var point = this.path.getPointAtLengthPosition(this.value);
  41123. return new BABYLON.Vector3(point.x, 0, point.y);
  41124. };
  41125. PathCursor.prototype.moveAhead = function (step) {
  41126. if (step === void 0) { step = 0.002; }
  41127. this.move(step);
  41128. return this;
  41129. };
  41130. PathCursor.prototype.moveBack = function (step) {
  41131. if (step === void 0) { step = 0.002; }
  41132. this.move(-step);
  41133. return this;
  41134. };
  41135. PathCursor.prototype.move = function (step) {
  41136. if (Math.abs(step) > 1) {
  41137. throw "step size should be less than 1.";
  41138. }
  41139. this.value += step;
  41140. this.ensureLimits();
  41141. this.raiseOnChange();
  41142. return this;
  41143. };
  41144. PathCursor.prototype.ensureLimits = function () {
  41145. while (this.value > 1) {
  41146. this.value -= 1;
  41147. }
  41148. while (this.value < 0) {
  41149. this.value += 1;
  41150. }
  41151. return this;
  41152. };
  41153. // used by animation engine
  41154. PathCursor.prototype.raiseOnChange = function () {
  41155. var _this = this;
  41156. this._onchange.forEach(function (f) { return f(_this); });
  41157. return this;
  41158. };
  41159. PathCursor.prototype.onchange = function (f) {
  41160. this._onchange.push(f);
  41161. return this;
  41162. };
  41163. return PathCursor;
  41164. }());
  41165. BABYLON.PathCursor = PathCursor;
  41166. var Animation = /** @class */ (function () {
  41167. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  41168. this.name = name;
  41169. this.targetProperty = targetProperty;
  41170. this.framePerSecond = framePerSecond;
  41171. this.dataType = dataType;
  41172. this.loopMode = loopMode;
  41173. this.enableBlending = enableBlending;
  41174. this._runtimeAnimations = new Array();
  41175. // The set of event that will be linked to this animation
  41176. this._events = new Array();
  41177. this.blendingSpeed = 0.01;
  41178. this._ranges = {};
  41179. this.targetPropertyPath = targetProperty.split(".");
  41180. this.dataType = dataType;
  41181. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  41182. }
  41183. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  41184. var dataType = undefined;
  41185. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  41186. dataType = Animation.ANIMATIONTYPE_FLOAT;
  41187. }
  41188. else if (from instanceof BABYLON.Quaternion) {
  41189. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  41190. }
  41191. else if (from instanceof BABYLON.Vector3) {
  41192. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  41193. }
  41194. else if (from instanceof BABYLON.Vector2) {
  41195. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  41196. }
  41197. else if (from instanceof BABYLON.Color3) {
  41198. dataType = Animation.ANIMATIONTYPE_COLOR3;
  41199. }
  41200. else if (from instanceof BABYLON.Size) {
  41201. dataType = Animation.ANIMATIONTYPE_SIZE;
  41202. }
  41203. if (dataType == undefined) {
  41204. return null;
  41205. }
  41206. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  41207. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  41208. animation.setKeys(keys);
  41209. if (easingFunction !== undefined) {
  41210. animation.setEasingFunction(easingFunction);
  41211. }
  41212. return animation;
  41213. };
  41214. /**
  41215. * Sets up an animation.
  41216. * @param property the property to animate
  41217. * @param animationType the animation type to apply
  41218. * @param easingFunction the easing function used in the animation
  41219. * @returns The created animation
  41220. */
  41221. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  41222. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  41223. animation.setEasingFunction(easingFunction);
  41224. return animation;
  41225. };
  41226. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  41227. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  41228. if (!animation) {
  41229. return null;
  41230. }
  41231. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  41232. };
  41233. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  41234. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  41235. if (!animation) {
  41236. return null;
  41237. }
  41238. node.animations.push(animation);
  41239. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  41240. };
  41241. /**
  41242. * Transition property of the Camera to the target Value.
  41243. * @param property The property to transition
  41244. * @param targetValue The target Value of the property
  41245. * @param host The object where the property to animate belongs
  41246. * @param scene Scene used to run the animation
  41247. * @param frameRate Framerate (in frame/s) to use
  41248. * @param transition The transition type we want to use
  41249. * @param duration The duration of the animation, in milliseconds
  41250. * @param onAnimationEnd Call back trigger at the end of the animation.
  41251. */
  41252. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  41253. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  41254. if (duration <= 0) {
  41255. host[property] = targetValue;
  41256. if (onAnimationEnd) {
  41257. onAnimationEnd();
  41258. }
  41259. return null;
  41260. }
  41261. var endFrame = frameRate * (duration / 1000);
  41262. transition.setKeys([{
  41263. frame: 0,
  41264. value: host[property].clone ? host[property].clone() : host[property]
  41265. },
  41266. {
  41267. frame: endFrame,
  41268. value: targetValue
  41269. }]);
  41270. if (!host.animations) {
  41271. host.animations = [];
  41272. }
  41273. host.animations.push(transition);
  41274. var animation = scene.beginAnimation(host, 0, endFrame, false);
  41275. animation.onAnimationEnd = onAnimationEnd;
  41276. return animation;
  41277. };
  41278. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  41279. /**
  41280. * Return the array of runtime animations currently using this animation
  41281. */
  41282. get: function () {
  41283. return this._runtimeAnimations;
  41284. },
  41285. enumerable: true,
  41286. configurable: true
  41287. });
  41288. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  41289. get: function () {
  41290. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  41291. var runtimeAnimation = _a[_i];
  41292. if (!runtimeAnimation.isStopped) {
  41293. return true;
  41294. }
  41295. }
  41296. return false;
  41297. },
  41298. enumerable: true,
  41299. configurable: true
  41300. });
  41301. // Methods
  41302. /**
  41303. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  41304. */
  41305. Animation.prototype.toString = function (fullDetails) {
  41306. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  41307. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  41308. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  41309. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  41310. if (fullDetails) {
  41311. ret += ", Ranges: {";
  41312. var first = true;
  41313. for (var name in this._ranges) {
  41314. if (first) {
  41315. ret += ", ";
  41316. first = false;
  41317. }
  41318. ret += name;
  41319. }
  41320. ret += "}";
  41321. }
  41322. return ret;
  41323. };
  41324. /**
  41325. * Add an event to this animation.
  41326. */
  41327. Animation.prototype.addEvent = function (event) {
  41328. this._events.push(event);
  41329. };
  41330. /**
  41331. * Remove all events found at the given frame
  41332. * @param frame
  41333. */
  41334. Animation.prototype.removeEvents = function (frame) {
  41335. for (var index = 0; index < this._events.length; index++) {
  41336. if (this._events[index].frame === frame) {
  41337. this._events.splice(index, 1);
  41338. index--;
  41339. }
  41340. }
  41341. };
  41342. Animation.prototype.getEvents = function () {
  41343. return this._events;
  41344. };
  41345. Animation.prototype.createRange = function (name, from, to) {
  41346. // check name not already in use; could happen for bones after serialized
  41347. if (!this._ranges[name]) {
  41348. this._ranges[name] = new AnimationRange(name, from, to);
  41349. }
  41350. };
  41351. Animation.prototype.deleteRange = function (name, deleteFrames) {
  41352. if (deleteFrames === void 0) { deleteFrames = true; }
  41353. var range = this._ranges[name];
  41354. if (!range) {
  41355. return;
  41356. }
  41357. if (deleteFrames) {
  41358. var from = range.from;
  41359. var to = range.to;
  41360. // this loop MUST go high to low for multiple splices to work
  41361. for (var key = this._keys.length - 1; key >= 0; key--) {
  41362. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  41363. this._keys.splice(key, 1);
  41364. }
  41365. }
  41366. }
  41367. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  41368. };
  41369. Animation.prototype.getRange = function (name) {
  41370. return this._ranges[name];
  41371. };
  41372. Animation.prototype.getKeys = function () {
  41373. return this._keys;
  41374. };
  41375. Animation.prototype.getHighestFrame = function () {
  41376. var ret = 0;
  41377. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  41378. if (ret < this._keys[key].frame) {
  41379. ret = this._keys[key].frame;
  41380. }
  41381. }
  41382. return ret;
  41383. };
  41384. Animation.prototype.getEasingFunction = function () {
  41385. return this._easingFunction;
  41386. };
  41387. Animation.prototype.setEasingFunction = function (easingFunction) {
  41388. this._easingFunction = easingFunction;
  41389. };
  41390. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  41391. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  41392. };
  41393. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  41394. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  41395. };
  41396. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  41397. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  41398. };
  41399. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  41400. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  41401. };
  41402. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  41403. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  41404. };
  41405. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  41406. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  41407. };
  41408. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  41409. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  41410. };
  41411. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  41412. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  41413. };
  41414. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  41415. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  41416. };
  41417. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  41418. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  41419. };
  41420. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  41421. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  41422. };
  41423. Animation.prototype.clone = function () {
  41424. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  41425. clone.enableBlending = this.enableBlending;
  41426. clone.blendingSpeed = this.blendingSpeed;
  41427. if (this._keys) {
  41428. clone.setKeys(this._keys);
  41429. }
  41430. if (this._ranges) {
  41431. clone._ranges = {};
  41432. for (var name in this._ranges) {
  41433. var range = this._ranges[name];
  41434. if (!range) {
  41435. continue;
  41436. }
  41437. clone._ranges[name] = range.clone();
  41438. }
  41439. }
  41440. return clone;
  41441. };
  41442. Animation.prototype.setKeys = function (values) {
  41443. this._keys = values.slice(0);
  41444. };
  41445. Animation.prototype.serialize = function () {
  41446. var serializationObject = {};
  41447. serializationObject.name = this.name;
  41448. serializationObject.property = this.targetProperty;
  41449. serializationObject.framePerSecond = this.framePerSecond;
  41450. serializationObject.dataType = this.dataType;
  41451. serializationObject.loopBehavior = this.loopMode;
  41452. serializationObject.enableBlending = this.enableBlending;
  41453. serializationObject.blendingSpeed = this.blendingSpeed;
  41454. var dataType = this.dataType;
  41455. serializationObject.keys = [];
  41456. var keys = this.getKeys();
  41457. for (var index = 0; index < keys.length; index++) {
  41458. var animationKey = keys[index];
  41459. var key = {};
  41460. key.frame = animationKey.frame;
  41461. switch (dataType) {
  41462. case Animation.ANIMATIONTYPE_FLOAT:
  41463. key.values = [animationKey.value];
  41464. break;
  41465. case Animation.ANIMATIONTYPE_QUATERNION:
  41466. case Animation.ANIMATIONTYPE_MATRIX:
  41467. case Animation.ANIMATIONTYPE_VECTOR3:
  41468. case Animation.ANIMATIONTYPE_COLOR3:
  41469. key.values = animationKey.value.asArray();
  41470. break;
  41471. }
  41472. serializationObject.keys.push(key);
  41473. }
  41474. serializationObject.ranges = [];
  41475. for (var name in this._ranges) {
  41476. var source = this._ranges[name];
  41477. if (!source) {
  41478. continue;
  41479. }
  41480. var range = {};
  41481. range.name = name;
  41482. range.from = source.from;
  41483. range.to = source.to;
  41484. serializationObject.ranges.push(range);
  41485. }
  41486. return serializationObject;
  41487. };
  41488. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  41489. get: function () {
  41490. return Animation._ANIMATIONTYPE_FLOAT;
  41491. },
  41492. enumerable: true,
  41493. configurable: true
  41494. });
  41495. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  41496. get: function () {
  41497. return Animation._ANIMATIONTYPE_VECTOR3;
  41498. },
  41499. enumerable: true,
  41500. configurable: true
  41501. });
  41502. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  41503. get: function () {
  41504. return Animation._ANIMATIONTYPE_VECTOR2;
  41505. },
  41506. enumerable: true,
  41507. configurable: true
  41508. });
  41509. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  41510. get: function () {
  41511. return Animation._ANIMATIONTYPE_SIZE;
  41512. },
  41513. enumerable: true,
  41514. configurable: true
  41515. });
  41516. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  41517. get: function () {
  41518. return Animation._ANIMATIONTYPE_QUATERNION;
  41519. },
  41520. enumerable: true,
  41521. configurable: true
  41522. });
  41523. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  41524. get: function () {
  41525. return Animation._ANIMATIONTYPE_MATRIX;
  41526. },
  41527. enumerable: true,
  41528. configurable: true
  41529. });
  41530. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  41531. get: function () {
  41532. return Animation._ANIMATIONTYPE_COLOR3;
  41533. },
  41534. enumerable: true,
  41535. configurable: true
  41536. });
  41537. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  41538. get: function () {
  41539. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  41540. },
  41541. enumerable: true,
  41542. configurable: true
  41543. });
  41544. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  41545. get: function () {
  41546. return Animation._ANIMATIONLOOPMODE_CYCLE;
  41547. },
  41548. enumerable: true,
  41549. configurable: true
  41550. });
  41551. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  41552. get: function () {
  41553. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  41554. },
  41555. enumerable: true,
  41556. configurable: true
  41557. });
  41558. Animation.Parse = function (parsedAnimation) {
  41559. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  41560. var dataType = parsedAnimation.dataType;
  41561. var keys = [];
  41562. var data;
  41563. var index;
  41564. if (parsedAnimation.enableBlending) {
  41565. animation.enableBlending = parsedAnimation.enableBlending;
  41566. }
  41567. if (parsedAnimation.blendingSpeed) {
  41568. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  41569. }
  41570. for (index = 0; index < parsedAnimation.keys.length; index++) {
  41571. var key = parsedAnimation.keys[index];
  41572. var inTangent;
  41573. var outTangent;
  41574. switch (dataType) {
  41575. case Animation.ANIMATIONTYPE_FLOAT:
  41576. data = key.values[0];
  41577. if (key.values.length >= 1) {
  41578. inTangent = key.values[1];
  41579. }
  41580. if (key.values.length >= 2) {
  41581. outTangent = key.values[2];
  41582. }
  41583. break;
  41584. case Animation.ANIMATIONTYPE_QUATERNION:
  41585. data = BABYLON.Quaternion.FromArray(key.values);
  41586. if (key.values.length >= 8) {
  41587. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  41588. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  41589. inTangent = _inTangent;
  41590. }
  41591. }
  41592. if (key.values.length >= 12) {
  41593. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  41594. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  41595. outTangent = _outTangent;
  41596. }
  41597. }
  41598. break;
  41599. case Animation.ANIMATIONTYPE_MATRIX:
  41600. data = BABYLON.Matrix.FromArray(key.values);
  41601. break;
  41602. case Animation.ANIMATIONTYPE_COLOR3:
  41603. data = BABYLON.Color3.FromArray(key.values);
  41604. break;
  41605. case Animation.ANIMATIONTYPE_VECTOR3:
  41606. default:
  41607. data = BABYLON.Vector3.FromArray(key.values);
  41608. break;
  41609. }
  41610. var keyData = {};
  41611. keyData.frame = key.frame;
  41612. keyData.value = data;
  41613. if (inTangent != undefined) {
  41614. keyData.inTangent = inTangent;
  41615. }
  41616. if (outTangent != undefined) {
  41617. keyData.outTangent = outTangent;
  41618. }
  41619. keys.push(keyData);
  41620. }
  41621. animation.setKeys(keys);
  41622. if (parsedAnimation.ranges) {
  41623. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  41624. data = parsedAnimation.ranges[index];
  41625. animation.createRange(data.name, data.from, data.to);
  41626. }
  41627. }
  41628. return animation;
  41629. };
  41630. Animation.AppendSerializedAnimations = function (source, destination) {
  41631. if (source.animations) {
  41632. destination.animations = [];
  41633. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  41634. var animation = source.animations[animationIndex];
  41635. destination.animations.push(animation.serialize());
  41636. }
  41637. }
  41638. };
  41639. Animation.AllowMatricesInterpolation = false;
  41640. // Statics
  41641. Animation._ANIMATIONTYPE_FLOAT = 0;
  41642. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  41643. Animation._ANIMATIONTYPE_QUATERNION = 2;
  41644. Animation._ANIMATIONTYPE_MATRIX = 3;
  41645. Animation._ANIMATIONTYPE_COLOR3 = 4;
  41646. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  41647. Animation._ANIMATIONTYPE_SIZE = 6;
  41648. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  41649. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  41650. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  41651. return Animation;
  41652. }());
  41653. BABYLON.Animation = Animation;
  41654. })(BABYLON || (BABYLON = {}));
  41655. //# sourceMappingURL=babylon.animation.js.map
  41656. var BABYLON;
  41657. (function (BABYLON) {
  41658. /**
  41659. * This class defines the direct association between an animation and a target
  41660. */
  41661. var TargetedAnimation = /** @class */ (function () {
  41662. function TargetedAnimation() {
  41663. }
  41664. return TargetedAnimation;
  41665. }());
  41666. BABYLON.TargetedAnimation = TargetedAnimation;
  41667. /**
  41668. * Use this class to create coordinated animations on multiple targets
  41669. */
  41670. var AnimationGroup = /** @class */ (function () {
  41671. function AnimationGroup(name, scene) {
  41672. if (scene === void 0) { scene = null; }
  41673. this.name = name;
  41674. this._targetedAnimations = new Array();
  41675. this._animatables = new Array();
  41676. this._from = Number.MAX_VALUE;
  41677. this._to = Number.MIN_VALUE;
  41678. this._speedRatio = 1;
  41679. this.onAnimationEndObservable = new BABYLON.Observable();
  41680. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  41681. this._scene.animationGroups.push(this);
  41682. }
  41683. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  41684. /**
  41685. * Define if the animations are started
  41686. */
  41687. get: function () {
  41688. return this._isStarted;
  41689. },
  41690. enumerable: true,
  41691. configurable: true
  41692. });
  41693. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  41694. /**
  41695. * Gets or sets the speed ratio to use for all animations
  41696. */
  41697. get: function () {
  41698. return this._speedRatio;
  41699. },
  41700. /**
  41701. * Gets or sets the speed ratio to use for all animations
  41702. */
  41703. set: function (value) {
  41704. if (this._speedRatio === value) {
  41705. return;
  41706. }
  41707. for (var index = 0; index < this._animatables.length; index++) {
  41708. var animatable = this._animatables[index];
  41709. animatable.speedRatio = this._speedRatio;
  41710. }
  41711. },
  41712. enumerable: true,
  41713. configurable: true
  41714. });
  41715. /**
  41716. * Add an animation (with its target) in the group
  41717. * @param animation defines the animation we want to add
  41718. * @param target defines the target of the animation
  41719. * @returns the {BABYLON.TargetedAnimation} object
  41720. */
  41721. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  41722. var targetedAnimation = {
  41723. animation: animation,
  41724. target: target
  41725. };
  41726. var keys = animation.getKeys();
  41727. if (this._from > keys[0].frame) {
  41728. this._from = keys[0].frame;
  41729. }
  41730. if (this._to < keys[keys.length - 1].frame) {
  41731. this._to = keys[keys.length - 1].frame;
  41732. }
  41733. this._targetedAnimations.push(targetedAnimation);
  41734. return targetedAnimation;
  41735. };
  41736. /**
  41737. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  41738. * It can add constant keys at begin or end
  41739. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smaller begin frame of all animations
  41740. * @param endFrame defines the new end frame for all animations. It can't be smaller than the larger end frame of all animations
  41741. */
  41742. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  41743. beginFrame = Math.min(beginFrame, this._from);
  41744. endFrame = Math.min(endFrame, this._to);
  41745. for (var index = 0; index < this._targetedAnimations.length; index++) {
  41746. var targetedAnimation = this._targetedAnimations[index];
  41747. var keys = targetedAnimation.animation.getKeys();
  41748. var startKey = keys[0];
  41749. var endKey = keys[keys.length - 1];
  41750. if (startKey.frame > beginFrame) {
  41751. var newKey = {
  41752. frame: beginFrame,
  41753. value: startKey.value,
  41754. inTangent: startKey.inTangent,
  41755. outTangent: startKey.outTangent
  41756. };
  41757. keys.splice(0, 0, newKey);
  41758. }
  41759. if (endKey.frame < endFrame) {
  41760. var newKey = {
  41761. frame: endFrame,
  41762. value: endKey.value,
  41763. inTangent: startKey.outTangent,
  41764. outTangent: startKey.outTangent
  41765. };
  41766. keys.push(newKey);
  41767. }
  41768. }
  41769. return this;
  41770. };
  41771. /**
  41772. * Start all animations on given targets
  41773. * @param loop defines if animations must loop
  41774. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  41775. */
  41776. AnimationGroup.prototype.start = function (loop, speedRatio) {
  41777. var _this = this;
  41778. if (loop === void 0) { loop = false; }
  41779. if (speedRatio === void 0) { speedRatio = 1; }
  41780. if (this._isStarted || this._targetedAnimations.length === 0) {
  41781. return this;
  41782. }
  41783. var _loop_1 = function () {
  41784. var targetedAnimation = this_1._targetedAnimations[index];
  41785. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  41786. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  41787. }));
  41788. };
  41789. var this_1 = this;
  41790. for (var index = 0; index < this._targetedAnimations.length; index++) {
  41791. _loop_1();
  41792. }
  41793. this._speedRatio = speedRatio;
  41794. this._isStarted = true;
  41795. return this;
  41796. };
  41797. /**
  41798. * Pause all animations
  41799. */
  41800. AnimationGroup.prototype.pause = function () {
  41801. if (!this._isStarted) {
  41802. return this;
  41803. }
  41804. for (var index = 0; index < this._animatables.length; index++) {
  41805. var animatable = this._animatables[index];
  41806. animatable.pause();
  41807. }
  41808. return this;
  41809. };
  41810. /**
  41811. * Play all animations to initial state
  41812. * This function will start() the animations if they were not started or will restart() them if they were paused
  41813. * @param loop defines if animations must loop
  41814. */
  41815. AnimationGroup.prototype.play = function (loop) {
  41816. if (this.isStarted) {
  41817. if (loop !== undefined) {
  41818. for (var index = 0; index < this._animatables.length; index++) {
  41819. var animatable = this._animatables[index];
  41820. animatable.loopAnimation = loop;
  41821. }
  41822. }
  41823. this.restart();
  41824. }
  41825. else {
  41826. this.start(loop);
  41827. }
  41828. return this;
  41829. };
  41830. /**
  41831. * Reset all animations to initial state
  41832. */
  41833. AnimationGroup.prototype.reset = function () {
  41834. if (!this._isStarted) {
  41835. return this;
  41836. }
  41837. for (var index = 0; index < this._animatables.length; index++) {
  41838. var animatable = this._animatables[index];
  41839. animatable.reset();
  41840. }
  41841. return this;
  41842. };
  41843. /**
  41844. * Restart animations from key 0
  41845. */
  41846. AnimationGroup.prototype.restart = function () {
  41847. if (!this._isStarted) {
  41848. return this;
  41849. }
  41850. for (var index = 0; index < this._animatables.length; index++) {
  41851. var animatable = this._animatables[index];
  41852. animatable.restart();
  41853. }
  41854. return this;
  41855. };
  41856. /**
  41857. * Stop all animations
  41858. */
  41859. AnimationGroup.prototype.stop = function () {
  41860. if (!this._isStarted) {
  41861. return this;
  41862. }
  41863. for (var index = 0; index < this._animatables.length; index++) {
  41864. var animatable = this._animatables[index];
  41865. animatable.stop();
  41866. }
  41867. this._isStarted = false;
  41868. return this;
  41869. };
  41870. /**
  41871. * Dispose all associated resources
  41872. */
  41873. AnimationGroup.prototype.dispose = function () {
  41874. this._targetedAnimations = [];
  41875. this._animatables = [];
  41876. var index = this._scene.animationGroups.indexOf(this);
  41877. if (index > -1) {
  41878. this._scene.animationGroups.splice(index, 1);
  41879. }
  41880. };
  41881. return AnimationGroup;
  41882. }());
  41883. BABYLON.AnimationGroup = AnimationGroup;
  41884. })(BABYLON || (BABYLON = {}));
  41885. //# sourceMappingURL=babylon.animationGroup.js.map
  41886. var BABYLON;
  41887. (function (BABYLON) {
  41888. var RuntimeAnimation = /** @class */ (function () {
  41889. function RuntimeAnimation(target, animation) {
  41890. this._offsetsCache = {};
  41891. this._highLimitsCache = {};
  41892. this._stopped = false;
  41893. this._blendingFactor = 0;
  41894. this._ratioOffset = 0;
  41895. this._animation = animation;
  41896. this._target = target;
  41897. animation._runtimeAnimations.push(this);
  41898. }
  41899. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  41900. get: function () {
  41901. return this._animation;
  41902. },
  41903. enumerable: true,
  41904. configurable: true
  41905. });
  41906. RuntimeAnimation.prototype.reset = function () {
  41907. this._offsetsCache = {};
  41908. this._highLimitsCache = {};
  41909. this.currentFrame = 0;
  41910. this._blendingFactor = 0;
  41911. this._originalBlendValue = null;
  41912. };
  41913. RuntimeAnimation.prototype.isStopped = function () {
  41914. return this._stopped;
  41915. };
  41916. RuntimeAnimation.prototype.dispose = function () {
  41917. var index = this._animation.runtimeAnimations.indexOf(this);
  41918. if (index > -1) {
  41919. this._animation.runtimeAnimations.splice(index, 1);
  41920. }
  41921. };
  41922. RuntimeAnimation.prototype._getKeyValue = function (value) {
  41923. if (typeof value === "function") {
  41924. return value();
  41925. }
  41926. return value;
  41927. };
  41928. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  41929. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  41930. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  41931. }
  41932. this.currentFrame = currentFrame;
  41933. var keys = this._animation.getKeys();
  41934. // Try to get a hash to find the right key
  41935. 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));
  41936. if (keys[startKeyIndex].frame >= currentFrame) {
  41937. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  41938. startKeyIndex--;
  41939. }
  41940. }
  41941. for (var key = startKeyIndex; key < keys.length; key++) {
  41942. var endKey = keys[key + 1];
  41943. if (endKey.frame >= currentFrame) {
  41944. var startKey = keys[key];
  41945. var startValue = this._getKeyValue(startKey.value);
  41946. var endValue = this._getKeyValue(endKey.value);
  41947. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  41948. var frameDelta = endKey.frame - startKey.frame;
  41949. // gradient : percent of currentFrame between the frame inf and the frame sup
  41950. var gradient = (currentFrame - startKey.frame) / frameDelta;
  41951. // check for easingFunction and correction of gradient
  41952. var easingFunction = this._animation.getEasingFunction();
  41953. if (easingFunction != null) {
  41954. gradient = easingFunction.ease(gradient);
  41955. }
  41956. switch (this._animation.dataType) {
  41957. // Float
  41958. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  41959. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  41960. switch (loopMode) {
  41961. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41962. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41963. return floatValue;
  41964. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41965. return offsetValue * repeatCount + floatValue;
  41966. }
  41967. break;
  41968. // Quaternion
  41969. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  41970. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  41971. switch (loopMode) {
  41972. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41973. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41974. return quatValue;
  41975. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41976. return quatValue.add(offsetValue.scale(repeatCount));
  41977. }
  41978. return quatValue;
  41979. // Vector3
  41980. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  41981. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  41982. switch (loopMode) {
  41983. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41984. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41985. return vec3Value;
  41986. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41987. return vec3Value.add(offsetValue.scale(repeatCount));
  41988. }
  41989. // Vector2
  41990. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  41991. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  41992. switch (loopMode) {
  41993. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41994. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41995. return vec2Value;
  41996. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41997. return vec2Value.add(offsetValue.scale(repeatCount));
  41998. }
  41999. // Size
  42000. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  42001. switch (loopMode) {
  42002. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42003. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42004. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  42005. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42006. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  42007. }
  42008. // Color3
  42009. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  42010. switch (loopMode) {
  42011. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42012. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42013. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  42014. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42015. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  42016. }
  42017. // Matrix
  42018. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  42019. switch (loopMode) {
  42020. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42021. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42022. if (BABYLON.Animation.AllowMatricesInterpolation) {
  42023. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  42024. }
  42025. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42026. return startValue;
  42027. }
  42028. default:
  42029. break;
  42030. }
  42031. break;
  42032. }
  42033. }
  42034. return this._getKeyValue(keys[keys.length - 1].value);
  42035. };
  42036. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  42037. if (blend === void 0) { blend = false; }
  42038. // Set value
  42039. var path;
  42040. var destination;
  42041. var targetPropertyPath = this._animation.targetPropertyPath;
  42042. if (targetPropertyPath.length > 1) {
  42043. var property = this._target[targetPropertyPath[0]];
  42044. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  42045. property = property[targetPropertyPath[index]];
  42046. }
  42047. path = targetPropertyPath[targetPropertyPath.length - 1];
  42048. destination = property;
  42049. }
  42050. else {
  42051. path = targetPropertyPath[0];
  42052. destination = this._target;
  42053. }
  42054. // Blending
  42055. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  42056. if (!this._originalBlendValue) {
  42057. if (destination[path].clone) {
  42058. this._originalBlendValue = destination[path].clone();
  42059. }
  42060. else {
  42061. this._originalBlendValue = destination[path];
  42062. }
  42063. }
  42064. if (this._originalBlendValue.prototype) {
  42065. if (this._originalBlendValue.prototype.Lerp) {
  42066. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  42067. }
  42068. else {
  42069. destination[path] = currentValue;
  42070. }
  42071. }
  42072. else if (this._originalBlendValue.m) {
  42073. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  42074. }
  42075. else {
  42076. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  42077. }
  42078. this._blendingFactor += this._animation.blendingSpeed;
  42079. }
  42080. else {
  42081. destination[path] = currentValue;
  42082. }
  42083. if (this._target.markAsDirty) {
  42084. this._target.markAsDirty(this._animation.targetProperty);
  42085. }
  42086. };
  42087. RuntimeAnimation.prototype.goToFrame = function (frame) {
  42088. var keys = this._animation.getKeys();
  42089. if (frame < keys[0].frame) {
  42090. frame = keys[0].frame;
  42091. }
  42092. else if (frame > keys[keys.length - 1].frame) {
  42093. frame = keys[keys.length - 1].frame;
  42094. }
  42095. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  42096. this.setValue(currentValue);
  42097. };
  42098. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  42099. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  42100. this._ratioOffset = this._previousRatio - newRatio;
  42101. };
  42102. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  42103. if (blend === void 0) { blend = false; }
  42104. var targetPropertyPath = this._animation.targetPropertyPath;
  42105. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  42106. this._stopped = true;
  42107. return false;
  42108. }
  42109. var returnValue = true;
  42110. var keys = this._animation.getKeys();
  42111. // Adding a start key at frame 0 if missing
  42112. if (keys[0].frame !== 0) {
  42113. var newKey = { frame: 0, value: keys[0].value };
  42114. keys.splice(0, 0, newKey);
  42115. }
  42116. // Check limits
  42117. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  42118. from = keys[0].frame;
  42119. }
  42120. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  42121. to = keys[keys.length - 1].frame;
  42122. }
  42123. //to and from cannot be the same key
  42124. if (from === to) {
  42125. if (from > keys[0].frame) {
  42126. from--;
  42127. }
  42128. else if (to < keys[keys.length - 1].frame) {
  42129. to++;
  42130. }
  42131. }
  42132. // Compute ratio
  42133. var range = to - from;
  42134. var offsetValue;
  42135. // ratio represents the frame delta between from and to
  42136. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  42137. var highLimitValue = 0;
  42138. this._previousDelay = delay;
  42139. this._previousRatio = ratio;
  42140. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  42141. returnValue = false;
  42142. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  42143. }
  42144. else {
  42145. // Get max value if required
  42146. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  42147. var keyOffset = to.toString() + from.toString();
  42148. if (!this._offsetsCache[keyOffset]) {
  42149. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  42150. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  42151. switch (this._animation.dataType) {
  42152. // Float
  42153. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  42154. this._offsetsCache[keyOffset] = toValue - fromValue;
  42155. break;
  42156. // Quaternion
  42157. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  42158. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42159. break;
  42160. // Vector3
  42161. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  42162. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42163. // Vector2
  42164. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  42165. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42166. // Size
  42167. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  42168. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42169. // Color3
  42170. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  42171. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42172. default:
  42173. break;
  42174. }
  42175. this._highLimitsCache[keyOffset] = toValue;
  42176. }
  42177. highLimitValue = this._highLimitsCache[keyOffset];
  42178. offsetValue = this._offsetsCache[keyOffset];
  42179. }
  42180. }
  42181. if (offsetValue === undefined) {
  42182. switch (this._animation.dataType) {
  42183. // Float
  42184. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  42185. offsetValue = 0;
  42186. break;
  42187. // Quaternion
  42188. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  42189. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  42190. break;
  42191. // Vector3
  42192. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  42193. offsetValue = BABYLON.Vector3.Zero();
  42194. break;
  42195. // Vector2
  42196. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  42197. offsetValue = BABYLON.Vector2.Zero();
  42198. break;
  42199. // Size
  42200. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  42201. offsetValue = BABYLON.Size.Zero();
  42202. break;
  42203. // Color3
  42204. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  42205. offsetValue = BABYLON.Color3.Black();
  42206. }
  42207. }
  42208. // Compute value
  42209. var repeatCount = (ratio / range) >> 0;
  42210. var currentFrame = returnValue ? from + ratio % range : to;
  42211. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  42212. // Set value
  42213. this.setValue(currentValue);
  42214. // Check events
  42215. var events = this._animation.getEvents();
  42216. for (var index = 0; index < events.length; index++) {
  42217. // Make sure current frame has passed event frame and that event frame is within the current range
  42218. // Also, handle both forward and reverse animations
  42219. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  42220. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  42221. var event = events[index];
  42222. if (!event.isDone) {
  42223. // If event should be done only once, remove it.
  42224. if (event.onlyOnce) {
  42225. events.splice(index, 1);
  42226. index--;
  42227. }
  42228. event.isDone = true;
  42229. event.action();
  42230. } // Don't do anything if the event has already be done.
  42231. }
  42232. else if (events[index].isDone && !events[index].onlyOnce) {
  42233. // reset event, the animation is looping
  42234. events[index].isDone = false;
  42235. }
  42236. }
  42237. if (!returnValue) {
  42238. this._stopped = true;
  42239. }
  42240. return returnValue;
  42241. };
  42242. return RuntimeAnimation;
  42243. }());
  42244. BABYLON.RuntimeAnimation = RuntimeAnimation;
  42245. })(BABYLON || (BABYLON = {}));
  42246. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  42247. var BABYLON;
  42248. (function (BABYLON) {
  42249. var Animatable = /** @class */ (function () {
  42250. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  42251. if (fromFrame === void 0) { fromFrame = 0; }
  42252. if (toFrame === void 0) { toFrame = 100; }
  42253. if (loopAnimation === void 0) { loopAnimation = false; }
  42254. if (speedRatio === void 0) { speedRatio = 1.0; }
  42255. this.target = target;
  42256. this.fromFrame = fromFrame;
  42257. this.toFrame = toFrame;
  42258. this.loopAnimation = loopAnimation;
  42259. this.onAnimationEnd = onAnimationEnd;
  42260. this._localDelayOffset = null;
  42261. this._pausedDelay = null;
  42262. this._runtimeAnimations = new Array();
  42263. this._paused = false;
  42264. this._speedRatio = 1;
  42265. this.animationStarted = false;
  42266. if (animations) {
  42267. this.appendAnimations(target, animations);
  42268. }
  42269. this._speedRatio = speedRatio;
  42270. this._scene = scene;
  42271. scene._activeAnimatables.push(this);
  42272. }
  42273. Object.defineProperty(Animatable.prototype, "speedRatio", {
  42274. get: function () {
  42275. return this._speedRatio;
  42276. },
  42277. set: function (value) {
  42278. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  42279. var animation = this._runtimeAnimations[index];
  42280. animation._prepareForSpeedRatioChange(value);
  42281. }
  42282. this._speedRatio = value;
  42283. },
  42284. enumerable: true,
  42285. configurable: true
  42286. });
  42287. // Methods
  42288. Animatable.prototype.getAnimations = function () {
  42289. return this._runtimeAnimations;
  42290. };
  42291. Animatable.prototype.appendAnimations = function (target, animations) {
  42292. for (var index = 0; index < animations.length; index++) {
  42293. var animation = animations[index];
  42294. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  42295. }
  42296. };
  42297. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  42298. var runtimeAnimations = this._runtimeAnimations;
  42299. for (var index = 0; index < runtimeAnimations.length; index++) {
  42300. if (runtimeAnimations[index].animation.targetProperty === property) {
  42301. return runtimeAnimations[index].animation;
  42302. }
  42303. }
  42304. return null;
  42305. };
  42306. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  42307. var runtimeAnimations = this._runtimeAnimations;
  42308. for (var index = 0; index < runtimeAnimations.length; index++) {
  42309. if (runtimeAnimations[index].animation.targetProperty === property) {
  42310. return runtimeAnimations[index];
  42311. }
  42312. }
  42313. return null;
  42314. };
  42315. Animatable.prototype.reset = function () {
  42316. var runtimeAnimations = this._runtimeAnimations;
  42317. for (var index = 0; index < runtimeAnimations.length; index++) {
  42318. runtimeAnimations[index].reset();
  42319. }
  42320. // Reset to original value
  42321. for (index = 0; index < runtimeAnimations.length; index++) {
  42322. var animation = runtimeAnimations[index];
  42323. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  42324. }
  42325. this._localDelayOffset = null;
  42326. this._pausedDelay = null;
  42327. };
  42328. Animatable.prototype.enableBlending = function (blendingSpeed) {
  42329. var runtimeAnimations = this._runtimeAnimations;
  42330. for (var index = 0; index < runtimeAnimations.length; index++) {
  42331. runtimeAnimations[index].animation.enableBlending = true;
  42332. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  42333. }
  42334. };
  42335. Animatable.prototype.disableBlending = function () {
  42336. var runtimeAnimations = this._runtimeAnimations;
  42337. for (var index = 0; index < runtimeAnimations.length; index++) {
  42338. runtimeAnimations[index].animation.enableBlending = false;
  42339. }
  42340. };
  42341. Animatable.prototype.goToFrame = function (frame) {
  42342. var runtimeAnimations = this._runtimeAnimations;
  42343. if (runtimeAnimations[0]) {
  42344. var fps = runtimeAnimations[0].animation.framePerSecond;
  42345. var currentFrame = runtimeAnimations[0].currentFrame;
  42346. var adjustTime = frame - currentFrame;
  42347. var delay = adjustTime * 1000 / fps;
  42348. if (this._localDelayOffset === null) {
  42349. this._localDelayOffset = 0;
  42350. }
  42351. this._localDelayOffset -= delay;
  42352. }
  42353. for (var index = 0; index < runtimeAnimations.length; index++) {
  42354. runtimeAnimations[index].goToFrame(frame);
  42355. }
  42356. };
  42357. Animatable.prototype.pause = function () {
  42358. if (this._paused) {
  42359. return;
  42360. }
  42361. this._paused = true;
  42362. };
  42363. Animatable.prototype.restart = function () {
  42364. this._paused = false;
  42365. };
  42366. Animatable.prototype.stop = function (animationName) {
  42367. if (animationName) {
  42368. var idx = this._scene._activeAnimatables.indexOf(this);
  42369. if (idx > -1) {
  42370. var runtimeAnimations = this._runtimeAnimations;
  42371. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  42372. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  42373. continue;
  42374. }
  42375. runtimeAnimations[index].dispose();
  42376. runtimeAnimations.splice(index, 1);
  42377. }
  42378. if (runtimeAnimations.length == 0) {
  42379. this._scene._activeAnimatables.splice(idx, 1);
  42380. if (this.onAnimationEnd) {
  42381. this.onAnimationEnd();
  42382. }
  42383. }
  42384. }
  42385. }
  42386. else {
  42387. var index = this._scene._activeAnimatables.indexOf(this);
  42388. if (index > -1) {
  42389. this._scene._activeAnimatables.splice(index, 1);
  42390. var runtimeAnimations = this._runtimeAnimations;
  42391. for (var index = 0; index < runtimeAnimations.length; index++) {
  42392. runtimeAnimations[index].dispose();
  42393. }
  42394. if (this.onAnimationEnd) {
  42395. this.onAnimationEnd();
  42396. }
  42397. }
  42398. }
  42399. };
  42400. Animatable.prototype._animate = function (delay) {
  42401. if (this._paused) {
  42402. this.animationStarted = false;
  42403. if (this._pausedDelay === null) {
  42404. this._pausedDelay = delay;
  42405. }
  42406. return true;
  42407. }
  42408. if (this._localDelayOffset === null) {
  42409. this._localDelayOffset = delay;
  42410. }
  42411. else if (this._pausedDelay !== null) {
  42412. this._localDelayOffset += delay - this._pausedDelay;
  42413. this._pausedDelay = null;
  42414. }
  42415. // Animating
  42416. var running = false;
  42417. var runtimeAnimations = this._runtimeAnimations;
  42418. var index;
  42419. for (index = 0; index < runtimeAnimations.length; index++) {
  42420. var animation = runtimeAnimations[index];
  42421. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  42422. running = running || isRunning;
  42423. }
  42424. this.animationStarted = running;
  42425. if (!running) {
  42426. // Remove from active animatables
  42427. index = this._scene._activeAnimatables.indexOf(this);
  42428. this._scene._activeAnimatables.splice(index, 1);
  42429. // Dispose all runtime animations
  42430. for (index = 0; index < runtimeAnimations.length; index++) {
  42431. runtimeAnimations[index].dispose();
  42432. }
  42433. }
  42434. if (!running && this.onAnimationEnd) {
  42435. this.onAnimationEnd();
  42436. this.onAnimationEnd = null;
  42437. }
  42438. return running;
  42439. };
  42440. return Animatable;
  42441. }());
  42442. BABYLON.Animatable = Animatable;
  42443. })(BABYLON || (BABYLON = {}));
  42444. //# sourceMappingURL=babylon.animatable.js.map
  42445. var BABYLON;
  42446. (function (BABYLON) {
  42447. var EasingFunction = /** @class */ (function () {
  42448. function EasingFunction() {
  42449. // Properties
  42450. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  42451. }
  42452. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  42453. get: function () {
  42454. return EasingFunction._EASINGMODE_EASEIN;
  42455. },
  42456. enumerable: true,
  42457. configurable: true
  42458. });
  42459. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  42460. get: function () {
  42461. return EasingFunction._EASINGMODE_EASEOUT;
  42462. },
  42463. enumerable: true,
  42464. configurable: true
  42465. });
  42466. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  42467. get: function () {
  42468. return EasingFunction._EASINGMODE_EASEINOUT;
  42469. },
  42470. enumerable: true,
  42471. configurable: true
  42472. });
  42473. EasingFunction.prototype.setEasingMode = function (easingMode) {
  42474. var n = Math.min(Math.max(easingMode, 0), 2);
  42475. this._easingMode = n;
  42476. };
  42477. EasingFunction.prototype.getEasingMode = function () {
  42478. return this._easingMode;
  42479. };
  42480. EasingFunction.prototype.easeInCore = function (gradient) {
  42481. throw new Error('You must implement this method');
  42482. };
  42483. EasingFunction.prototype.ease = function (gradient) {
  42484. switch (this._easingMode) {
  42485. case EasingFunction.EASINGMODE_EASEIN:
  42486. return this.easeInCore(gradient);
  42487. case EasingFunction.EASINGMODE_EASEOUT:
  42488. return (1 - this.easeInCore(1 - gradient));
  42489. }
  42490. if (gradient >= 0.5) {
  42491. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  42492. }
  42493. return (this.easeInCore(gradient * 2) * 0.5);
  42494. };
  42495. //Statics
  42496. EasingFunction._EASINGMODE_EASEIN = 0;
  42497. EasingFunction._EASINGMODE_EASEOUT = 1;
  42498. EasingFunction._EASINGMODE_EASEINOUT = 2;
  42499. return EasingFunction;
  42500. }());
  42501. BABYLON.EasingFunction = EasingFunction;
  42502. var CircleEase = /** @class */ (function (_super) {
  42503. __extends(CircleEase, _super);
  42504. function CircleEase() {
  42505. return _super !== null && _super.apply(this, arguments) || this;
  42506. }
  42507. CircleEase.prototype.easeInCore = function (gradient) {
  42508. gradient = Math.max(0, Math.min(1, gradient));
  42509. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  42510. };
  42511. return CircleEase;
  42512. }(EasingFunction));
  42513. BABYLON.CircleEase = CircleEase;
  42514. var BackEase = /** @class */ (function (_super) {
  42515. __extends(BackEase, _super);
  42516. function BackEase(amplitude) {
  42517. if (amplitude === void 0) { amplitude = 1; }
  42518. var _this = _super.call(this) || this;
  42519. _this.amplitude = amplitude;
  42520. return _this;
  42521. }
  42522. BackEase.prototype.easeInCore = function (gradient) {
  42523. var num = Math.max(0, this.amplitude);
  42524. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  42525. };
  42526. return BackEase;
  42527. }(EasingFunction));
  42528. BABYLON.BackEase = BackEase;
  42529. var BounceEase = /** @class */ (function (_super) {
  42530. __extends(BounceEase, _super);
  42531. function BounceEase(bounces, bounciness) {
  42532. if (bounces === void 0) { bounces = 3; }
  42533. if (bounciness === void 0) { bounciness = 2; }
  42534. var _this = _super.call(this) || this;
  42535. _this.bounces = bounces;
  42536. _this.bounciness = bounciness;
  42537. return _this;
  42538. }
  42539. BounceEase.prototype.easeInCore = function (gradient) {
  42540. var y = Math.max(0.0, this.bounces);
  42541. var bounciness = this.bounciness;
  42542. if (bounciness <= 1.0) {
  42543. bounciness = 1.001;
  42544. }
  42545. var num9 = Math.pow(bounciness, y);
  42546. var num5 = 1.0 - bounciness;
  42547. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  42548. var num15 = gradient * num4;
  42549. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  42550. var num3 = Math.floor(num65);
  42551. var num13 = num3 + 1.0;
  42552. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  42553. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  42554. var num7 = (num8 + num12) * 0.5;
  42555. var num6 = gradient - num7;
  42556. var num2 = num7 - num8;
  42557. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  42558. };
  42559. return BounceEase;
  42560. }(EasingFunction));
  42561. BABYLON.BounceEase = BounceEase;
  42562. var CubicEase = /** @class */ (function (_super) {
  42563. __extends(CubicEase, _super);
  42564. function CubicEase() {
  42565. return _super !== null && _super.apply(this, arguments) || this;
  42566. }
  42567. CubicEase.prototype.easeInCore = function (gradient) {
  42568. return (gradient * gradient * gradient);
  42569. };
  42570. return CubicEase;
  42571. }(EasingFunction));
  42572. BABYLON.CubicEase = CubicEase;
  42573. var ElasticEase = /** @class */ (function (_super) {
  42574. __extends(ElasticEase, _super);
  42575. function ElasticEase(oscillations, springiness) {
  42576. if (oscillations === void 0) { oscillations = 3; }
  42577. if (springiness === void 0) { springiness = 3; }
  42578. var _this = _super.call(this) || this;
  42579. _this.oscillations = oscillations;
  42580. _this.springiness = springiness;
  42581. return _this;
  42582. }
  42583. ElasticEase.prototype.easeInCore = function (gradient) {
  42584. var num2;
  42585. var num3 = Math.max(0.0, this.oscillations);
  42586. var num = Math.max(0.0, this.springiness);
  42587. if (num == 0) {
  42588. num2 = gradient;
  42589. }
  42590. else {
  42591. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  42592. }
  42593. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  42594. };
  42595. return ElasticEase;
  42596. }(EasingFunction));
  42597. BABYLON.ElasticEase = ElasticEase;
  42598. var ExponentialEase = /** @class */ (function (_super) {
  42599. __extends(ExponentialEase, _super);
  42600. function ExponentialEase(exponent) {
  42601. if (exponent === void 0) { exponent = 2; }
  42602. var _this = _super.call(this) || this;
  42603. _this.exponent = exponent;
  42604. return _this;
  42605. }
  42606. ExponentialEase.prototype.easeInCore = function (gradient) {
  42607. if (this.exponent <= 0) {
  42608. return gradient;
  42609. }
  42610. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  42611. };
  42612. return ExponentialEase;
  42613. }(EasingFunction));
  42614. BABYLON.ExponentialEase = ExponentialEase;
  42615. var PowerEase = /** @class */ (function (_super) {
  42616. __extends(PowerEase, _super);
  42617. function PowerEase(power) {
  42618. if (power === void 0) { power = 2; }
  42619. var _this = _super.call(this) || this;
  42620. _this.power = power;
  42621. return _this;
  42622. }
  42623. PowerEase.prototype.easeInCore = function (gradient) {
  42624. var y = Math.max(0.0, this.power);
  42625. return Math.pow(gradient, y);
  42626. };
  42627. return PowerEase;
  42628. }(EasingFunction));
  42629. BABYLON.PowerEase = PowerEase;
  42630. var QuadraticEase = /** @class */ (function (_super) {
  42631. __extends(QuadraticEase, _super);
  42632. function QuadraticEase() {
  42633. return _super !== null && _super.apply(this, arguments) || this;
  42634. }
  42635. QuadraticEase.prototype.easeInCore = function (gradient) {
  42636. return (gradient * gradient);
  42637. };
  42638. return QuadraticEase;
  42639. }(EasingFunction));
  42640. BABYLON.QuadraticEase = QuadraticEase;
  42641. var QuarticEase = /** @class */ (function (_super) {
  42642. __extends(QuarticEase, _super);
  42643. function QuarticEase() {
  42644. return _super !== null && _super.apply(this, arguments) || this;
  42645. }
  42646. QuarticEase.prototype.easeInCore = function (gradient) {
  42647. return (gradient * gradient * gradient * gradient);
  42648. };
  42649. return QuarticEase;
  42650. }(EasingFunction));
  42651. BABYLON.QuarticEase = QuarticEase;
  42652. var QuinticEase = /** @class */ (function (_super) {
  42653. __extends(QuinticEase, _super);
  42654. function QuinticEase() {
  42655. return _super !== null && _super.apply(this, arguments) || this;
  42656. }
  42657. QuinticEase.prototype.easeInCore = function (gradient) {
  42658. return (gradient * gradient * gradient * gradient * gradient);
  42659. };
  42660. return QuinticEase;
  42661. }(EasingFunction));
  42662. BABYLON.QuinticEase = QuinticEase;
  42663. var SineEase = /** @class */ (function (_super) {
  42664. __extends(SineEase, _super);
  42665. function SineEase() {
  42666. return _super !== null && _super.apply(this, arguments) || this;
  42667. }
  42668. SineEase.prototype.easeInCore = function (gradient) {
  42669. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  42670. };
  42671. return SineEase;
  42672. }(EasingFunction));
  42673. BABYLON.SineEase = SineEase;
  42674. var BezierCurveEase = /** @class */ (function (_super) {
  42675. __extends(BezierCurveEase, _super);
  42676. function BezierCurveEase(x1, y1, x2, y2) {
  42677. if (x1 === void 0) { x1 = 0; }
  42678. if (y1 === void 0) { y1 = 0; }
  42679. if (x2 === void 0) { x2 = 1; }
  42680. if (y2 === void 0) { y2 = 1; }
  42681. var _this = _super.call(this) || this;
  42682. _this.x1 = x1;
  42683. _this.y1 = y1;
  42684. _this.x2 = x2;
  42685. _this.y2 = y2;
  42686. return _this;
  42687. }
  42688. BezierCurveEase.prototype.easeInCore = function (gradient) {
  42689. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  42690. };
  42691. return BezierCurveEase;
  42692. }(EasingFunction));
  42693. BABYLON.BezierCurveEase = BezierCurveEase;
  42694. })(BABYLON || (BABYLON = {}));
  42695. //# sourceMappingURL=babylon.easing.js.map
  42696. var BABYLON;
  42697. (function (BABYLON) {
  42698. var Condition = /** @class */ (function () {
  42699. function Condition(actionManager) {
  42700. this._actionManager = actionManager;
  42701. }
  42702. Condition.prototype.isValid = function () {
  42703. return true;
  42704. };
  42705. Condition.prototype._getProperty = function (propertyPath) {
  42706. return this._actionManager._getProperty(propertyPath);
  42707. };
  42708. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  42709. return this._actionManager._getEffectiveTarget(target, propertyPath);
  42710. };
  42711. Condition.prototype.serialize = function () {
  42712. };
  42713. Condition.prototype._serialize = function (serializedCondition) {
  42714. return {
  42715. type: 2,
  42716. children: [],
  42717. name: serializedCondition.name,
  42718. properties: serializedCondition.properties
  42719. };
  42720. };
  42721. return Condition;
  42722. }());
  42723. BABYLON.Condition = Condition;
  42724. var ValueCondition = /** @class */ (function (_super) {
  42725. __extends(ValueCondition, _super);
  42726. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  42727. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  42728. var _this = _super.call(this, actionManager) || this;
  42729. _this.propertyPath = propertyPath;
  42730. _this.value = value;
  42731. _this.operator = operator;
  42732. _this._target = target;
  42733. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  42734. _this._property = _this._getProperty(_this.propertyPath);
  42735. return _this;
  42736. }
  42737. Object.defineProperty(ValueCondition, "IsEqual", {
  42738. get: function () {
  42739. return ValueCondition._IsEqual;
  42740. },
  42741. enumerable: true,
  42742. configurable: true
  42743. });
  42744. Object.defineProperty(ValueCondition, "IsDifferent", {
  42745. get: function () {
  42746. return ValueCondition._IsDifferent;
  42747. },
  42748. enumerable: true,
  42749. configurable: true
  42750. });
  42751. Object.defineProperty(ValueCondition, "IsGreater", {
  42752. get: function () {
  42753. return ValueCondition._IsGreater;
  42754. },
  42755. enumerable: true,
  42756. configurable: true
  42757. });
  42758. Object.defineProperty(ValueCondition, "IsLesser", {
  42759. get: function () {
  42760. return ValueCondition._IsLesser;
  42761. },
  42762. enumerable: true,
  42763. configurable: true
  42764. });
  42765. // Methods
  42766. ValueCondition.prototype.isValid = function () {
  42767. switch (this.operator) {
  42768. case ValueCondition.IsGreater:
  42769. return this._effectiveTarget[this._property] > this.value;
  42770. case ValueCondition.IsLesser:
  42771. return this._effectiveTarget[this._property] < this.value;
  42772. case ValueCondition.IsEqual:
  42773. case ValueCondition.IsDifferent:
  42774. var check;
  42775. if (this.value.equals) {
  42776. check = this.value.equals(this._effectiveTarget[this._property]);
  42777. }
  42778. else {
  42779. check = this.value === this._effectiveTarget[this._property];
  42780. }
  42781. return this.operator === ValueCondition.IsEqual ? check : !check;
  42782. }
  42783. return false;
  42784. };
  42785. ValueCondition.prototype.serialize = function () {
  42786. return this._serialize({
  42787. name: "ValueCondition",
  42788. properties: [
  42789. BABYLON.Action._GetTargetProperty(this._target),
  42790. { name: "propertyPath", value: this.propertyPath },
  42791. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  42792. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  42793. ]
  42794. });
  42795. };
  42796. ValueCondition.GetOperatorName = function (operator) {
  42797. switch (operator) {
  42798. case ValueCondition._IsEqual: return "IsEqual";
  42799. case ValueCondition._IsDifferent: return "IsDifferent";
  42800. case ValueCondition._IsGreater: return "IsGreater";
  42801. case ValueCondition._IsLesser: return "IsLesser";
  42802. default: return "";
  42803. }
  42804. };
  42805. // Statics
  42806. ValueCondition._IsEqual = 0;
  42807. ValueCondition._IsDifferent = 1;
  42808. ValueCondition._IsGreater = 2;
  42809. ValueCondition._IsLesser = 3;
  42810. return ValueCondition;
  42811. }(Condition));
  42812. BABYLON.ValueCondition = ValueCondition;
  42813. var PredicateCondition = /** @class */ (function (_super) {
  42814. __extends(PredicateCondition, _super);
  42815. function PredicateCondition(actionManager, predicate) {
  42816. var _this = _super.call(this, actionManager) || this;
  42817. _this.predicate = predicate;
  42818. return _this;
  42819. }
  42820. PredicateCondition.prototype.isValid = function () {
  42821. return this.predicate();
  42822. };
  42823. return PredicateCondition;
  42824. }(Condition));
  42825. BABYLON.PredicateCondition = PredicateCondition;
  42826. var StateCondition = /** @class */ (function (_super) {
  42827. __extends(StateCondition, _super);
  42828. function StateCondition(actionManager, target, value) {
  42829. var _this = _super.call(this, actionManager) || this;
  42830. _this.value = value;
  42831. _this._target = target;
  42832. return _this;
  42833. }
  42834. // Methods
  42835. StateCondition.prototype.isValid = function () {
  42836. return this._target.state === this.value;
  42837. };
  42838. StateCondition.prototype.serialize = function () {
  42839. return this._serialize({
  42840. name: "StateCondition",
  42841. properties: [
  42842. BABYLON.Action._GetTargetProperty(this._target),
  42843. { name: "value", value: this.value }
  42844. ]
  42845. });
  42846. };
  42847. return StateCondition;
  42848. }(Condition));
  42849. BABYLON.StateCondition = StateCondition;
  42850. })(BABYLON || (BABYLON = {}));
  42851. //# sourceMappingURL=babylon.condition.js.map
  42852. var BABYLON;
  42853. (function (BABYLON) {
  42854. var Action = /** @class */ (function () {
  42855. function Action(triggerOptions, condition) {
  42856. this.triggerOptions = triggerOptions;
  42857. this.onBeforeExecuteObservable = new BABYLON.Observable();
  42858. if (triggerOptions.parameter) {
  42859. this.trigger = triggerOptions.trigger;
  42860. this._triggerParameter = triggerOptions.parameter;
  42861. }
  42862. else {
  42863. this.trigger = triggerOptions;
  42864. }
  42865. this._nextActiveAction = this;
  42866. this._condition = condition;
  42867. }
  42868. // Methods
  42869. Action.prototype._prepare = function () {
  42870. };
  42871. Action.prototype.getTriggerParameter = function () {
  42872. return this._triggerParameter;
  42873. };
  42874. Action.prototype._executeCurrent = function (evt) {
  42875. if (this._nextActiveAction._condition) {
  42876. var condition = this._nextActiveAction._condition;
  42877. var currentRenderId = this._actionManager.getScene().getRenderId();
  42878. // We cache the current evaluation for the current frame
  42879. if (condition._evaluationId === currentRenderId) {
  42880. if (!condition._currentResult) {
  42881. return;
  42882. }
  42883. }
  42884. else {
  42885. condition._evaluationId = currentRenderId;
  42886. if (!condition.isValid()) {
  42887. condition._currentResult = false;
  42888. return;
  42889. }
  42890. condition._currentResult = true;
  42891. }
  42892. }
  42893. this.onBeforeExecuteObservable.notifyObservers(this);
  42894. this._nextActiveAction.execute(evt);
  42895. this.skipToNextActiveAction();
  42896. };
  42897. Action.prototype.execute = function (evt) {
  42898. };
  42899. Action.prototype.skipToNextActiveAction = function () {
  42900. if (this._nextActiveAction._child) {
  42901. if (!this._nextActiveAction._child._actionManager) {
  42902. this._nextActiveAction._child._actionManager = this._actionManager;
  42903. }
  42904. this._nextActiveAction = this._nextActiveAction._child;
  42905. }
  42906. else {
  42907. this._nextActiveAction = this;
  42908. }
  42909. };
  42910. Action.prototype.then = function (action) {
  42911. this._child = action;
  42912. action._actionManager = this._actionManager;
  42913. action._prepare();
  42914. return action;
  42915. };
  42916. Action.prototype._getProperty = function (propertyPath) {
  42917. return this._actionManager._getProperty(propertyPath);
  42918. };
  42919. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  42920. return this._actionManager._getEffectiveTarget(target, propertyPath);
  42921. };
  42922. Action.prototype.serialize = function (parent) {
  42923. };
  42924. // Called by BABYLON.Action objects in serialize(...). Internal use
  42925. Action.prototype._serialize = function (serializedAction, parent) {
  42926. var serializationObject = {
  42927. type: 1,
  42928. children: [],
  42929. name: serializedAction.name,
  42930. properties: serializedAction.properties || []
  42931. };
  42932. // Serialize child
  42933. if (this._child) {
  42934. this._child.serialize(serializationObject);
  42935. }
  42936. // Check if "this" has a condition
  42937. if (this._condition) {
  42938. var serializedCondition = this._condition.serialize();
  42939. serializedCondition.children.push(serializationObject);
  42940. if (parent) {
  42941. parent.children.push(serializedCondition);
  42942. }
  42943. return serializedCondition;
  42944. }
  42945. if (parent) {
  42946. parent.children.push(serializationObject);
  42947. }
  42948. return serializationObject;
  42949. };
  42950. Action._SerializeValueAsString = function (value) {
  42951. if (typeof value === "number") {
  42952. return value.toString();
  42953. }
  42954. if (typeof value === "boolean") {
  42955. return value ? "true" : "false";
  42956. }
  42957. if (value instanceof BABYLON.Vector2) {
  42958. return value.x + ", " + value.y;
  42959. }
  42960. if (value instanceof BABYLON.Vector3) {
  42961. return value.x + ", " + value.y + ", " + value.z;
  42962. }
  42963. if (value instanceof BABYLON.Color3) {
  42964. return value.r + ", " + value.g + ", " + value.b;
  42965. }
  42966. if (value instanceof BABYLON.Color4) {
  42967. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  42968. }
  42969. return value; // string
  42970. };
  42971. Action._GetTargetProperty = function (target) {
  42972. return {
  42973. name: "target",
  42974. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  42975. : target instanceof BABYLON.Light ? "LightProperties"
  42976. : target instanceof BABYLON.Camera ? "CameraProperties"
  42977. : "SceneProperties",
  42978. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  42979. };
  42980. };
  42981. return Action;
  42982. }());
  42983. BABYLON.Action = Action;
  42984. })(BABYLON || (BABYLON = {}));
  42985. //# sourceMappingURL=babylon.action.js.map
  42986. var BABYLON;
  42987. (function (BABYLON) {
  42988. /**
  42989. * ActionEvent is the event beint sent when an action is triggered.
  42990. */
  42991. var ActionEvent = /** @class */ (function () {
  42992. /**
  42993. * @param source The mesh or sprite that triggered the action.
  42994. * @param pointerX The X mouse cursor position at the time of the event
  42995. * @param pointerY The Y mouse cursor position at the time of the event
  42996. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  42997. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  42998. */
  42999. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  43000. this.source = source;
  43001. this.pointerX = pointerX;
  43002. this.pointerY = pointerY;
  43003. this.meshUnderPointer = meshUnderPointer;
  43004. this.sourceEvent = sourceEvent;
  43005. this.additionalData = additionalData;
  43006. }
  43007. /**
  43008. * Helper function to auto-create an ActionEvent from a source mesh.
  43009. * @param source The source mesh that triggered the event
  43010. * @param evt {Event} The original (browser) event
  43011. */
  43012. ActionEvent.CreateNew = function (source, evt, additionalData) {
  43013. var scene = source.getScene();
  43014. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  43015. };
  43016. /**
  43017. * Helper function to auto-create an ActionEvent from a source mesh.
  43018. * @param source The source sprite that triggered the event
  43019. * @param scene Scene associated with the sprite
  43020. * @param evt {Event} The original (browser) event
  43021. */
  43022. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  43023. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  43024. };
  43025. /**
  43026. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  43027. * @param scene the scene where the event occurred
  43028. * @param evt {Event} The original (browser) event
  43029. */
  43030. ActionEvent.CreateNewFromScene = function (scene, evt) {
  43031. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  43032. };
  43033. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  43034. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  43035. };
  43036. return ActionEvent;
  43037. }());
  43038. BABYLON.ActionEvent = ActionEvent;
  43039. /**
  43040. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  43041. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  43042. */
  43043. var ActionManager = /** @class */ (function () {
  43044. function ActionManager(scene) {
  43045. // Members
  43046. this.actions = new Array();
  43047. this.hoverCursor = '';
  43048. this._scene = scene;
  43049. scene._actionManagers.push(this);
  43050. }
  43051. Object.defineProperty(ActionManager, "NothingTrigger", {
  43052. get: function () {
  43053. return ActionManager._NothingTrigger;
  43054. },
  43055. enumerable: true,
  43056. configurable: true
  43057. });
  43058. Object.defineProperty(ActionManager, "OnPickTrigger", {
  43059. get: function () {
  43060. return ActionManager._OnPickTrigger;
  43061. },
  43062. enumerable: true,
  43063. configurable: true
  43064. });
  43065. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  43066. get: function () {
  43067. return ActionManager._OnLeftPickTrigger;
  43068. },
  43069. enumerable: true,
  43070. configurable: true
  43071. });
  43072. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  43073. get: function () {
  43074. return ActionManager._OnRightPickTrigger;
  43075. },
  43076. enumerable: true,
  43077. configurable: true
  43078. });
  43079. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  43080. get: function () {
  43081. return ActionManager._OnCenterPickTrigger;
  43082. },
  43083. enumerable: true,
  43084. configurable: true
  43085. });
  43086. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  43087. get: function () {
  43088. return ActionManager._OnPickDownTrigger;
  43089. },
  43090. enumerable: true,
  43091. configurable: true
  43092. });
  43093. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  43094. get: function () {
  43095. return ActionManager._OnDoublePickTrigger;
  43096. },
  43097. enumerable: true,
  43098. configurable: true
  43099. });
  43100. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  43101. get: function () {
  43102. return ActionManager._OnPickUpTrigger;
  43103. },
  43104. enumerable: true,
  43105. configurable: true
  43106. });
  43107. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  43108. /// This trigger will only be raised if you also declared a OnPickDown
  43109. get: function () {
  43110. return ActionManager._OnPickOutTrigger;
  43111. },
  43112. enumerable: true,
  43113. configurable: true
  43114. });
  43115. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  43116. get: function () {
  43117. return ActionManager._OnLongPressTrigger;
  43118. },
  43119. enumerable: true,
  43120. configurable: true
  43121. });
  43122. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  43123. get: function () {
  43124. return ActionManager._OnPointerOverTrigger;
  43125. },
  43126. enumerable: true,
  43127. configurable: true
  43128. });
  43129. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  43130. get: function () {
  43131. return ActionManager._OnPointerOutTrigger;
  43132. },
  43133. enumerable: true,
  43134. configurable: true
  43135. });
  43136. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  43137. get: function () {
  43138. return ActionManager._OnEveryFrameTrigger;
  43139. },
  43140. enumerable: true,
  43141. configurable: true
  43142. });
  43143. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  43144. get: function () {
  43145. return ActionManager._OnIntersectionEnterTrigger;
  43146. },
  43147. enumerable: true,
  43148. configurable: true
  43149. });
  43150. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  43151. get: function () {
  43152. return ActionManager._OnIntersectionExitTrigger;
  43153. },
  43154. enumerable: true,
  43155. configurable: true
  43156. });
  43157. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  43158. get: function () {
  43159. return ActionManager._OnKeyDownTrigger;
  43160. },
  43161. enumerable: true,
  43162. configurable: true
  43163. });
  43164. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  43165. get: function () {
  43166. return ActionManager._OnKeyUpTrigger;
  43167. },
  43168. enumerable: true,
  43169. configurable: true
  43170. });
  43171. // Methods
  43172. ActionManager.prototype.dispose = function () {
  43173. var index = this._scene._actionManagers.indexOf(this);
  43174. for (var i = 0; i < this.actions.length; i++) {
  43175. var action = this.actions[i];
  43176. ActionManager.Triggers[action.trigger]--;
  43177. if (ActionManager.Triggers[action.trigger] === 0) {
  43178. delete ActionManager.Triggers[action.trigger];
  43179. }
  43180. }
  43181. if (index > -1) {
  43182. this._scene._actionManagers.splice(index, 1);
  43183. }
  43184. };
  43185. ActionManager.prototype.getScene = function () {
  43186. return this._scene;
  43187. };
  43188. /**
  43189. * Does this action manager handles actions of any of the given triggers
  43190. * @param {number[]} triggers - the triggers to be tested
  43191. * @return {boolean} whether one (or more) of the triggers is handeled
  43192. */
  43193. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  43194. for (var index = 0; index < this.actions.length; index++) {
  43195. var action = this.actions[index];
  43196. if (triggers.indexOf(action.trigger) > -1) {
  43197. return true;
  43198. }
  43199. }
  43200. return false;
  43201. };
  43202. /**
  43203. * Does this action manager handles actions of a given trigger
  43204. * @param {number} trigger - the trigger to be tested
  43205. * @return {boolean} whether the trigger is handeled
  43206. */
  43207. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  43208. for (var index = 0; index < this.actions.length; index++) {
  43209. var action = this.actions[index];
  43210. if (action.trigger === trigger) {
  43211. return true;
  43212. }
  43213. }
  43214. return false;
  43215. };
  43216. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  43217. /**
  43218. * Does this action manager has pointer triggers
  43219. * @return {boolean} whether or not it has pointer triggers
  43220. */
  43221. get: function () {
  43222. for (var index = 0; index < this.actions.length; index++) {
  43223. var action = this.actions[index];
  43224. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  43225. return true;
  43226. }
  43227. }
  43228. return false;
  43229. },
  43230. enumerable: true,
  43231. configurable: true
  43232. });
  43233. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  43234. /**
  43235. * Does this action manager has pick triggers
  43236. * @return {boolean} whether or not it has pick triggers
  43237. */
  43238. get: function () {
  43239. for (var index = 0; index < this.actions.length; index++) {
  43240. var action = this.actions[index];
  43241. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  43242. return true;
  43243. }
  43244. }
  43245. return false;
  43246. },
  43247. enumerable: true,
  43248. configurable: true
  43249. });
  43250. Object.defineProperty(ActionManager, "HasTriggers", {
  43251. /**
  43252. * Does exist one action manager with at least one trigger
  43253. * @return {boolean} whether or not it exists one action manager with one trigger
  43254. **/
  43255. get: function () {
  43256. for (var t in ActionManager.Triggers) {
  43257. if (ActionManager.Triggers.hasOwnProperty(t)) {
  43258. return true;
  43259. }
  43260. }
  43261. return false;
  43262. },
  43263. enumerable: true,
  43264. configurable: true
  43265. });
  43266. Object.defineProperty(ActionManager, "HasPickTriggers", {
  43267. /**
  43268. * Does exist one action manager with at least one pick trigger
  43269. * @return {boolean} whether or not it exists one action manager with one pick trigger
  43270. **/
  43271. get: function () {
  43272. for (var t in ActionManager.Triggers) {
  43273. if (ActionManager.Triggers.hasOwnProperty(t)) {
  43274. var t_int = parseInt(t);
  43275. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  43276. return true;
  43277. }
  43278. }
  43279. }
  43280. return false;
  43281. },
  43282. enumerable: true,
  43283. configurable: true
  43284. });
  43285. /**
  43286. * Does exist one action manager that handles actions of a given trigger
  43287. * @param {number} trigger - the trigger to be tested
  43288. * @return {boolean} whether the trigger is handeled by at least one action manager
  43289. **/
  43290. ActionManager.HasSpecificTrigger = function (trigger) {
  43291. for (var t in ActionManager.Triggers) {
  43292. if (ActionManager.Triggers.hasOwnProperty(t)) {
  43293. var t_int = parseInt(t);
  43294. if (t_int === trigger) {
  43295. return true;
  43296. }
  43297. }
  43298. }
  43299. return false;
  43300. };
  43301. /**
  43302. * Registers an action to this action manager
  43303. * @param {BABYLON.Action} action - the action to be registered
  43304. * @return {BABYLON.Action} the action amended (prepared) after registration
  43305. */
  43306. ActionManager.prototype.registerAction = function (action) {
  43307. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  43308. if (this.getScene().actionManager !== this) {
  43309. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  43310. return null;
  43311. }
  43312. }
  43313. this.actions.push(action);
  43314. if (ActionManager.Triggers[action.trigger]) {
  43315. ActionManager.Triggers[action.trigger]++;
  43316. }
  43317. else {
  43318. ActionManager.Triggers[action.trigger] = 1;
  43319. }
  43320. action._actionManager = this;
  43321. action._prepare();
  43322. return action;
  43323. };
  43324. /**
  43325. * Process a specific trigger
  43326. * @param {number} trigger - the trigger to process
  43327. * @param evt {BABYLON.ActionEvent} the event details to be processed
  43328. */
  43329. ActionManager.prototype.processTrigger = function (trigger, evt) {
  43330. for (var index = 0; index < this.actions.length; index++) {
  43331. var action = this.actions[index];
  43332. if (action.trigger === trigger) {
  43333. if (evt) {
  43334. if (trigger === ActionManager.OnKeyUpTrigger
  43335. || trigger === ActionManager.OnKeyDownTrigger) {
  43336. var parameter = action.getTriggerParameter();
  43337. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  43338. if (!parameter.toLowerCase) {
  43339. continue;
  43340. }
  43341. var lowerCase = parameter.toLowerCase();
  43342. if (lowerCase !== evt.sourceEvent.key) {
  43343. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  43344. var actualkey = String.fromCharCode(unicode).toLowerCase();
  43345. if (actualkey !== lowerCase) {
  43346. continue;
  43347. }
  43348. }
  43349. }
  43350. }
  43351. }
  43352. action._executeCurrent(evt);
  43353. }
  43354. }
  43355. };
  43356. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  43357. var properties = propertyPath.split(".");
  43358. for (var index = 0; index < properties.length - 1; index++) {
  43359. target = target[properties[index]];
  43360. }
  43361. return target;
  43362. };
  43363. ActionManager.prototype._getProperty = function (propertyPath) {
  43364. var properties = propertyPath.split(".");
  43365. return properties[properties.length - 1];
  43366. };
  43367. ActionManager.prototype.serialize = function (name) {
  43368. var root = {
  43369. children: new Array(),
  43370. name: name,
  43371. type: 3,
  43372. properties: new Array() // Empty for root but required
  43373. };
  43374. for (var i = 0; i < this.actions.length; i++) {
  43375. var triggerObject = {
  43376. type: 0,
  43377. children: new Array(),
  43378. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  43379. properties: new Array()
  43380. };
  43381. var triggerOptions = this.actions[i].triggerOptions;
  43382. if (triggerOptions && typeof triggerOptions !== "number") {
  43383. if (triggerOptions.parameter instanceof BABYLON.Node) {
  43384. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  43385. }
  43386. else {
  43387. var parameter = {};
  43388. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  43389. if (triggerOptions.parameter.mesh) {
  43390. parameter._meshId = triggerOptions.parameter.mesh.id;
  43391. }
  43392. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  43393. }
  43394. }
  43395. // Serialize child action, recursively
  43396. this.actions[i].serialize(triggerObject);
  43397. // Add serialized trigger
  43398. root.children.push(triggerObject);
  43399. }
  43400. return root;
  43401. };
  43402. ActionManager.Parse = function (parsedActions, object, scene) {
  43403. var actionManager = new ActionManager(scene);
  43404. if (object === null)
  43405. scene.actionManager = actionManager;
  43406. else
  43407. object.actionManager = actionManager;
  43408. // instanciate a new object
  43409. var instanciate = function (name, params) {
  43410. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  43411. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  43412. newInstance.constructor.apply(newInstance, params);
  43413. return newInstance;
  43414. };
  43415. var parseParameter = function (name, value, target, propertyPath) {
  43416. if (propertyPath === null) {
  43417. // String, boolean or float
  43418. var floatValue = parseFloat(value);
  43419. if (value === "true" || value === "false")
  43420. return value === "true";
  43421. else
  43422. return isNaN(floatValue) ? value : floatValue;
  43423. }
  43424. var effectiveTarget = propertyPath.split(".");
  43425. var values = value.split(",");
  43426. // Get effective Target
  43427. for (var i = 0; i < effectiveTarget.length; i++) {
  43428. target = target[effectiveTarget[i]];
  43429. }
  43430. // Return appropriate value with its type
  43431. if (typeof (target) === "boolean")
  43432. return values[0] === "true";
  43433. if (typeof (target) === "string")
  43434. return values[0];
  43435. // Parameters with multiple values such as Vector3 etc.
  43436. var split = new Array();
  43437. for (var i = 0; i < values.length; i++)
  43438. split.push(parseFloat(values[i]));
  43439. if (target instanceof BABYLON.Vector3)
  43440. return BABYLON.Vector3.FromArray(split);
  43441. if (target instanceof BABYLON.Vector4)
  43442. return BABYLON.Vector4.FromArray(split);
  43443. if (target instanceof BABYLON.Color3)
  43444. return BABYLON.Color3.FromArray(split);
  43445. if (target instanceof BABYLON.Color4)
  43446. return BABYLON.Color4.FromArray(split);
  43447. return parseFloat(values[0]);
  43448. };
  43449. // traverse graph per trigger
  43450. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  43451. if (combineArray === void 0) { combineArray = null; }
  43452. if (parsedAction.detached)
  43453. return;
  43454. var parameters = new Array();
  43455. var target = null;
  43456. var propertyPath = null;
  43457. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  43458. // Parameters
  43459. if (parsedAction.type === 2)
  43460. parameters.push(actionManager);
  43461. else
  43462. parameters.push(trigger);
  43463. if (combine) {
  43464. var actions = new Array();
  43465. for (var j = 0; j < parsedAction.combine.length; j++) {
  43466. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  43467. }
  43468. parameters.push(actions);
  43469. }
  43470. else {
  43471. for (var i = 0; i < parsedAction.properties.length; i++) {
  43472. var value = parsedAction.properties[i].value;
  43473. var name = parsedAction.properties[i].name;
  43474. var targetType = parsedAction.properties[i].targetType;
  43475. if (name === "target")
  43476. if (targetType !== null && targetType === "SceneProperties")
  43477. value = target = scene;
  43478. else
  43479. value = target = scene.getNodeByName(value);
  43480. else if (name === "parent")
  43481. value = scene.getNodeByName(value);
  43482. else if (name === "sound")
  43483. value = scene.getSoundByName(value);
  43484. else if (name !== "propertyPath") {
  43485. if (parsedAction.type === 2 && name === "operator")
  43486. value = BABYLON.ValueCondition[value];
  43487. else
  43488. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  43489. }
  43490. else {
  43491. propertyPath = value;
  43492. }
  43493. parameters.push(value);
  43494. }
  43495. }
  43496. if (combineArray === null) {
  43497. parameters.push(condition);
  43498. }
  43499. else {
  43500. parameters.push(null);
  43501. }
  43502. // If interpolate value action
  43503. if (parsedAction.name === "InterpolateValueAction") {
  43504. var param = parameters[parameters.length - 2];
  43505. parameters[parameters.length - 1] = param;
  43506. parameters[parameters.length - 2] = condition;
  43507. }
  43508. // Action or condition(s) and not CombineAction
  43509. var newAction = instanciate(parsedAction.name, parameters);
  43510. if (newAction instanceof BABYLON.Condition && condition !== null) {
  43511. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  43512. if (action)
  43513. action.then(nothing);
  43514. else
  43515. actionManager.registerAction(nothing);
  43516. action = nothing;
  43517. }
  43518. if (combineArray === null) {
  43519. if (newAction instanceof BABYLON.Condition) {
  43520. condition = newAction;
  43521. newAction = action;
  43522. }
  43523. else {
  43524. condition = null;
  43525. if (action)
  43526. action.then(newAction);
  43527. else
  43528. actionManager.registerAction(newAction);
  43529. }
  43530. }
  43531. else {
  43532. combineArray.push(newAction);
  43533. }
  43534. for (var i = 0; i < parsedAction.children.length; i++)
  43535. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  43536. };
  43537. // triggers
  43538. for (var i = 0; i < parsedActions.children.length; i++) {
  43539. var triggerParams;
  43540. var trigger = parsedActions.children[i];
  43541. if (trigger.properties.length > 0) {
  43542. var param = trigger.properties[0].value;
  43543. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  43544. if (value._meshId) {
  43545. value.mesh = scene.getMeshByID(value._meshId);
  43546. }
  43547. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  43548. }
  43549. else
  43550. triggerParams = ActionManager[trigger.name];
  43551. for (var j = 0; j < trigger.children.length; j++) {
  43552. if (!trigger.detached)
  43553. traverse(trigger.children[j], triggerParams, null, null);
  43554. }
  43555. }
  43556. };
  43557. ActionManager.GetTriggerName = function (trigger) {
  43558. switch (trigger) {
  43559. case 0: return "NothingTrigger";
  43560. case 1: return "OnPickTrigger";
  43561. case 2: return "OnLeftPickTrigger";
  43562. case 3: return "OnRightPickTrigger";
  43563. case 4: return "OnCenterPickTrigger";
  43564. case 5: return "OnPickDownTrigger";
  43565. case 6: return "OnPickUpTrigger";
  43566. case 7: return "OnLongPressTrigger";
  43567. case 8: return "OnPointerOverTrigger";
  43568. case 9: return "OnPointerOutTrigger";
  43569. case 10: return "OnEveryFrameTrigger";
  43570. case 11: return "OnIntersectionEnterTrigger";
  43571. case 12: return "OnIntersectionExitTrigger";
  43572. case 13: return "OnKeyDownTrigger";
  43573. case 14: return "OnKeyUpTrigger";
  43574. case 15: return "OnPickOutTrigger";
  43575. default: return "";
  43576. }
  43577. };
  43578. // Statics
  43579. ActionManager._NothingTrigger = 0;
  43580. ActionManager._OnPickTrigger = 1;
  43581. ActionManager._OnLeftPickTrigger = 2;
  43582. ActionManager._OnRightPickTrigger = 3;
  43583. ActionManager._OnCenterPickTrigger = 4;
  43584. ActionManager._OnPickDownTrigger = 5;
  43585. ActionManager._OnDoublePickTrigger = 6;
  43586. ActionManager._OnPickUpTrigger = 7;
  43587. ActionManager._OnLongPressTrigger = 8;
  43588. ActionManager._OnPointerOverTrigger = 9;
  43589. ActionManager._OnPointerOutTrigger = 10;
  43590. ActionManager._OnEveryFrameTrigger = 11;
  43591. ActionManager._OnIntersectionEnterTrigger = 12;
  43592. ActionManager._OnIntersectionExitTrigger = 13;
  43593. ActionManager._OnKeyDownTrigger = 14;
  43594. ActionManager._OnKeyUpTrigger = 15;
  43595. ActionManager._OnPickOutTrigger = 16;
  43596. ActionManager.Triggers = {};
  43597. return ActionManager;
  43598. }());
  43599. BABYLON.ActionManager = ActionManager;
  43600. })(BABYLON || (BABYLON = {}));
  43601. //# sourceMappingURL=babylon.actionManager.js.map
  43602. var BABYLON;
  43603. (function (BABYLON) {
  43604. var InterpolateValueAction = /** @class */ (function (_super) {
  43605. __extends(InterpolateValueAction, _super);
  43606. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  43607. if (duration === void 0) { duration = 1000; }
  43608. var _this = _super.call(this, triggerOptions, condition) || this;
  43609. _this.propertyPath = propertyPath;
  43610. _this.value = value;
  43611. _this.duration = duration;
  43612. _this.stopOtherAnimations = stopOtherAnimations;
  43613. _this.onInterpolationDone = onInterpolationDone;
  43614. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  43615. _this._target = _this._effectiveTarget = target;
  43616. return _this;
  43617. }
  43618. InterpolateValueAction.prototype._prepare = function () {
  43619. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  43620. this._property = this._getProperty(this.propertyPath);
  43621. };
  43622. InterpolateValueAction.prototype.execute = function () {
  43623. var _this = this;
  43624. var scene = this._actionManager.getScene();
  43625. var keys = [
  43626. {
  43627. frame: 0,
  43628. value: this._effectiveTarget[this._property]
  43629. }, {
  43630. frame: 100,
  43631. value: this.value
  43632. }
  43633. ];
  43634. var dataType;
  43635. if (typeof this.value === "number") {
  43636. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  43637. }
  43638. else if (this.value instanceof BABYLON.Color3) {
  43639. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  43640. }
  43641. else if (this.value instanceof BABYLON.Vector3) {
  43642. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  43643. }
  43644. else if (this.value instanceof BABYLON.Matrix) {
  43645. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  43646. }
  43647. else if (this.value instanceof BABYLON.Quaternion) {
  43648. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  43649. }
  43650. else {
  43651. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  43652. return;
  43653. }
  43654. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  43655. animation.setKeys(keys);
  43656. if (this.stopOtherAnimations) {
  43657. scene.stopAnimation(this._effectiveTarget);
  43658. }
  43659. var wrapper = function () {
  43660. _this.onInterpolationDoneObservable.notifyObservers(_this);
  43661. if (_this.onInterpolationDone) {
  43662. _this.onInterpolationDone();
  43663. }
  43664. };
  43665. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  43666. };
  43667. InterpolateValueAction.prototype.serialize = function (parent) {
  43668. return _super.prototype._serialize.call(this, {
  43669. name: "InterpolateValueAction",
  43670. properties: [
  43671. BABYLON.Action._GetTargetProperty(this._target),
  43672. { name: "propertyPath", value: this.propertyPath },
  43673. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  43674. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  43675. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  43676. ]
  43677. }, parent);
  43678. };
  43679. return InterpolateValueAction;
  43680. }(BABYLON.Action));
  43681. BABYLON.InterpolateValueAction = InterpolateValueAction;
  43682. })(BABYLON || (BABYLON = {}));
  43683. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  43684. var BABYLON;
  43685. (function (BABYLON) {
  43686. var SwitchBooleanAction = /** @class */ (function (_super) {
  43687. __extends(SwitchBooleanAction, _super);
  43688. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  43689. var _this = _super.call(this, triggerOptions, condition) || this;
  43690. _this.propertyPath = propertyPath;
  43691. _this._target = _this._effectiveTarget = target;
  43692. return _this;
  43693. }
  43694. SwitchBooleanAction.prototype._prepare = function () {
  43695. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  43696. this._property = this._getProperty(this.propertyPath);
  43697. };
  43698. SwitchBooleanAction.prototype.execute = function () {
  43699. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  43700. };
  43701. SwitchBooleanAction.prototype.serialize = function (parent) {
  43702. return _super.prototype._serialize.call(this, {
  43703. name: "SwitchBooleanAction",
  43704. properties: [
  43705. BABYLON.Action._GetTargetProperty(this._target),
  43706. { name: "propertyPath", value: this.propertyPath }
  43707. ]
  43708. }, parent);
  43709. };
  43710. return SwitchBooleanAction;
  43711. }(BABYLON.Action));
  43712. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  43713. var SetStateAction = /** @class */ (function (_super) {
  43714. __extends(SetStateAction, _super);
  43715. function SetStateAction(triggerOptions, target, value, condition) {
  43716. var _this = _super.call(this, triggerOptions, condition) || this;
  43717. _this.value = value;
  43718. _this._target = target;
  43719. return _this;
  43720. }
  43721. SetStateAction.prototype.execute = function () {
  43722. this._target.state = this.value;
  43723. };
  43724. SetStateAction.prototype.serialize = function (parent) {
  43725. return _super.prototype._serialize.call(this, {
  43726. name: "SetStateAction",
  43727. properties: [
  43728. BABYLON.Action._GetTargetProperty(this._target),
  43729. { name: "value", value: this.value }
  43730. ]
  43731. }, parent);
  43732. };
  43733. return SetStateAction;
  43734. }(BABYLON.Action));
  43735. BABYLON.SetStateAction = SetStateAction;
  43736. var SetValueAction = /** @class */ (function (_super) {
  43737. __extends(SetValueAction, _super);
  43738. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  43739. var _this = _super.call(this, triggerOptions, condition) || this;
  43740. _this.propertyPath = propertyPath;
  43741. _this.value = value;
  43742. _this._target = _this._effectiveTarget = target;
  43743. return _this;
  43744. }
  43745. SetValueAction.prototype._prepare = function () {
  43746. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  43747. this._property = this._getProperty(this.propertyPath);
  43748. };
  43749. SetValueAction.prototype.execute = function () {
  43750. this._effectiveTarget[this._property] = this.value;
  43751. if (this._target.markAsDirty) {
  43752. this._target.markAsDirty(this._property);
  43753. }
  43754. };
  43755. SetValueAction.prototype.serialize = function (parent) {
  43756. return _super.prototype._serialize.call(this, {
  43757. name: "SetValueAction",
  43758. properties: [
  43759. BABYLON.Action._GetTargetProperty(this._target),
  43760. { name: "propertyPath", value: this.propertyPath },
  43761. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  43762. ]
  43763. }, parent);
  43764. };
  43765. return SetValueAction;
  43766. }(BABYLON.Action));
  43767. BABYLON.SetValueAction = SetValueAction;
  43768. var IncrementValueAction = /** @class */ (function (_super) {
  43769. __extends(IncrementValueAction, _super);
  43770. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  43771. var _this = _super.call(this, triggerOptions, condition) || this;
  43772. _this.propertyPath = propertyPath;
  43773. _this.value = value;
  43774. _this._target = _this._effectiveTarget = target;
  43775. return _this;
  43776. }
  43777. IncrementValueAction.prototype._prepare = function () {
  43778. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  43779. this._property = this._getProperty(this.propertyPath);
  43780. if (typeof this._effectiveTarget[this._property] !== "number") {
  43781. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  43782. }
  43783. };
  43784. IncrementValueAction.prototype.execute = function () {
  43785. this._effectiveTarget[this._property] += this.value;
  43786. if (this._target.markAsDirty) {
  43787. this._target.markAsDirty(this._property);
  43788. }
  43789. };
  43790. IncrementValueAction.prototype.serialize = function (parent) {
  43791. return _super.prototype._serialize.call(this, {
  43792. name: "IncrementValueAction",
  43793. properties: [
  43794. BABYLON.Action._GetTargetProperty(this._target),
  43795. { name: "propertyPath", value: this.propertyPath },
  43796. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  43797. ]
  43798. }, parent);
  43799. };
  43800. return IncrementValueAction;
  43801. }(BABYLON.Action));
  43802. BABYLON.IncrementValueAction = IncrementValueAction;
  43803. var PlayAnimationAction = /** @class */ (function (_super) {
  43804. __extends(PlayAnimationAction, _super);
  43805. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  43806. var _this = _super.call(this, triggerOptions, condition) || this;
  43807. _this.from = from;
  43808. _this.to = to;
  43809. _this.loop = loop;
  43810. _this._target = target;
  43811. return _this;
  43812. }
  43813. PlayAnimationAction.prototype._prepare = function () {
  43814. };
  43815. PlayAnimationAction.prototype.execute = function () {
  43816. var scene = this._actionManager.getScene();
  43817. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  43818. };
  43819. PlayAnimationAction.prototype.serialize = function (parent) {
  43820. return _super.prototype._serialize.call(this, {
  43821. name: "PlayAnimationAction",
  43822. properties: [
  43823. BABYLON.Action._GetTargetProperty(this._target),
  43824. { name: "from", value: String(this.from) },
  43825. { name: "to", value: String(this.to) },
  43826. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  43827. ]
  43828. }, parent);
  43829. };
  43830. return PlayAnimationAction;
  43831. }(BABYLON.Action));
  43832. BABYLON.PlayAnimationAction = PlayAnimationAction;
  43833. var StopAnimationAction = /** @class */ (function (_super) {
  43834. __extends(StopAnimationAction, _super);
  43835. function StopAnimationAction(triggerOptions, target, condition) {
  43836. var _this = _super.call(this, triggerOptions, condition) || this;
  43837. _this._target = target;
  43838. return _this;
  43839. }
  43840. StopAnimationAction.prototype._prepare = function () {
  43841. };
  43842. StopAnimationAction.prototype.execute = function () {
  43843. var scene = this._actionManager.getScene();
  43844. scene.stopAnimation(this._target);
  43845. };
  43846. StopAnimationAction.prototype.serialize = function (parent) {
  43847. return _super.prototype._serialize.call(this, {
  43848. name: "StopAnimationAction",
  43849. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  43850. }, parent);
  43851. };
  43852. return StopAnimationAction;
  43853. }(BABYLON.Action));
  43854. BABYLON.StopAnimationAction = StopAnimationAction;
  43855. var DoNothingAction = /** @class */ (function (_super) {
  43856. __extends(DoNothingAction, _super);
  43857. function DoNothingAction(triggerOptions, condition) {
  43858. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  43859. return _super.call(this, triggerOptions, condition) || this;
  43860. }
  43861. DoNothingAction.prototype.execute = function () {
  43862. };
  43863. DoNothingAction.prototype.serialize = function (parent) {
  43864. return _super.prototype._serialize.call(this, {
  43865. name: "DoNothingAction",
  43866. properties: []
  43867. }, parent);
  43868. };
  43869. return DoNothingAction;
  43870. }(BABYLON.Action));
  43871. BABYLON.DoNothingAction = DoNothingAction;
  43872. var CombineAction = /** @class */ (function (_super) {
  43873. __extends(CombineAction, _super);
  43874. function CombineAction(triggerOptions, children, condition) {
  43875. var _this = _super.call(this, triggerOptions, condition) || this;
  43876. _this.children = children;
  43877. return _this;
  43878. }
  43879. CombineAction.prototype._prepare = function () {
  43880. for (var index = 0; index < this.children.length; index++) {
  43881. this.children[index]._actionManager = this._actionManager;
  43882. this.children[index]._prepare();
  43883. }
  43884. };
  43885. CombineAction.prototype.execute = function (evt) {
  43886. for (var index = 0; index < this.children.length; index++) {
  43887. this.children[index].execute(evt);
  43888. }
  43889. };
  43890. CombineAction.prototype.serialize = function (parent) {
  43891. var serializationObject = _super.prototype._serialize.call(this, {
  43892. name: "CombineAction",
  43893. properties: [],
  43894. combine: []
  43895. }, parent);
  43896. for (var i = 0; i < this.children.length; i++) {
  43897. serializationObject.combine.push(this.children[i].serialize(null));
  43898. }
  43899. return serializationObject;
  43900. };
  43901. return CombineAction;
  43902. }(BABYLON.Action));
  43903. BABYLON.CombineAction = CombineAction;
  43904. var ExecuteCodeAction = /** @class */ (function (_super) {
  43905. __extends(ExecuteCodeAction, _super);
  43906. function ExecuteCodeAction(triggerOptions, func, condition) {
  43907. var _this = _super.call(this, triggerOptions, condition) || this;
  43908. _this.func = func;
  43909. return _this;
  43910. }
  43911. ExecuteCodeAction.prototype.execute = function (evt) {
  43912. this.func(evt);
  43913. };
  43914. return ExecuteCodeAction;
  43915. }(BABYLON.Action));
  43916. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  43917. var SetParentAction = /** @class */ (function (_super) {
  43918. __extends(SetParentAction, _super);
  43919. function SetParentAction(triggerOptions, target, parent, condition) {
  43920. var _this = _super.call(this, triggerOptions, condition) || this;
  43921. _this._target = target;
  43922. _this._parent = parent;
  43923. return _this;
  43924. }
  43925. SetParentAction.prototype._prepare = function () {
  43926. };
  43927. SetParentAction.prototype.execute = function () {
  43928. if (this._target.parent === this._parent) {
  43929. return;
  43930. }
  43931. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  43932. invertParentWorldMatrix.invert();
  43933. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  43934. this._target.parent = this._parent;
  43935. };
  43936. SetParentAction.prototype.serialize = function (parent) {
  43937. return _super.prototype._serialize.call(this, {
  43938. name: "SetParentAction",
  43939. properties: [
  43940. BABYLON.Action._GetTargetProperty(this._target),
  43941. BABYLON.Action._GetTargetProperty(this._parent),
  43942. ]
  43943. }, parent);
  43944. };
  43945. return SetParentAction;
  43946. }(BABYLON.Action));
  43947. BABYLON.SetParentAction = SetParentAction;
  43948. var PlaySoundAction = /** @class */ (function (_super) {
  43949. __extends(PlaySoundAction, _super);
  43950. function PlaySoundAction(triggerOptions, sound, condition) {
  43951. var _this = _super.call(this, triggerOptions, condition) || this;
  43952. _this._sound = sound;
  43953. return _this;
  43954. }
  43955. PlaySoundAction.prototype._prepare = function () {
  43956. };
  43957. PlaySoundAction.prototype.execute = function () {
  43958. if (this._sound !== undefined)
  43959. this._sound.play();
  43960. };
  43961. PlaySoundAction.prototype.serialize = function (parent) {
  43962. return _super.prototype._serialize.call(this, {
  43963. name: "PlaySoundAction",
  43964. properties: [{ name: "sound", value: this._sound.name }]
  43965. }, parent);
  43966. };
  43967. return PlaySoundAction;
  43968. }(BABYLON.Action));
  43969. BABYLON.PlaySoundAction = PlaySoundAction;
  43970. var StopSoundAction = /** @class */ (function (_super) {
  43971. __extends(StopSoundAction, _super);
  43972. function StopSoundAction(triggerOptions, sound, condition) {
  43973. var _this = _super.call(this, triggerOptions, condition) || this;
  43974. _this._sound = sound;
  43975. return _this;
  43976. }
  43977. StopSoundAction.prototype._prepare = function () {
  43978. };
  43979. StopSoundAction.prototype.execute = function () {
  43980. if (this._sound !== undefined)
  43981. this._sound.stop();
  43982. };
  43983. StopSoundAction.prototype.serialize = function (parent) {
  43984. return _super.prototype._serialize.call(this, {
  43985. name: "StopSoundAction",
  43986. properties: [{ name: "sound", value: this._sound.name }]
  43987. }, parent);
  43988. };
  43989. return StopSoundAction;
  43990. }(BABYLON.Action));
  43991. BABYLON.StopSoundAction = StopSoundAction;
  43992. })(BABYLON || (BABYLON = {}));
  43993. //# sourceMappingURL=babylon.directActions.js.map
  43994. var BABYLON;
  43995. (function (BABYLON) {
  43996. var SpriteManager = /** @class */ (function () {
  43997. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  43998. if (epsilon === void 0) { epsilon = 0.01; }
  43999. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44000. this.name = name;
  44001. this.sprites = new Array();
  44002. this.renderingGroupId = 0;
  44003. this.layerMask = 0x0FFFFFFF;
  44004. this.fogEnabled = true;
  44005. this.isPickable = false;
  44006. /**
  44007. * An event triggered when the manager is disposed.
  44008. * @type {BABYLON.Observable}
  44009. */
  44010. this.onDisposeObservable = new BABYLON.Observable();
  44011. this._vertexBuffers = {};
  44012. this._capacity = capacity;
  44013. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  44014. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44015. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44016. if (cellSize.width && cellSize.height) {
  44017. this.cellWidth = cellSize.width;
  44018. this.cellHeight = cellSize.height;
  44019. }
  44020. else if (cellSize !== undefined) {
  44021. this.cellWidth = cellSize;
  44022. this.cellHeight = cellSize;
  44023. }
  44024. else {
  44025. return;
  44026. }
  44027. this._epsilon = epsilon;
  44028. this._scene = scene;
  44029. this._scene.spriteManagers.push(this);
  44030. var indices = [];
  44031. var index = 0;
  44032. for (var count = 0; count < capacity; count++) {
  44033. indices.push(index);
  44034. indices.push(index + 1);
  44035. indices.push(index + 2);
  44036. indices.push(index);
  44037. indices.push(index + 2);
  44038. indices.push(index + 3);
  44039. index += 4;
  44040. }
  44041. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  44042. // VBO
  44043. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  44044. this._vertexData = new Float32Array(capacity * 16 * 4);
  44045. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  44046. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  44047. var options = this._buffer.createVertexBuffer("options", 4, 4);
  44048. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  44049. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  44050. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  44051. this._vertexBuffers["options"] = options;
  44052. this._vertexBuffers["cellInfo"] = cellInfo;
  44053. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  44054. // Effects
  44055. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  44056. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  44057. }
  44058. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  44059. set: function (callback) {
  44060. if (this._onDisposeObserver) {
  44061. this.onDisposeObservable.remove(this._onDisposeObserver);
  44062. }
  44063. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  44064. },
  44065. enumerable: true,
  44066. configurable: true
  44067. });
  44068. Object.defineProperty(SpriteManager.prototype, "texture", {
  44069. get: function () {
  44070. return this._spriteTexture;
  44071. },
  44072. set: function (value) {
  44073. this._spriteTexture = value;
  44074. },
  44075. enumerable: true,
  44076. configurable: true
  44077. });
  44078. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  44079. var arrayOffset = index * 16;
  44080. if (offsetX === 0)
  44081. offsetX = this._epsilon;
  44082. else if (offsetX === 1)
  44083. offsetX = 1 - this._epsilon;
  44084. if (offsetY === 0)
  44085. offsetY = this._epsilon;
  44086. else if (offsetY === 1)
  44087. offsetY = 1 - this._epsilon;
  44088. this._vertexData[arrayOffset] = sprite.position.x;
  44089. this._vertexData[arrayOffset + 1] = sprite.position.y;
  44090. this._vertexData[arrayOffset + 2] = sprite.position.z;
  44091. this._vertexData[arrayOffset + 3] = sprite.angle;
  44092. this._vertexData[arrayOffset + 4] = sprite.width;
  44093. this._vertexData[arrayOffset + 5] = sprite.height;
  44094. this._vertexData[arrayOffset + 6] = offsetX;
  44095. this._vertexData[arrayOffset + 7] = offsetY;
  44096. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  44097. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  44098. var offset = (sprite.cellIndex / rowSize) >> 0;
  44099. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  44100. this._vertexData[arrayOffset + 11] = offset;
  44101. // Color
  44102. this._vertexData[arrayOffset + 12] = sprite.color.r;
  44103. this._vertexData[arrayOffset + 13] = sprite.color.g;
  44104. this._vertexData[arrayOffset + 14] = sprite.color.b;
  44105. this._vertexData[arrayOffset + 15] = sprite.color.a;
  44106. };
  44107. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  44108. var count = Math.min(this._capacity, this.sprites.length);
  44109. var min = BABYLON.Vector3.Zero();
  44110. var max = BABYLON.Vector3.Zero();
  44111. var distance = Number.MAX_VALUE;
  44112. var currentSprite = null;
  44113. var cameraSpacePosition = BABYLON.Vector3.Zero();
  44114. var cameraView = camera.getViewMatrix();
  44115. for (var index = 0; index < count; index++) {
  44116. var sprite = this.sprites[index];
  44117. if (!sprite) {
  44118. continue;
  44119. }
  44120. if (predicate) {
  44121. if (!predicate(sprite)) {
  44122. continue;
  44123. }
  44124. }
  44125. else if (!sprite.isPickable) {
  44126. continue;
  44127. }
  44128. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  44129. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  44130. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  44131. if (ray.intersectsBoxMinMax(min, max)) {
  44132. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  44133. if (distance > currentDistance) {
  44134. distance = currentDistance;
  44135. currentSprite = sprite;
  44136. if (fastCheck) {
  44137. break;
  44138. }
  44139. }
  44140. }
  44141. }
  44142. if (currentSprite) {
  44143. var result = new BABYLON.PickingInfo();
  44144. result.hit = true;
  44145. result.pickedSprite = currentSprite;
  44146. result.distance = distance;
  44147. return result;
  44148. }
  44149. return null;
  44150. };
  44151. SpriteManager.prototype.render = function () {
  44152. // Check
  44153. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  44154. return;
  44155. var engine = this._scene.getEngine();
  44156. var baseSize = this._spriteTexture.getBaseSize();
  44157. // Sprites
  44158. var deltaTime = engine.getDeltaTime();
  44159. var max = Math.min(this._capacity, this.sprites.length);
  44160. var rowSize = baseSize.width / this.cellWidth;
  44161. var offset = 0;
  44162. for (var index = 0; index < max; index++) {
  44163. var sprite = this.sprites[index];
  44164. if (!sprite) {
  44165. continue;
  44166. }
  44167. sprite._animate(deltaTime);
  44168. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  44169. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  44170. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  44171. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  44172. }
  44173. this._buffer.update(this._vertexData);
  44174. // Render
  44175. var effect = this._effectBase;
  44176. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  44177. effect = this._effectFog;
  44178. }
  44179. engine.enableEffect(effect);
  44180. var viewMatrix = this._scene.getViewMatrix();
  44181. effect.setTexture("diffuseSampler", this._spriteTexture);
  44182. effect.setMatrix("view", viewMatrix);
  44183. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  44184. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  44185. // Fog
  44186. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  44187. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  44188. effect.setColor3("vFogColor", this._scene.fogColor);
  44189. }
  44190. // VBOs
  44191. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  44192. // Draw order
  44193. engine.setDepthFunctionToLessOrEqual();
  44194. effect.setBool("alphaTest", true);
  44195. engine.setColorWrite(false);
  44196. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  44197. engine.setColorWrite(true);
  44198. effect.setBool("alphaTest", false);
  44199. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  44200. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  44201. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  44202. };
  44203. SpriteManager.prototype.dispose = function () {
  44204. if (this._buffer) {
  44205. this._buffer.dispose();
  44206. this._buffer = null;
  44207. }
  44208. if (this._indexBuffer) {
  44209. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  44210. this._indexBuffer = null;
  44211. }
  44212. if (this._spriteTexture) {
  44213. this._spriteTexture.dispose();
  44214. this._spriteTexture = null;
  44215. }
  44216. // Remove from scene
  44217. var index = this._scene.spriteManagers.indexOf(this);
  44218. this._scene.spriteManagers.splice(index, 1);
  44219. // Callback
  44220. this.onDisposeObservable.notifyObservers(this);
  44221. this.onDisposeObservable.clear();
  44222. };
  44223. return SpriteManager;
  44224. }());
  44225. BABYLON.SpriteManager = SpriteManager;
  44226. })(BABYLON || (BABYLON = {}));
  44227. //# sourceMappingURL=babylon.spriteManager.js.map
  44228. var BABYLON;
  44229. (function (BABYLON) {
  44230. var Sprite = /** @class */ (function () {
  44231. function Sprite(name, manager) {
  44232. this.name = name;
  44233. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44234. this.width = 1.0;
  44235. this.height = 1.0;
  44236. this.angle = 0;
  44237. this.cellIndex = 0;
  44238. this.invertU = 0;
  44239. this.invertV = 0;
  44240. this.animations = new Array();
  44241. this.isPickable = false;
  44242. this._animationStarted = false;
  44243. this._loopAnimation = false;
  44244. this._fromIndex = 0;
  44245. this._toIndex = 0;
  44246. this._delay = 0;
  44247. this._direction = 1;
  44248. this._time = 0;
  44249. this._manager = manager;
  44250. this._manager.sprites.push(this);
  44251. this.position = BABYLON.Vector3.Zero();
  44252. }
  44253. Object.defineProperty(Sprite.prototype, "size", {
  44254. get: function () {
  44255. return this.width;
  44256. },
  44257. set: function (value) {
  44258. this.width = value;
  44259. this.height = value;
  44260. },
  44261. enumerable: true,
  44262. configurable: true
  44263. });
  44264. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  44265. this._fromIndex = from;
  44266. this._toIndex = to;
  44267. this._loopAnimation = loop;
  44268. this._delay = delay;
  44269. this._animationStarted = true;
  44270. this._direction = from < to ? 1 : -1;
  44271. this.cellIndex = from;
  44272. this._time = 0;
  44273. this._onAnimationEnd = onAnimationEnd;
  44274. };
  44275. Sprite.prototype.stopAnimation = function () {
  44276. this._animationStarted = false;
  44277. };
  44278. Sprite.prototype._animate = function (deltaTime) {
  44279. if (!this._animationStarted)
  44280. return;
  44281. this._time += deltaTime;
  44282. if (this._time > this._delay) {
  44283. this._time = this._time % this._delay;
  44284. this.cellIndex += this._direction;
  44285. if (this.cellIndex > this._toIndex) {
  44286. if (this._loopAnimation) {
  44287. this.cellIndex = this._fromIndex;
  44288. }
  44289. else {
  44290. this.cellIndex = this._toIndex;
  44291. this._animationStarted = false;
  44292. if (this._onAnimationEnd) {
  44293. this._onAnimationEnd();
  44294. }
  44295. if (this.disposeWhenFinishedAnimating) {
  44296. this.dispose();
  44297. }
  44298. }
  44299. }
  44300. }
  44301. };
  44302. Sprite.prototype.dispose = function () {
  44303. for (var i = 0; i < this._manager.sprites.length; i++) {
  44304. if (this._manager.sprites[i] == this) {
  44305. this._manager.sprites.splice(i, 1);
  44306. }
  44307. }
  44308. };
  44309. return Sprite;
  44310. }());
  44311. BABYLON.Sprite = Sprite;
  44312. })(BABYLON || (BABYLON = {}));
  44313. //# sourceMappingURL=babylon.sprite.js.map
  44314. var BABYLON;
  44315. (function (BABYLON) {
  44316. var IntersectionInfo = /** @class */ (function () {
  44317. function IntersectionInfo(bu, bv, distance) {
  44318. this.bu = bu;
  44319. this.bv = bv;
  44320. this.distance = distance;
  44321. this.faceId = 0;
  44322. this.subMeshId = 0;
  44323. }
  44324. return IntersectionInfo;
  44325. }());
  44326. BABYLON.IntersectionInfo = IntersectionInfo;
  44327. var PickingInfo = /** @class */ (function () {
  44328. function PickingInfo() {
  44329. this.hit = false;
  44330. this.distance = 0;
  44331. this.pickedPoint = null;
  44332. this.pickedMesh = null;
  44333. this.bu = 0;
  44334. this.bv = 0;
  44335. this.faceId = -1;
  44336. this.subMeshId = 0;
  44337. this.pickedSprite = null;
  44338. }
  44339. // Methods
  44340. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  44341. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  44342. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  44343. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44344. return null;
  44345. }
  44346. var indices = this.pickedMesh.getIndices();
  44347. if (!indices) {
  44348. return null;
  44349. }
  44350. var result;
  44351. if (useVerticesNormals) {
  44352. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  44353. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  44354. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  44355. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  44356. normal0 = normal0.scale(this.bu);
  44357. normal1 = normal1.scale(this.bv);
  44358. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  44359. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  44360. }
  44361. else {
  44362. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  44363. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  44364. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  44365. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  44366. var p1p2 = vertex1.subtract(vertex2);
  44367. var p3p2 = vertex3.subtract(vertex2);
  44368. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  44369. }
  44370. if (useWorldCoordinates) {
  44371. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  44372. }
  44373. return BABYLON.Vector3.Normalize(result);
  44374. };
  44375. PickingInfo.prototype.getTextureCoordinates = function () {
  44376. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  44377. return null;
  44378. }
  44379. var indices = this.pickedMesh.getIndices();
  44380. if (!indices) {
  44381. return null;
  44382. }
  44383. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  44384. if (!uvs) {
  44385. return null;
  44386. }
  44387. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  44388. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  44389. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  44390. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  44391. uv1 = uv1.scale(this.bu);
  44392. uv2 = uv2.scale(this.bv);
  44393. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  44394. };
  44395. return PickingInfo;
  44396. }());
  44397. BABYLON.PickingInfo = PickingInfo;
  44398. })(BABYLON || (BABYLON = {}));
  44399. //# sourceMappingURL=babylon.pickingInfo.js.map
  44400. var BABYLON;
  44401. (function (BABYLON) {
  44402. var Ray = /** @class */ (function () {
  44403. function Ray(origin, direction, length) {
  44404. if (length === void 0) { length = Number.MAX_VALUE; }
  44405. this.origin = origin;
  44406. this.direction = direction;
  44407. this.length = length;
  44408. }
  44409. // Methods
  44410. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  44411. var d = 0.0;
  44412. var maxValue = Number.MAX_VALUE;
  44413. var inv;
  44414. var min;
  44415. var max;
  44416. var temp;
  44417. if (Math.abs(this.direction.x) < 0.0000001) {
  44418. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  44419. return false;
  44420. }
  44421. }
  44422. else {
  44423. inv = 1.0 / this.direction.x;
  44424. min = (minimum.x - this.origin.x) * inv;
  44425. max = (maximum.x - this.origin.x) * inv;
  44426. if (max === -Infinity) {
  44427. max = Infinity;
  44428. }
  44429. if (min > max) {
  44430. temp = min;
  44431. min = max;
  44432. max = temp;
  44433. }
  44434. d = Math.max(min, d);
  44435. maxValue = Math.min(max, maxValue);
  44436. if (d > maxValue) {
  44437. return false;
  44438. }
  44439. }
  44440. if (Math.abs(this.direction.y) < 0.0000001) {
  44441. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  44442. return false;
  44443. }
  44444. }
  44445. else {
  44446. inv = 1.0 / this.direction.y;
  44447. min = (minimum.y - this.origin.y) * inv;
  44448. max = (maximum.y - this.origin.y) * inv;
  44449. if (max === -Infinity) {
  44450. max = Infinity;
  44451. }
  44452. if (min > max) {
  44453. temp = min;
  44454. min = max;
  44455. max = temp;
  44456. }
  44457. d = Math.max(min, d);
  44458. maxValue = Math.min(max, maxValue);
  44459. if (d > maxValue) {
  44460. return false;
  44461. }
  44462. }
  44463. if (Math.abs(this.direction.z) < 0.0000001) {
  44464. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  44465. return false;
  44466. }
  44467. }
  44468. else {
  44469. inv = 1.0 / this.direction.z;
  44470. min = (minimum.z - this.origin.z) * inv;
  44471. max = (maximum.z - this.origin.z) * inv;
  44472. if (max === -Infinity) {
  44473. max = Infinity;
  44474. }
  44475. if (min > max) {
  44476. temp = min;
  44477. min = max;
  44478. max = temp;
  44479. }
  44480. d = Math.max(min, d);
  44481. maxValue = Math.min(max, maxValue);
  44482. if (d > maxValue) {
  44483. return false;
  44484. }
  44485. }
  44486. return true;
  44487. };
  44488. Ray.prototype.intersectsBox = function (box) {
  44489. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  44490. };
  44491. Ray.prototype.intersectsSphere = function (sphere) {
  44492. var x = sphere.center.x - this.origin.x;
  44493. var y = sphere.center.y - this.origin.y;
  44494. var z = sphere.center.z - this.origin.z;
  44495. var pyth = (x * x) + (y * y) + (z * z);
  44496. var rr = sphere.radius * sphere.radius;
  44497. if (pyth <= rr) {
  44498. return true;
  44499. }
  44500. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  44501. if (dot < 0.0) {
  44502. return false;
  44503. }
  44504. var temp = pyth - (dot * dot);
  44505. return temp <= rr;
  44506. };
  44507. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  44508. if (!this._edge1) {
  44509. this._edge1 = BABYLON.Vector3.Zero();
  44510. this._edge2 = BABYLON.Vector3.Zero();
  44511. this._pvec = BABYLON.Vector3.Zero();
  44512. this._tvec = BABYLON.Vector3.Zero();
  44513. this._qvec = BABYLON.Vector3.Zero();
  44514. }
  44515. vertex1.subtractToRef(vertex0, this._edge1);
  44516. vertex2.subtractToRef(vertex0, this._edge2);
  44517. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  44518. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  44519. if (det === 0) {
  44520. return null;
  44521. }
  44522. var invdet = 1 / det;
  44523. this.origin.subtractToRef(vertex0, this._tvec);
  44524. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  44525. if (bu < 0 || bu > 1.0) {
  44526. return null;
  44527. }
  44528. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  44529. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  44530. if (bv < 0 || bu + bv > 1.0) {
  44531. return null;
  44532. }
  44533. //check if the distance is longer than the predefined length.
  44534. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  44535. if (distance > this.length) {
  44536. return null;
  44537. }
  44538. return new BABYLON.IntersectionInfo(bu, bv, distance);
  44539. };
  44540. Ray.prototype.intersectsPlane = function (plane) {
  44541. var distance;
  44542. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  44543. if (Math.abs(result1) < 9.99999997475243E-07) {
  44544. return null;
  44545. }
  44546. else {
  44547. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  44548. distance = (-plane.d - result2) / result1;
  44549. if (distance < 0.0) {
  44550. if (distance < -9.99999997475243E-07) {
  44551. return null;
  44552. }
  44553. else {
  44554. return 0;
  44555. }
  44556. }
  44557. return distance;
  44558. }
  44559. };
  44560. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  44561. var tm = BABYLON.Tmp.Matrix[0];
  44562. mesh.getWorldMatrix().invertToRef(tm);
  44563. if (this._tmpRay) {
  44564. Ray.TransformToRef(this, tm, this._tmpRay);
  44565. }
  44566. else {
  44567. this._tmpRay = Ray.Transform(this, tm);
  44568. }
  44569. return mesh.intersects(this._tmpRay, fastCheck);
  44570. };
  44571. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  44572. if (results) {
  44573. results.length = 0;
  44574. }
  44575. else {
  44576. results = [];
  44577. }
  44578. for (var i = 0; i < meshes.length; i++) {
  44579. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  44580. if (pickInfo.hit) {
  44581. results.push(pickInfo);
  44582. }
  44583. }
  44584. results.sort(this._comparePickingInfo);
  44585. return results;
  44586. };
  44587. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  44588. if (pickingInfoA.distance < pickingInfoB.distance) {
  44589. return -1;
  44590. }
  44591. else if (pickingInfoA.distance > pickingInfoB.distance) {
  44592. return 1;
  44593. }
  44594. else {
  44595. return 0;
  44596. }
  44597. };
  44598. /**
  44599. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  44600. * @param sega the first point of the segment to test the intersection against
  44601. * @param segb the second point of the segment to test the intersection against
  44602. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  44603. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  44604. */
  44605. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  44606. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  44607. var u = segb.subtract(sega);
  44608. var v = rsegb.subtract(this.origin);
  44609. var w = sega.subtract(this.origin);
  44610. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  44611. var b = BABYLON.Vector3.Dot(u, v);
  44612. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  44613. var d = BABYLON.Vector3.Dot(u, w);
  44614. var e = BABYLON.Vector3.Dot(v, w);
  44615. var D = a * c - b * b; // always >= 0
  44616. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  44617. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  44618. // compute the line parameters of the two closest points
  44619. if (D < Ray.smallnum) {
  44620. sN = 0.0; // force using point P0 on segment S1
  44621. sD = 1.0; // to prevent possible division by 0.0 later
  44622. tN = e;
  44623. tD = c;
  44624. }
  44625. else {
  44626. sN = (b * e - c * d);
  44627. tN = (a * e - b * d);
  44628. if (sN < 0.0) {
  44629. sN = 0.0;
  44630. tN = e;
  44631. tD = c;
  44632. }
  44633. else if (sN > sD) {
  44634. sN = sD;
  44635. tN = e + b;
  44636. tD = c;
  44637. }
  44638. }
  44639. if (tN < 0.0) {
  44640. tN = 0.0;
  44641. // recompute sc for this edge
  44642. if (-d < 0.0) {
  44643. sN = 0.0;
  44644. }
  44645. else if (-d > a)
  44646. sN = sD;
  44647. else {
  44648. sN = -d;
  44649. sD = a;
  44650. }
  44651. }
  44652. else if (tN > tD) {
  44653. tN = tD;
  44654. // recompute sc for this edge
  44655. if ((-d + b) < 0.0) {
  44656. sN = 0;
  44657. }
  44658. else if ((-d + b) > a) {
  44659. sN = sD;
  44660. }
  44661. else {
  44662. sN = (-d + b);
  44663. sD = a;
  44664. }
  44665. }
  44666. // finally do the division to get sc and tc
  44667. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  44668. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  44669. // get the difference of the two closest points
  44670. var qtc = v.multiplyByFloats(tc, tc, tc);
  44671. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  44672. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  44673. if (isIntersected) {
  44674. return qtc.length();
  44675. }
  44676. return -1;
  44677. };
  44678. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  44679. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  44680. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  44681. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  44682. this.direction.normalize();
  44683. return this;
  44684. };
  44685. // Statics
  44686. Ray.Zero = function () {
  44687. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  44688. };
  44689. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  44690. var result = Ray.Zero();
  44691. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  44692. };
  44693. /**
  44694. * 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
  44695. * transformed to the given world matrix.
  44696. * @param origin The origin point
  44697. * @param end The end point
  44698. * @param world a matrix to transform the ray to. Default is the identity matrix.
  44699. */
  44700. Ray.CreateNewFromTo = function (origin, end, world) {
  44701. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  44702. var direction = end.subtract(origin);
  44703. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  44704. direction.normalize();
  44705. return Ray.Transform(new Ray(origin, direction, length), world);
  44706. };
  44707. Ray.Transform = function (ray, matrix) {
  44708. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  44709. Ray.TransformToRef(ray, matrix, result);
  44710. return result;
  44711. };
  44712. Ray.TransformToRef = function (ray, matrix, result) {
  44713. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  44714. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  44715. result.length = ray.length;
  44716. var dir = result.direction;
  44717. var len = dir.length();
  44718. if (!(len === 0 || len === 1)) {
  44719. var num = 1.0 / len;
  44720. dir.x *= num;
  44721. dir.y *= num;
  44722. dir.z *= num;
  44723. result.length *= len;
  44724. }
  44725. };
  44726. Ray.smallnum = 0.00000001;
  44727. Ray.rayl = 10e8;
  44728. return Ray;
  44729. }());
  44730. BABYLON.Ray = Ray;
  44731. })(BABYLON || (BABYLON = {}));
  44732. //# sourceMappingURL=babylon.ray.js.map
  44733. var BABYLON;
  44734. (function (BABYLON) {
  44735. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  44736. if (boxMin.x > sphereCenter.x + sphereRadius)
  44737. return false;
  44738. if (sphereCenter.x - sphereRadius > boxMax.x)
  44739. return false;
  44740. if (boxMin.y > sphereCenter.y + sphereRadius)
  44741. return false;
  44742. if (sphereCenter.y - sphereRadius > boxMax.y)
  44743. return false;
  44744. if (boxMin.z > sphereCenter.z + sphereRadius)
  44745. return false;
  44746. if (sphereCenter.z - sphereRadius > boxMax.z)
  44747. return false;
  44748. return true;
  44749. };
  44750. var getLowestRoot = (function () {
  44751. var result = { root: 0, found: false };
  44752. return function (a, b, c, maxR) {
  44753. result.root = 0;
  44754. result.found = false;
  44755. var determinant = b * b - 4.0 * a * c;
  44756. if (determinant < 0)
  44757. return result;
  44758. var sqrtD = Math.sqrt(determinant);
  44759. var r1 = (-b - sqrtD) / (2.0 * a);
  44760. var r2 = (-b + sqrtD) / (2.0 * a);
  44761. if (r1 > r2) {
  44762. var temp = r2;
  44763. r2 = r1;
  44764. r1 = temp;
  44765. }
  44766. if (r1 > 0 && r1 < maxR) {
  44767. result.root = r1;
  44768. result.found = true;
  44769. return result;
  44770. }
  44771. if (r2 > 0 && r2 < maxR) {
  44772. result.root = r2;
  44773. result.found = true;
  44774. return result;
  44775. }
  44776. return result;
  44777. };
  44778. })();
  44779. var Collider = /** @class */ (function () {
  44780. function Collider() {
  44781. this._collisionPoint = BABYLON.Vector3.Zero();
  44782. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  44783. this._tempVector = BABYLON.Vector3.Zero();
  44784. this._tempVector2 = BABYLON.Vector3.Zero();
  44785. this._tempVector3 = BABYLON.Vector3.Zero();
  44786. this._tempVector4 = BABYLON.Vector3.Zero();
  44787. this._edge = BABYLON.Vector3.Zero();
  44788. this._baseToVertex = BABYLON.Vector3.Zero();
  44789. this._destinationPoint = BABYLON.Vector3.Zero();
  44790. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  44791. this._displacementVector = BABYLON.Vector3.Zero();
  44792. this._radius = BABYLON.Vector3.One();
  44793. this._retry = 0;
  44794. this._basePointWorld = BABYLON.Vector3.Zero();
  44795. this._velocityWorld = BABYLON.Vector3.Zero();
  44796. this._normalizedVelocity = BABYLON.Vector3.Zero();
  44797. this._collisionMask = -1;
  44798. }
  44799. Object.defineProperty(Collider.prototype, "collisionMask", {
  44800. get: function () {
  44801. return this._collisionMask;
  44802. },
  44803. set: function (mask) {
  44804. this._collisionMask = !isNaN(mask) ? mask : -1;
  44805. },
  44806. enumerable: true,
  44807. configurable: true
  44808. });
  44809. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  44810. /**
  44811. * Gets the plane normal used to compute the sliding response (in local space)
  44812. */
  44813. get: function () {
  44814. return this._slidePlaneNormal;
  44815. },
  44816. enumerable: true,
  44817. configurable: true
  44818. });
  44819. // Methods
  44820. Collider.prototype._initialize = function (source, dir, e) {
  44821. this._velocity = dir;
  44822. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  44823. this._basePoint = source;
  44824. source.multiplyToRef(this._radius, this._basePointWorld);
  44825. dir.multiplyToRef(this._radius, this._velocityWorld);
  44826. this._velocityWorldLength = this._velocityWorld.length();
  44827. this._epsilon = e;
  44828. this.collisionFound = false;
  44829. };
  44830. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  44831. pa.subtractToRef(point, this._tempVector);
  44832. pb.subtractToRef(point, this._tempVector2);
  44833. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  44834. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  44835. if (d < 0)
  44836. return false;
  44837. pc.subtractToRef(point, this._tempVector3);
  44838. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  44839. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  44840. if (d < 0)
  44841. return false;
  44842. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  44843. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  44844. return d >= 0;
  44845. };
  44846. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  44847. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  44848. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  44849. if (distance > this._velocityWorldLength + max + sphereRadius) {
  44850. return false;
  44851. }
  44852. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  44853. return false;
  44854. return true;
  44855. };
  44856. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  44857. var t0;
  44858. var embeddedInPlane = false;
  44859. //defensive programming, actually not needed.
  44860. if (!trianglePlaneArray) {
  44861. trianglePlaneArray = [];
  44862. }
  44863. if (!trianglePlaneArray[faceIndex]) {
  44864. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  44865. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  44866. }
  44867. var trianglePlane = trianglePlaneArray[faceIndex];
  44868. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  44869. return;
  44870. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  44871. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  44872. if (normalDotVelocity == 0) {
  44873. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  44874. return;
  44875. embeddedInPlane = true;
  44876. t0 = 0;
  44877. }
  44878. else {
  44879. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  44880. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  44881. if (t0 > t1) {
  44882. var temp = t1;
  44883. t1 = t0;
  44884. t0 = temp;
  44885. }
  44886. if (t0 > 1.0 || t1 < 0.0)
  44887. return;
  44888. if (t0 < 0)
  44889. t0 = 0;
  44890. if (t0 > 1.0)
  44891. t0 = 1.0;
  44892. }
  44893. this._collisionPoint.copyFromFloats(0, 0, 0);
  44894. var found = false;
  44895. var t = 1.0;
  44896. if (!embeddedInPlane) {
  44897. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  44898. this._velocity.scaleToRef(t0, this._tempVector);
  44899. this._planeIntersectionPoint.addInPlace(this._tempVector);
  44900. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  44901. found = true;
  44902. t = t0;
  44903. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  44904. }
  44905. }
  44906. if (!found) {
  44907. var velocitySquaredLength = this._velocity.lengthSquared();
  44908. var a = velocitySquaredLength;
  44909. this._basePoint.subtractToRef(p1, this._tempVector);
  44910. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  44911. var c = this._tempVector.lengthSquared() - 1.0;
  44912. var lowestRoot = getLowestRoot(a, b, c, t);
  44913. if (lowestRoot.found) {
  44914. t = lowestRoot.root;
  44915. found = true;
  44916. this._collisionPoint.copyFrom(p1);
  44917. }
  44918. this._basePoint.subtractToRef(p2, this._tempVector);
  44919. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  44920. c = this._tempVector.lengthSquared() - 1.0;
  44921. lowestRoot = getLowestRoot(a, b, c, t);
  44922. if (lowestRoot.found) {
  44923. t = lowestRoot.root;
  44924. found = true;
  44925. this._collisionPoint.copyFrom(p2);
  44926. }
  44927. this._basePoint.subtractToRef(p3, this._tempVector);
  44928. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  44929. c = this._tempVector.lengthSquared() - 1.0;
  44930. lowestRoot = getLowestRoot(a, b, c, t);
  44931. if (lowestRoot.found) {
  44932. t = lowestRoot.root;
  44933. found = true;
  44934. this._collisionPoint.copyFrom(p3);
  44935. }
  44936. p2.subtractToRef(p1, this._edge);
  44937. p1.subtractToRef(this._basePoint, this._baseToVertex);
  44938. var edgeSquaredLength = this._edge.lengthSquared();
  44939. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  44940. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  44941. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  44942. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  44943. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  44944. lowestRoot = getLowestRoot(a, b, c, t);
  44945. if (lowestRoot.found) {
  44946. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  44947. if (f >= 0.0 && f <= 1.0) {
  44948. t = lowestRoot.root;
  44949. found = true;
  44950. this._edge.scaleInPlace(f);
  44951. p1.addToRef(this._edge, this._collisionPoint);
  44952. }
  44953. }
  44954. p3.subtractToRef(p2, this._edge);
  44955. p2.subtractToRef(this._basePoint, this._baseToVertex);
  44956. edgeSquaredLength = this._edge.lengthSquared();
  44957. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  44958. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  44959. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  44960. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  44961. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  44962. lowestRoot = getLowestRoot(a, b, c, t);
  44963. if (lowestRoot.found) {
  44964. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  44965. if (f >= 0.0 && f <= 1.0) {
  44966. t = lowestRoot.root;
  44967. found = true;
  44968. this._edge.scaleInPlace(f);
  44969. p2.addToRef(this._edge, this._collisionPoint);
  44970. }
  44971. }
  44972. p1.subtractToRef(p3, this._edge);
  44973. p3.subtractToRef(this._basePoint, this._baseToVertex);
  44974. edgeSquaredLength = this._edge.lengthSquared();
  44975. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  44976. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  44977. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  44978. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  44979. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  44980. lowestRoot = getLowestRoot(a, b, c, t);
  44981. if (lowestRoot.found) {
  44982. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  44983. if (f >= 0.0 && f <= 1.0) {
  44984. t = lowestRoot.root;
  44985. found = true;
  44986. this._edge.scaleInPlace(f);
  44987. p3.addToRef(this._edge, this._collisionPoint);
  44988. }
  44989. }
  44990. }
  44991. if (found) {
  44992. var distToCollision = t * this._velocity.length();
  44993. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  44994. if (!this.intersectionPoint) {
  44995. this.intersectionPoint = this._collisionPoint.clone();
  44996. }
  44997. else {
  44998. this.intersectionPoint.copyFrom(this._collisionPoint);
  44999. }
  45000. this._nearestDistance = distToCollision;
  45001. this.collisionFound = true;
  45002. }
  45003. }
  45004. };
  45005. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  45006. for (var i = indexStart; i < indexEnd; i += 3) {
  45007. var p1 = pts[indices[i] - decal];
  45008. var p2 = pts[indices[i + 1] - decal];
  45009. var p3 = pts[indices[i + 2] - decal];
  45010. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  45011. }
  45012. };
  45013. Collider.prototype._getResponse = function (pos, vel) {
  45014. pos.addToRef(vel, this._destinationPoint);
  45015. vel.scaleInPlace((this._nearestDistance / vel.length()));
  45016. this._basePoint.addToRef(vel, pos);
  45017. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  45018. this._slidePlaneNormal.normalize();
  45019. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  45020. pos.addInPlace(this._displacementVector);
  45021. this.intersectionPoint.addInPlace(this._displacementVector);
  45022. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  45023. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  45024. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  45025. };
  45026. return Collider;
  45027. }());
  45028. BABYLON.Collider = Collider;
  45029. })(BABYLON || (BABYLON = {}));
  45030. //# sourceMappingURL=babylon.collider.js.map
  45031. var BABYLON;
  45032. (function (BABYLON) {
  45033. //WebWorker code will be inserted to this variable.
  45034. BABYLON.CollisionWorker = "";
  45035. var WorkerTaskType;
  45036. (function (WorkerTaskType) {
  45037. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  45038. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  45039. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  45040. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  45041. var WorkerReplyType;
  45042. (function (WorkerReplyType) {
  45043. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  45044. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  45045. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  45046. var CollisionCoordinatorWorker = /** @class */ (function () {
  45047. function CollisionCoordinatorWorker() {
  45048. var _this = this;
  45049. this._scaledPosition = BABYLON.Vector3.Zero();
  45050. this._scaledVelocity = BABYLON.Vector3.Zero();
  45051. this.onMeshUpdated = function (transformNode) {
  45052. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  45053. };
  45054. this.onGeometryUpdated = function (geometry) {
  45055. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  45056. };
  45057. this._afterRender = function () {
  45058. if (!_this._init)
  45059. return;
  45060. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  45061. return;
  45062. }
  45063. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  45064. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  45065. if (_this._runningUpdated > 4) {
  45066. return;
  45067. }
  45068. ++_this._runningUpdated;
  45069. var payload = {
  45070. updatedMeshes: _this._addUpdateMeshesList,
  45071. updatedGeometries: _this._addUpdateGeometriesList,
  45072. removedGeometries: _this._toRemoveGeometryArray,
  45073. removedMeshes: _this._toRemoveMeshesArray
  45074. };
  45075. var message = {
  45076. payload: payload,
  45077. taskType: WorkerTaskType.UPDATE
  45078. };
  45079. var serializable = [];
  45080. for (var id in payload.updatedGeometries) {
  45081. if (payload.updatedGeometries.hasOwnProperty(id)) {
  45082. //prepare transferables
  45083. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  45084. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  45085. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  45086. }
  45087. }
  45088. _this._worker.postMessage(message, serializable);
  45089. _this._addUpdateMeshesList = {};
  45090. _this._addUpdateGeometriesList = {};
  45091. _this._toRemoveGeometryArray = [];
  45092. _this._toRemoveMeshesArray = [];
  45093. };
  45094. this._onMessageFromWorker = function (e) {
  45095. var returnData = e.data;
  45096. if (returnData.error != WorkerReplyType.SUCCESS) {
  45097. //TODO what errors can be returned from the worker?
  45098. BABYLON.Tools.Warn("error returned from worker!");
  45099. return;
  45100. }
  45101. switch (returnData.taskType) {
  45102. case WorkerTaskType.INIT:
  45103. _this._init = true;
  45104. //Update the worked with ALL of the scene's current state
  45105. _this._scene.meshes.forEach(function (mesh) {
  45106. _this.onMeshAdded(mesh);
  45107. });
  45108. _this._scene.getGeometries().forEach(function (geometry) {
  45109. _this.onGeometryAdded(geometry);
  45110. });
  45111. break;
  45112. case WorkerTaskType.UPDATE:
  45113. _this._runningUpdated--;
  45114. break;
  45115. case WorkerTaskType.COLLIDE:
  45116. var returnPayload = returnData.payload;
  45117. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  45118. return;
  45119. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  45120. if (callback) {
  45121. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  45122. if (mesh) {
  45123. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  45124. }
  45125. }
  45126. //cleanup
  45127. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  45128. break;
  45129. }
  45130. };
  45131. this._collisionsCallbackArray = [];
  45132. this._init = false;
  45133. this._runningUpdated = 0;
  45134. this._addUpdateMeshesList = {};
  45135. this._addUpdateGeometriesList = {};
  45136. this._toRemoveGeometryArray = [];
  45137. this._toRemoveMeshesArray = [];
  45138. }
  45139. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  45140. if (!this._init)
  45141. return;
  45142. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  45143. return;
  45144. position.divideToRef(collider._radius, this._scaledPosition);
  45145. displacement.divideToRef(collider._radius, this._scaledVelocity);
  45146. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  45147. var payload = {
  45148. collider: {
  45149. position: this._scaledPosition.asArray(),
  45150. velocity: this._scaledVelocity.asArray(),
  45151. radius: collider._radius.asArray()
  45152. },
  45153. collisionId: collisionIndex,
  45154. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  45155. maximumRetry: maximumRetry
  45156. };
  45157. var message = {
  45158. payload: payload,
  45159. taskType: WorkerTaskType.COLLIDE
  45160. };
  45161. this._worker.postMessage(message);
  45162. };
  45163. CollisionCoordinatorWorker.prototype.init = function (scene) {
  45164. this._scene = scene;
  45165. this._scene.registerAfterRender(this._afterRender);
  45166. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  45167. this._worker = new Worker(workerUrl);
  45168. this._worker.onmessage = this._onMessageFromWorker;
  45169. var message = {
  45170. payload: {},
  45171. taskType: WorkerTaskType.INIT
  45172. };
  45173. this._worker.postMessage(message);
  45174. };
  45175. CollisionCoordinatorWorker.prototype.destroy = function () {
  45176. this._scene.unregisterAfterRender(this._afterRender);
  45177. this._worker.terminate();
  45178. };
  45179. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  45180. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  45181. this.onMeshUpdated(mesh);
  45182. };
  45183. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  45184. this._toRemoveMeshesArray.push(mesh.uniqueId);
  45185. };
  45186. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  45187. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  45188. geometry.onGeometryUpdated = this.onGeometryUpdated;
  45189. this.onGeometryUpdated(geometry);
  45190. };
  45191. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  45192. this._toRemoveGeometryArray.push(geometry.id);
  45193. };
  45194. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  45195. var submeshes = [];
  45196. if (mesh.subMeshes) {
  45197. submeshes = mesh.subMeshes.map(function (sm, idx) {
  45198. var boundingInfo = sm.getBoundingInfo();
  45199. return {
  45200. position: idx,
  45201. verticesStart: sm.verticesStart,
  45202. verticesCount: sm.verticesCount,
  45203. indexStart: sm.indexStart,
  45204. indexCount: sm.indexCount,
  45205. hasMaterial: !!sm.getMaterial(),
  45206. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  45207. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  45208. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  45209. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  45210. };
  45211. });
  45212. }
  45213. var geometryId = null;
  45214. if (mesh instanceof BABYLON.Mesh) {
  45215. var geometry = mesh.geometry;
  45216. geometryId = geometry ? geometry.id : null;
  45217. }
  45218. else if (mesh instanceof BABYLON.InstancedMesh) {
  45219. var geometry = mesh.sourceMesh.geometry;
  45220. geometryId = geometry ? geometry.id : null;
  45221. }
  45222. var boundingInfo = mesh.getBoundingInfo();
  45223. return {
  45224. uniqueId: mesh.uniqueId,
  45225. id: mesh.id,
  45226. name: mesh.name,
  45227. geometryId: geometryId,
  45228. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  45229. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  45230. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  45231. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  45232. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  45233. subMeshes: submeshes,
  45234. checkCollisions: mesh.checkCollisions
  45235. };
  45236. };
  45237. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  45238. return {
  45239. id: geometry.id,
  45240. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  45241. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  45242. indices: new Uint32Array(geometry.getIndices() || []),
  45243. };
  45244. };
  45245. return CollisionCoordinatorWorker;
  45246. }());
  45247. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  45248. var CollisionCoordinatorLegacy = /** @class */ (function () {
  45249. function CollisionCoordinatorLegacy() {
  45250. this._scaledPosition = BABYLON.Vector3.Zero();
  45251. this._scaledVelocity = BABYLON.Vector3.Zero();
  45252. this._finalPosition = BABYLON.Vector3.Zero();
  45253. }
  45254. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  45255. position.divideToRef(collider._radius, this._scaledPosition);
  45256. displacement.divideToRef(collider._radius, this._scaledVelocity);
  45257. collider.collidedMesh = null;
  45258. collider._retry = 0;
  45259. collider._initialVelocity = this._scaledVelocity;
  45260. collider._initialPosition = this._scaledPosition;
  45261. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  45262. this._finalPosition.multiplyInPlace(collider._radius);
  45263. //run the callback
  45264. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  45265. };
  45266. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  45267. this._scene = scene;
  45268. };
  45269. CollisionCoordinatorLegacy.prototype.destroy = function () {
  45270. //Legacy need no destruction method.
  45271. };
  45272. //No update in legacy mode
  45273. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  45274. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  45275. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  45276. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  45277. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  45278. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  45279. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  45280. if (excludedMesh === void 0) { excludedMesh = null; }
  45281. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  45282. if (collider._retry >= maximumRetry) {
  45283. finalPosition.copyFrom(position);
  45284. return;
  45285. }
  45286. // Check if this is a mesh else camera or -1
  45287. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  45288. collider._initialize(position, velocity, closeDistance);
  45289. // Check all meshes
  45290. for (var index = 0; index < this._scene.meshes.length; index++) {
  45291. var mesh = this._scene.meshes[index];
  45292. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  45293. mesh._checkCollision(collider);
  45294. }
  45295. }
  45296. if (!collider.collisionFound) {
  45297. position.addToRef(velocity, finalPosition);
  45298. return;
  45299. }
  45300. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  45301. collider._getResponse(position, velocity);
  45302. }
  45303. if (velocity.length() <= closeDistance) {
  45304. finalPosition.copyFrom(position);
  45305. return;
  45306. }
  45307. collider._retry++;
  45308. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  45309. };
  45310. return CollisionCoordinatorLegacy;
  45311. }());
  45312. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  45313. })(BABYLON || (BABYLON = {}));
  45314. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  45315. var BABYLON;
  45316. (function (BABYLON) {
  45317. var Particle = /** @class */ (function () {
  45318. function Particle(particleSystem) {
  45319. this.particleSystem = particleSystem;
  45320. this.position = BABYLON.Vector3.Zero();
  45321. this.direction = BABYLON.Vector3.Zero();
  45322. this.color = new BABYLON.Color4(0, 0, 0, 0);
  45323. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  45324. this.lifeTime = 1.0;
  45325. this.age = 0;
  45326. this.size = 0;
  45327. this.angle = 0;
  45328. this.angularSpeed = 0;
  45329. this._currentFrameCounter = 0;
  45330. this.cellIndex = 0;
  45331. if (!this.particleSystem.isAnimationSheetEnabled) {
  45332. return;
  45333. }
  45334. this.cellIndex = this.particleSystem.startSpriteCellID;
  45335. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  45336. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  45337. }
  45338. else {
  45339. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  45340. }
  45341. }
  45342. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  45343. // (ageOffset / scaledUpdateSpeed) / available cells
  45344. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  45345. this._currentFrameCounter += scaledUpdateSpeed;
  45346. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  45347. this._currentFrameCounter = 0;
  45348. this.cellIndex++;
  45349. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  45350. this.cellIndex = this.particleSystem.endSpriteCellID;
  45351. }
  45352. }
  45353. };
  45354. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  45355. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  45356. this.cellIndex++;
  45357. this._currentFrameCounter = 0;
  45358. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  45359. if (this.particleSystem.spriteCellLoop) {
  45360. this.cellIndex = this.particleSystem.startSpriteCellID;
  45361. }
  45362. else {
  45363. this.cellIndex = this.particleSystem.endSpriteCellID;
  45364. }
  45365. }
  45366. }
  45367. else {
  45368. this._currentFrameCounter++;
  45369. }
  45370. };
  45371. Particle.prototype.copyTo = function (other) {
  45372. other.position.copyFrom(this.position);
  45373. other.direction.copyFrom(this.direction);
  45374. other.color.copyFrom(this.color);
  45375. other.colorStep.copyFrom(this.colorStep);
  45376. other.lifeTime = this.lifeTime;
  45377. other.age = this.age;
  45378. other.size = this.size;
  45379. other.angle = this.angle;
  45380. other.angularSpeed = this.angularSpeed;
  45381. other.particleSystem = this.particleSystem;
  45382. other.cellIndex = this.cellIndex;
  45383. };
  45384. return Particle;
  45385. }());
  45386. BABYLON.Particle = Particle;
  45387. })(BABYLON || (BABYLON = {}));
  45388. //# sourceMappingURL=babylon.particle.js.map
  45389. var BABYLON;
  45390. (function (BABYLON) {
  45391. var randomNumber = function (min, max) {
  45392. if (min === max) {
  45393. return (min);
  45394. }
  45395. var random = Math.random();
  45396. return ((random * (max - min)) + min);
  45397. };
  45398. var ParticleSystem = /** @class */ (function () {
  45399. // end of sheet animation
  45400. function ParticleSystem(name, capacity, scene, customEffect, _isAnimationSheetEnabled, epsilon) {
  45401. if (customEffect === void 0) { customEffect = null; }
  45402. if (_isAnimationSheetEnabled === void 0) { _isAnimationSheetEnabled = false; }
  45403. if (epsilon === void 0) { epsilon = 0.01; }
  45404. var _this = this;
  45405. this.name = name;
  45406. this._isAnimationSheetEnabled = _isAnimationSheetEnabled;
  45407. // Members
  45408. this.animations = [];
  45409. this.renderingGroupId = 0;
  45410. this.emitter = null;
  45411. this.emitRate = 10;
  45412. this.manualEmitCount = -1;
  45413. this.updateSpeed = 0.01;
  45414. this.targetStopDuration = 0;
  45415. this.disposeOnStop = false;
  45416. this.minEmitPower = 1;
  45417. this.maxEmitPower = 1;
  45418. this.minLifeTime = 1;
  45419. this.maxLifeTime = 1;
  45420. this.minSize = 1;
  45421. this.maxSize = 1;
  45422. this.minAngularSpeed = 0;
  45423. this.maxAngularSpeed = 0;
  45424. this.layerMask = 0x0FFFFFFF;
  45425. this.customShader = null;
  45426. this.preventAutoStart = false;
  45427. /**
  45428. * An event triggered when the system is disposed.
  45429. * @type {BABYLON.Observable}
  45430. */
  45431. this.onDisposeObservable = new BABYLON.Observable();
  45432. this.onAnimationEnd = null;
  45433. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  45434. this.forceDepthWrite = false;
  45435. this.gravity = BABYLON.Vector3.Zero();
  45436. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  45437. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  45438. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  45439. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  45440. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  45441. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  45442. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  45443. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  45444. this.particles = new Array();
  45445. this._stockParticles = new Array();
  45446. this._newPartsExcess = 0;
  45447. this._vertexBuffers = {};
  45448. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  45449. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  45450. this._scaledDirection = BABYLON.Vector3.Zero();
  45451. this._scaledGravity = BABYLON.Vector3.Zero();
  45452. this._currentRenderId = -1;
  45453. this._started = false;
  45454. this._stopped = false;
  45455. this._actualFrame = 0;
  45456. // sheet animation
  45457. this.startSpriteCellID = 0;
  45458. this.endSpriteCellID = 0;
  45459. this.spriteCellLoop = true;
  45460. this.spriteCellChangeSpeed = 0;
  45461. this.spriteCellWidth = 0;
  45462. this.spriteCellHeight = 0;
  45463. this._vertexBufferSize = 11;
  45464. this.appendParticleVertexes = null;
  45465. this.id = name;
  45466. this._capacity = capacity;
  45467. this._epsilon = epsilon;
  45468. if (_isAnimationSheetEnabled) {
  45469. this._vertexBufferSize = 12;
  45470. }
  45471. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  45472. this._customEffect = customEffect;
  45473. scene.particleSystems.push(this);
  45474. this._createIndexBuffer();
  45475. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  45476. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  45477. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  45478. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  45479. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  45480. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  45481. if (this._isAnimationSheetEnabled) {
  45482. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  45483. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  45484. }
  45485. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  45486. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  45487. this._vertexBuffers["options"] = options;
  45488. // Default behaviors
  45489. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  45490. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  45491. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  45492. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  45493. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  45494. };
  45495. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  45496. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  45497. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  45498. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  45499. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  45500. };
  45501. this.updateFunction = function (particles) {
  45502. for (var index = 0; index < particles.length; index++) {
  45503. var particle = particles[index];
  45504. particle.age += _this._scaledUpdateSpeed;
  45505. if (particle.age >= particle.lifeTime) {
  45506. _this.recycleParticle(particle);
  45507. index--;
  45508. continue;
  45509. }
  45510. else {
  45511. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  45512. particle.color.addInPlace(_this._scaledColorStep);
  45513. if (particle.color.a < 0)
  45514. particle.color.a = 0;
  45515. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  45516. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  45517. particle.position.addInPlace(_this._scaledDirection);
  45518. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  45519. particle.direction.addInPlace(_this._scaledGravity);
  45520. if (_this._isAnimationSheetEnabled) {
  45521. particle.updateCellIndex(_this._scaledUpdateSpeed);
  45522. }
  45523. }
  45524. }
  45525. };
  45526. }
  45527. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  45528. set: function (callback) {
  45529. if (this._onDisposeObserver) {
  45530. this.onDisposeObservable.remove(this._onDisposeObserver);
  45531. }
  45532. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  45533. },
  45534. enumerable: true,
  45535. configurable: true
  45536. });
  45537. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  45538. get: function () {
  45539. return this._isAnimationSheetEnabled;
  45540. },
  45541. enumerable: true,
  45542. configurable: true
  45543. });
  45544. ParticleSystem.prototype._createIndexBuffer = function () {
  45545. var indices = [];
  45546. var index = 0;
  45547. for (var count = 0; count < this._capacity; count++) {
  45548. indices.push(index);
  45549. indices.push(index + 1);
  45550. indices.push(index + 2);
  45551. indices.push(index);
  45552. indices.push(index + 2);
  45553. indices.push(index + 3);
  45554. index += 4;
  45555. }
  45556. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  45557. };
  45558. ParticleSystem.prototype.recycleParticle = function (particle) {
  45559. var lastParticle = this.particles.pop();
  45560. if (lastParticle !== particle) {
  45561. lastParticle.copyTo(particle);
  45562. this._stockParticles.push(lastParticle);
  45563. }
  45564. };
  45565. ParticleSystem.prototype.getCapacity = function () {
  45566. return this._capacity;
  45567. };
  45568. ParticleSystem.prototype.isAlive = function () {
  45569. return this._alive;
  45570. };
  45571. ParticleSystem.prototype.isStarted = function () {
  45572. return this._started;
  45573. };
  45574. ParticleSystem.prototype.start = function () {
  45575. this._started = true;
  45576. this._stopped = false;
  45577. this._actualFrame = 0;
  45578. };
  45579. ParticleSystem.prototype.stop = function () {
  45580. this._stopped = true;
  45581. };
  45582. // animation sheet
  45583. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  45584. var offset = index * this._vertexBufferSize;
  45585. this._vertexData[offset] = particle.position.x;
  45586. this._vertexData[offset + 1] = particle.position.y;
  45587. this._vertexData[offset + 2] = particle.position.z;
  45588. this._vertexData[offset + 3] = particle.color.r;
  45589. this._vertexData[offset + 4] = particle.color.g;
  45590. this._vertexData[offset + 5] = particle.color.b;
  45591. this._vertexData[offset + 6] = particle.color.a;
  45592. this._vertexData[offset + 7] = particle.angle;
  45593. this._vertexData[offset + 8] = particle.size;
  45594. this._vertexData[offset + 9] = offsetX;
  45595. this._vertexData[offset + 10] = offsetY;
  45596. };
  45597. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  45598. if (offsetX === 0)
  45599. offsetX = this._epsilon;
  45600. else if (offsetX === 1)
  45601. offsetX = 1 - this._epsilon;
  45602. if (offsetY === 0)
  45603. offsetY = this._epsilon;
  45604. else if (offsetY === 1)
  45605. offsetY = 1 - this._epsilon;
  45606. var offset = index * this._vertexBufferSize;
  45607. this._vertexData[offset] = particle.position.x;
  45608. this._vertexData[offset + 1] = particle.position.y;
  45609. this._vertexData[offset + 2] = particle.position.z;
  45610. this._vertexData[offset + 3] = particle.color.r;
  45611. this._vertexData[offset + 4] = particle.color.g;
  45612. this._vertexData[offset + 5] = particle.color.b;
  45613. this._vertexData[offset + 6] = particle.color.a;
  45614. this._vertexData[offset + 7] = particle.angle;
  45615. this._vertexData[offset + 8] = particle.size;
  45616. this._vertexData[offset + 9] = offsetX;
  45617. this._vertexData[offset + 10] = offsetY;
  45618. this._vertexData[offset + 11] = particle.cellIndex;
  45619. };
  45620. ParticleSystem.prototype._update = function (newParticles) {
  45621. // Update current
  45622. this._alive = this.particles.length > 0;
  45623. this.updateFunction(this.particles);
  45624. // Add new ones
  45625. var worldMatrix;
  45626. if (this.emitter.position) {
  45627. var emitterMesh = this.emitter;
  45628. worldMatrix = emitterMesh.getWorldMatrix();
  45629. }
  45630. else {
  45631. var emitterPosition = this.emitter;
  45632. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  45633. }
  45634. var particle;
  45635. for (var index = 0; index < newParticles; index++) {
  45636. if (this.particles.length === this._capacity) {
  45637. break;
  45638. }
  45639. if (this._stockParticles.length !== 0) {
  45640. particle = this._stockParticles.pop();
  45641. particle.age = 0;
  45642. particle.cellIndex = this.startSpriteCellID;
  45643. }
  45644. else {
  45645. particle = new BABYLON.Particle(this);
  45646. }
  45647. this.particles.push(particle);
  45648. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  45649. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  45650. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  45651. particle.size = randomNumber(this.minSize, this.maxSize);
  45652. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  45653. this.startPositionFunction(worldMatrix, particle.position, particle);
  45654. var step = randomNumber(0, 1.0);
  45655. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  45656. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  45657. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  45658. }
  45659. };
  45660. ParticleSystem.prototype._getEffect = function () {
  45661. if (this._customEffect) {
  45662. return this._customEffect;
  45663. }
  45664. ;
  45665. var defines = [];
  45666. if (this._scene.clipPlane) {
  45667. defines.push("#define CLIPPLANE");
  45668. }
  45669. if (this._isAnimationSheetEnabled) {
  45670. defines.push("#define ANIMATESHEET");
  45671. }
  45672. // Effect
  45673. var join = defines.join("\n");
  45674. if (this._cachedDefines !== join) {
  45675. this._cachedDefines = join;
  45676. var attributesNamesOrOptions;
  45677. var effectCreationOption;
  45678. if (this._isAnimationSheetEnabled) {
  45679. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  45680. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  45681. }
  45682. else {
  45683. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  45684. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  45685. }
  45686. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  45687. }
  45688. return this._effect;
  45689. };
  45690. ParticleSystem.prototype.animate = function () {
  45691. if (!this._started)
  45692. return;
  45693. var effect = this._getEffect();
  45694. // Check
  45695. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  45696. return;
  45697. if (this._currentRenderId === this._scene.getRenderId()) {
  45698. return;
  45699. }
  45700. this._currentRenderId = this._scene.getRenderId();
  45701. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  45702. // determine the number of particles we need to create
  45703. var newParticles;
  45704. if (this.manualEmitCount > -1) {
  45705. newParticles = this.manualEmitCount;
  45706. this._newPartsExcess = 0;
  45707. this.manualEmitCount = 0;
  45708. }
  45709. else {
  45710. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  45711. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  45712. }
  45713. if (this._newPartsExcess > 1.0) {
  45714. newParticles += this._newPartsExcess >> 0;
  45715. this._newPartsExcess -= this._newPartsExcess >> 0;
  45716. }
  45717. this._alive = false;
  45718. if (!this._stopped) {
  45719. this._actualFrame += this._scaledUpdateSpeed;
  45720. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  45721. this.stop();
  45722. }
  45723. else {
  45724. newParticles = 0;
  45725. }
  45726. this._update(newParticles);
  45727. // Stopped?
  45728. if (this._stopped) {
  45729. if (!this._alive) {
  45730. this._started = false;
  45731. if (this.onAnimationEnd) {
  45732. this.onAnimationEnd();
  45733. }
  45734. if (this.disposeOnStop) {
  45735. this._scene._toBeDisposed.push(this);
  45736. }
  45737. }
  45738. }
  45739. // Animation sheet
  45740. if (this._isAnimationSheetEnabled) {
  45741. this.appendParticleVertexes = this.appenedParticleVertexesWithSheet;
  45742. }
  45743. else {
  45744. this.appendParticleVertexes = this.appenedParticleVertexesNoSheet;
  45745. }
  45746. // Update VBO
  45747. var offset = 0;
  45748. for (var index = 0; index < this.particles.length; index++) {
  45749. var particle = this.particles[index];
  45750. this.appendParticleVertexes(offset, particle);
  45751. offset += 4;
  45752. }
  45753. if (this._vertexBuffer) {
  45754. this._vertexBuffer.update(this._vertexData);
  45755. }
  45756. };
  45757. ParticleSystem.prototype.appenedParticleVertexesWithSheet = function (offset, particle) {
  45758. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  45759. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  45760. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  45761. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  45762. };
  45763. ParticleSystem.prototype.appenedParticleVertexesNoSheet = function (offset, particle) {
  45764. this._appendParticleVertex(offset++, particle, 0, 0);
  45765. this._appendParticleVertex(offset++, particle, 1, 0);
  45766. this._appendParticleVertex(offset++, particle, 1, 1);
  45767. this._appendParticleVertex(offset++, particle, 0, 1);
  45768. };
  45769. ParticleSystem.prototype.rebuild = function () {
  45770. this._createIndexBuffer();
  45771. if (this._vertexBuffer) {
  45772. this._vertexBuffer._rebuild();
  45773. }
  45774. };
  45775. ParticleSystem.prototype.render = function () {
  45776. var effect = this._getEffect();
  45777. // Check
  45778. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  45779. return 0;
  45780. var engine = this._scene.getEngine();
  45781. // Render
  45782. engine.enableEffect(effect);
  45783. engine.setState(false);
  45784. var viewMatrix = this._scene.getViewMatrix();
  45785. effect.setTexture("diffuseSampler", this.particleTexture);
  45786. effect.setMatrix("view", viewMatrix);
  45787. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  45788. if (this._isAnimationSheetEnabled) {
  45789. var baseSize = this.particleTexture.getBaseSize();
  45790. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  45791. }
  45792. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  45793. if (this._scene.clipPlane) {
  45794. var clipPlane = this._scene.clipPlane;
  45795. var invView = viewMatrix.clone();
  45796. invView.invert();
  45797. effect.setMatrix("invView", invView);
  45798. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  45799. }
  45800. // VBOs
  45801. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  45802. // Draw order
  45803. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  45804. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  45805. }
  45806. else {
  45807. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  45808. }
  45809. if (this.forceDepthWrite) {
  45810. engine.setDepthWrite(true);
  45811. }
  45812. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this.particles.length * 6);
  45813. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  45814. return this.particles.length;
  45815. };
  45816. ParticleSystem.prototype.dispose = function () {
  45817. if (this._vertexBuffer) {
  45818. this._vertexBuffer.dispose();
  45819. this._vertexBuffer = null;
  45820. }
  45821. if (this._indexBuffer) {
  45822. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  45823. this._indexBuffer = null;
  45824. }
  45825. if (this.particleTexture) {
  45826. this.particleTexture.dispose();
  45827. this.particleTexture = null;
  45828. }
  45829. // Remove from scene
  45830. var index = this._scene.particleSystems.indexOf(this);
  45831. if (index > -1) {
  45832. this._scene.particleSystems.splice(index, 1);
  45833. }
  45834. // Callback
  45835. this.onDisposeObservable.notifyObservers(this);
  45836. this.onDisposeObservable.clear();
  45837. };
  45838. // Clone
  45839. ParticleSystem.prototype.clone = function (name, newEmitter) {
  45840. var custom = null;
  45841. var program = null;
  45842. if (this.customShader != null) {
  45843. program = this.customShader;
  45844. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  45845. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  45846. }
  45847. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  45848. result.customShader = program;
  45849. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  45850. if (newEmitter === undefined) {
  45851. newEmitter = this.emitter;
  45852. }
  45853. result.emitter = newEmitter;
  45854. if (this.particleTexture) {
  45855. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  45856. }
  45857. if (!this.preventAutoStart) {
  45858. result.start();
  45859. }
  45860. return result;
  45861. };
  45862. ParticleSystem.prototype.serialize = function () {
  45863. var serializationObject = {};
  45864. serializationObject.name = this.name;
  45865. serializationObject.id = this.id;
  45866. // Emitter
  45867. if (this.emitter.position) {
  45868. var emitterMesh = this.emitter;
  45869. serializationObject.emitterId = emitterMesh.id;
  45870. }
  45871. else {
  45872. var emitterPosition = this.emitter;
  45873. serializationObject.emitter = emitterPosition.asArray();
  45874. }
  45875. serializationObject.capacity = this.getCapacity();
  45876. if (this.particleTexture) {
  45877. serializationObject.textureName = this.particleTexture.name;
  45878. }
  45879. // Animations
  45880. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  45881. // Particle system
  45882. serializationObject.minAngularSpeed = this.minAngularSpeed;
  45883. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  45884. serializationObject.minSize = this.minSize;
  45885. serializationObject.maxSize = this.maxSize;
  45886. serializationObject.minEmitPower = this.minEmitPower;
  45887. serializationObject.maxEmitPower = this.maxEmitPower;
  45888. serializationObject.minLifeTime = this.minLifeTime;
  45889. serializationObject.maxLifeTime = this.maxLifeTime;
  45890. serializationObject.emitRate = this.emitRate;
  45891. serializationObject.minEmitBox = this.minEmitBox.asArray();
  45892. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  45893. serializationObject.gravity = this.gravity.asArray();
  45894. serializationObject.direction1 = this.direction1.asArray();
  45895. serializationObject.direction2 = this.direction2.asArray();
  45896. serializationObject.color1 = this.color1.asArray();
  45897. serializationObject.color2 = this.color2.asArray();
  45898. serializationObject.colorDead = this.colorDead.asArray();
  45899. serializationObject.updateSpeed = this.updateSpeed;
  45900. serializationObject.targetStopDuration = this.targetStopDuration;
  45901. serializationObject.textureMask = this.textureMask.asArray();
  45902. serializationObject.blendMode = this.blendMode;
  45903. serializationObject.customShader = this.customShader;
  45904. serializationObject.preventAutoStart = this.preventAutoStart;
  45905. serializationObject.startSpriteCellID = this.startSpriteCellID;
  45906. serializationObject.endSpriteCellID = this.endSpriteCellID;
  45907. serializationObject.spriteCellLoop = this.spriteCellLoop;
  45908. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  45909. serializationObject.spriteCellWidth = this.spriteCellWidth;
  45910. serializationObject.spriteCellHeight = this.spriteCellHeight;
  45911. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  45912. return serializationObject;
  45913. };
  45914. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  45915. var name = parsedParticleSystem.name;
  45916. var custom = null;
  45917. var program = null;
  45918. if (parsedParticleSystem.customShader) {
  45919. program = parsedParticleSystem.customShader;
  45920. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  45921. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  45922. }
  45923. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  45924. particleSystem.customShader = program;
  45925. if (parsedParticleSystem.id) {
  45926. particleSystem.id = parsedParticleSystem.id;
  45927. }
  45928. // Auto start
  45929. if (parsedParticleSystem.preventAutoStart) {
  45930. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  45931. }
  45932. // Texture
  45933. if (parsedParticleSystem.textureName) {
  45934. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  45935. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  45936. }
  45937. // Emitter
  45938. if (parsedParticleSystem.emitterId) {
  45939. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  45940. }
  45941. else {
  45942. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  45943. }
  45944. // Animations
  45945. if (parsedParticleSystem.animations) {
  45946. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  45947. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  45948. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  45949. }
  45950. }
  45951. if (parsedParticleSystem.autoAnimate) {
  45952. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  45953. }
  45954. // Particle system
  45955. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  45956. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  45957. particleSystem.minSize = parsedParticleSystem.minSize;
  45958. particleSystem.maxSize = parsedParticleSystem.maxSize;
  45959. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  45960. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  45961. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  45962. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  45963. particleSystem.emitRate = parsedParticleSystem.emitRate;
  45964. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  45965. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  45966. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  45967. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  45968. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  45969. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  45970. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  45971. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  45972. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  45973. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  45974. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  45975. particleSystem.blendMode = parsedParticleSystem.blendMode;
  45976. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  45977. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  45978. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  45979. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  45980. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  45981. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  45982. if (!particleSystem.preventAutoStart) {
  45983. particleSystem.start();
  45984. }
  45985. return particleSystem;
  45986. };
  45987. // Statics
  45988. ParticleSystem.BLENDMODE_ONEONE = 0;
  45989. ParticleSystem.BLENDMODE_STANDARD = 1;
  45990. return ParticleSystem;
  45991. }());
  45992. BABYLON.ParticleSystem = ParticleSystem;
  45993. })(BABYLON || (BABYLON = {}));
  45994. //# sourceMappingURL=babylon.particleSystem.js.map
  45995. var BABYLON;
  45996. (function (BABYLON) {
  45997. var SolidParticle = /** @class */ (function () {
  45998. /**
  45999. * Creates a Solid Particle object.
  46000. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  46001. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  46002. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  46003. * `indiceIndex` (integer) is the starting index of the particle indices in the SPS "indices" array.
  46004. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  46005. * `shapeId` (integer) is the model shape identifier in the SPS.
  46006. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  46007. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  46008. */
  46009. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  46010. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  46011. this.idx = 0; // particle global index
  46012. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  46013. this.position = BABYLON.Vector3.Zero(); // position
  46014. this.rotation = BABYLON.Vector3.Zero(); // rotation
  46015. this.scaling = BABYLON.Vector3.One(); // scaling
  46016. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  46017. this.velocity = BABYLON.Vector3.Zero(); // velocity
  46018. this.pivot = BABYLON.Vector3.Zero(); // pivot point in the particle local space
  46019. this.alive = true; // alive
  46020. this.isVisible = true; // visibility
  46021. this._pos = 0; // index of this particle in the global "positions" array
  46022. this._ind = 0; // index of this particle in the global "indices" array
  46023. this.shapeId = 0; // model shape id
  46024. this.idxInShape = 0; // index of the particle in its shape id
  46025. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  46026. this.idx = particleIndex;
  46027. this._pos = positionIndex;
  46028. this._ind = indiceIndex;
  46029. this._model = model;
  46030. this.shapeId = shapeId;
  46031. this.idxInShape = idxInShape;
  46032. this._sps = sps;
  46033. if (modelBoundingInfo) {
  46034. this._modelBoundingInfo = modelBoundingInfo;
  46035. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  46036. }
  46037. }
  46038. Object.defineProperty(SolidParticle.prototype, "scale", {
  46039. /**
  46040. * legacy support, changed scale to scaling
  46041. */
  46042. get: function () {
  46043. return this.scaling;
  46044. },
  46045. set: function (scale) {
  46046. this.scaling = scale;
  46047. },
  46048. enumerable: true,
  46049. configurable: true
  46050. });
  46051. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  46052. /**
  46053. * legacy support, changed quaternion to rotationQuaternion
  46054. */
  46055. get: function () {
  46056. return this.rotationQuaternion;
  46057. },
  46058. set: function (q) {
  46059. this.rotationQuaternion = q;
  46060. },
  46061. enumerable: true,
  46062. configurable: true
  46063. });
  46064. /**
  46065. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  46066. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  46067. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  46068. */
  46069. SolidParticle.prototype.intersectsMesh = function (target) {
  46070. if (!this._boundingInfo || !target._boundingInfo) {
  46071. return false;
  46072. }
  46073. if (this._sps._bSphereOnly) {
  46074. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  46075. }
  46076. return this._boundingInfo.intersects(target._boundingInfo, false);
  46077. };
  46078. return SolidParticle;
  46079. }());
  46080. BABYLON.SolidParticle = SolidParticle;
  46081. var ModelShape = /** @class */ (function () {
  46082. /**
  46083. * 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.
  46084. * SPS internal tool, don't use it manually.
  46085. */
  46086. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  46087. this._indicesLength = 0; // length of the shape in the model indices array
  46088. this.shapeID = id;
  46089. this._shape = shape;
  46090. this._indicesLength = indicesLength;
  46091. this._shapeUV = shapeUV;
  46092. this._positionFunction = posFunction;
  46093. this._vertexFunction = vtxFunction;
  46094. }
  46095. return ModelShape;
  46096. }());
  46097. BABYLON.ModelShape = ModelShape;
  46098. var DepthSortedParticle = /** @class */ (function () {
  46099. function DepthSortedParticle() {
  46100. this.ind = 0; // index of the particle in the "indices" array
  46101. this.indicesLength = 0; // length of the particle shape in the "indices" array
  46102. this.sqDistance = 0.0; // squared distance from the particle to the camera
  46103. }
  46104. return DepthSortedParticle;
  46105. }());
  46106. BABYLON.DepthSortedParticle = DepthSortedParticle;
  46107. })(BABYLON || (BABYLON = {}));
  46108. //# sourceMappingURL=babylon.solidParticle.js.map
  46109. var BABYLON;
  46110. (function (BABYLON) {
  46111. /**
  46112. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  46113. */
  46114. var SolidParticleSystem = /** @class */ (function () {
  46115. /**
  46116. * Creates a SPS (Solid Particle System) object.
  46117. * `name` (String) is the SPS name, this will be the underlying mesh name.
  46118. * `scene` (Scene) is the scene in which the SPS is added.
  46119. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  46120. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  46121. * `enableDepthSort` (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  46122. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  46123. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  46124. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  46125. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  46126. */
  46127. function SolidParticleSystem(name, scene, options) {
  46128. // public members
  46129. /**
  46130. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  46131. * Example : var p = SPS.particles[i];
  46132. */
  46133. this.particles = new Array();
  46134. /**
  46135. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  46136. */
  46137. this.nbParticles = 0;
  46138. /**
  46139. * If the particles must ever face the camera (default false). Useful for planar particles.
  46140. */
  46141. this.billboard = false;
  46142. /**
  46143. * Recompute normals when adding a shape
  46144. */
  46145. this.recomputeNormals = true;
  46146. /**
  46147. * This a counter ofr your own usage. It's not set by any SPS functions.
  46148. */
  46149. this.counter = 0;
  46150. /**
  46151. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  46152. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  46153. */
  46154. this.vars = {};
  46155. this._positions = new Array();
  46156. this._indices = new Array();
  46157. this._normals = new Array();
  46158. this._colors = new Array();
  46159. this._uvs = new Array();
  46160. this._index = 0; // indices index
  46161. this._updatable = true;
  46162. this._pickable = false;
  46163. this._isVisibilityBoxLocked = false;
  46164. this._alwaysVisible = false;
  46165. this._depthSort = false;
  46166. this._shapeCounter = 0;
  46167. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  46168. this._color = new BABYLON.Color4(0, 0, 0, 0);
  46169. this._computeParticleColor = true;
  46170. this._computeParticleTexture = true;
  46171. this._computeParticleRotation = true;
  46172. this._computeParticleVertex = false;
  46173. this._computeBoundingBox = false;
  46174. this._depthSortParticles = true;
  46175. this._cam_axisZ = BABYLON.Vector3.Zero();
  46176. this._cam_axisY = BABYLON.Vector3.Zero();
  46177. this._cam_axisX = BABYLON.Vector3.Zero();
  46178. this._axisZ = BABYLON.Axis.Z;
  46179. this._camDir = BABYLON.Vector3.Zero();
  46180. this._camInvertedPosition = BABYLON.Vector3.Zero();
  46181. this._rotMatrix = new BABYLON.Matrix();
  46182. this._invertMatrix = new BABYLON.Matrix();
  46183. this._rotated = BABYLON.Vector3.Zero();
  46184. this._quaternion = new BABYLON.Quaternion();
  46185. this._vertex = BABYLON.Vector3.Zero();
  46186. this._normal = BABYLON.Vector3.Zero();
  46187. this._yaw = 0.0;
  46188. this._pitch = 0.0;
  46189. this._roll = 0.0;
  46190. this._halfroll = 0.0;
  46191. this._halfpitch = 0.0;
  46192. this._halfyaw = 0.0;
  46193. this._sinRoll = 0.0;
  46194. this._cosRoll = 0.0;
  46195. this._sinPitch = 0.0;
  46196. this._cosPitch = 0.0;
  46197. this._sinYaw = 0.0;
  46198. this._cosYaw = 0.0;
  46199. this._mustUnrotateFixedNormals = false;
  46200. this._minimum = BABYLON.Tmp.Vector3[0];
  46201. this._maximum = BABYLON.Tmp.Vector3[1];
  46202. this._minBbox = BABYLON.Tmp.Vector3[4];
  46203. this._maxBbox = BABYLON.Tmp.Vector3[5];
  46204. this._particlesIntersect = false;
  46205. this._depthSortFunction = function (p1, p2) {
  46206. return (p2.sqDistance - p1.sqDistance);
  46207. };
  46208. this._needs32Bits = false;
  46209. this._bSphereOnly = false;
  46210. this._bSphereRadiusFactor = 1.0;
  46211. this.name = name;
  46212. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46213. this._camera = scene.activeCamera;
  46214. this._pickable = options ? options.isPickable : false;
  46215. this._depthSort = options ? options.enableDepthSort : false;
  46216. this._particlesIntersect = options ? options.particleIntersection : false;
  46217. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  46218. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  46219. if (options && options.updatable) {
  46220. this._updatable = options.updatable;
  46221. }
  46222. else {
  46223. this._updatable = true;
  46224. }
  46225. if (this._pickable) {
  46226. this.pickedParticles = [];
  46227. }
  46228. if (this._depthSort) {
  46229. this.depthSortedParticles = [];
  46230. }
  46231. }
  46232. /**
  46233. * Builds the SPS underlying mesh. Returns a standard Mesh.
  46234. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  46235. */
  46236. SolidParticleSystem.prototype.buildMesh = function () {
  46237. if (this.nbParticles === 0) {
  46238. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  46239. this.addShape(triangle, 1);
  46240. triangle.dispose();
  46241. }
  46242. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  46243. this._positions32 = new Float32Array(this._positions);
  46244. this._uvs32 = new Float32Array(this._uvs);
  46245. this._colors32 = new Float32Array(this._colors);
  46246. if (this.recomputeNormals) {
  46247. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  46248. }
  46249. this._normals32 = new Float32Array(this._normals);
  46250. this._fixedNormal32 = new Float32Array(this._normals);
  46251. if (this._mustUnrotateFixedNormals) {
  46252. this._unrotateFixedNormals();
  46253. }
  46254. var vertexData = new BABYLON.VertexData();
  46255. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  46256. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  46257. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  46258. if (this._uvs32) {
  46259. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  46260. ;
  46261. }
  46262. if (this._colors32) {
  46263. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  46264. }
  46265. var mesh = new BABYLON.Mesh(this.name, this._scene);
  46266. vertexData.applyToMesh(mesh, this._updatable);
  46267. this.mesh = mesh;
  46268. this.mesh.isPickable = this._pickable;
  46269. // free memory
  46270. if (!this._depthSort) {
  46271. this._indices = null;
  46272. }
  46273. this._positions = null;
  46274. this._normals = null;
  46275. this._uvs = null;
  46276. this._colors = null;
  46277. if (!this._updatable) {
  46278. this.particles.length = 0;
  46279. }
  46280. return mesh;
  46281. };
  46282. /**
  46283. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  46284. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  46285. * Thus the particles generated from `digest()` have their property `position` set yet.
  46286. * `mesh` ( Mesh ) is the mesh to be digested
  46287. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  46288. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  46289. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  46290. */
  46291. SolidParticleSystem.prototype.digest = function (mesh, options) {
  46292. var size = (options && options.facetNb) || 1;
  46293. var number = (options && options.number) || 0;
  46294. var delta = (options && options.delta) || 0;
  46295. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46296. var meshInd = mesh.getIndices();
  46297. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  46298. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  46299. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  46300. var f = 0; // facet counter
  46301. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  46302. // compute size from number
  46303. if (number) {
  46304. number = (number > totalFacets) ? totalFacets : number;
  46305. size = Math.round(totalFacets / number);
  46306. delta = 0;
  46307. }
  46308. else {
  46309. size = (size > totalFacets) ? totalFacets : size;
  46310. }
  46311. var facetPos = []; // submesh positions
  46312. var facetInd = []; // submesh indices
  46313. var facetUV = []; // submesh UV
  46314. var facetCol = []; // submesh colors
  46315. var barycenter = BABYLON.Tmp.Vector3[0];
  46316. var sizeO = size;
  46317. while (f < totalFacets) {
  46318. size = sizeO + Math.floor((1 + delta) * Math.random());
  46319. if (f > totalFacets - size) {
  46320. size = totalFacets - f;
  46321. }
  46322. // reset temp arrays
  46323. facetPos.length = 0;
  46324. facetInd.length = 0;
  46325. facetUV.length = 0;
  46326. facetCol.length = 0;
  46327. // iterate over "size" facets
  46328. var fi = 0;
  46329. for (var j = f * 3; j < (f + size) * 3; j++) {
  46330. facetInd.push(fi);
  46331. var i = meshInd[j];
  46332. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  46333. if (meshUV) {
  46334. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  46335. }
  46336. if (meshCol) {
  46337. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  46338. }
  46339. fi++;
  46340. }
  46341. // create a model shape for each single particle
  46342. var idx = this.nbParticles;
  46343. var shape = this._posToShape(facetPos);
  46344. var shapeUV = this._uvsToShapeUV(facetUV);
  46345. // compute the barycenter of the shape
  46346. var v;
  46347. for (v = 0; v < shape.length; v++) {
  46348. barycenter.addInPlace(shape[v]);
  46349. }
  46350. barycenter.scaleInPlace(1 / shape.length);
  46351. // shift the shape from its barycenter to the origin
  46352. for (v = 0; v < shape.length; v++) {
  46353. shape[v].subtractInPlace(barycenter);
  46354. }
  46355. var bInfo;
  46356. if (this._particlesIntersect) {
  46357. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  46358. }
  46359. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  46360. // add the particle in the SPS
  46361. var currentPos = this._positions.length;
  46362. var currentInd = this._indices.length;
  46363. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  46364. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  46365. // initialize the particle position
  46366. this.particles[this.nbParticles].position.addInPlace(barycenter);
  46367. this._index += shape.length;
  46368. idx++;
  46369. this.nbParticles++;
  46370. this._shapeCounter++;
  46371. f += size;
  46372. }
  46373. return this;
  46374. };
  46375. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  46376. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  46377. var index = 0;
  46378. var idx = 0;
  46379. for (var p = 0; p < this.particles.length; p++) {
  46380. this._particle = this.particles[p];
  46381. this._shape = this._particle._model._shape;
  46382. if (this._particle.rotationQuaternion) {
  46383. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  46384. }
  46385. else {
  46386. this._yaw = this._particle.rotation.y;
  46387. this._pitch = this._particle.rotation.x;
  46388. this._roll = this._particle.rotation.z;
  46389. this._quaternionRotationYPR();
  46390. }
  46391. this._quaternionToRotationMatrix();
  46392. this._rotMatrix.invertToRef(this._invertMatrix);
  46393. for (var pt = 0; pt < this._shape.length; pt++) {
  46394. idx = index + pt * 3;
  46395. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  46396. this._fixedNormal32[idx] = this._normal.x;
  46397. this._fixedNormal32[idx + 1] = this._normal.y;
  46398. this._fixedNormal32[idx + 2] = this._normal.z;
  46399. }
  46400. index = idx + 3;
  46401. }
  46402. };
  46403. //reset copy
  46404. SolidParticleSystem.prototype._resetCopy = function () {
  46405. this._copy.position.x = 0;
  46406. this._copy.position.y = 0;
  46407. this._copy.position.z = 0;
  46408. this._copy.rotation.x = 0;
  46409. this._copy.rotation.y = 0;
  46410. this._copy.rotation.z = 0;
  46411. this._copy.rotationQuaternion = null;
  46412. this._copy.scaling.x = 1.0;
  46413. this._copy.scaling.y = 1.0;
  46414. this._copy.scaling.z = 1.0;
  46415. this._copy.uvs.x = 0;
  46416. this._copy.uvs.y = 0;
  46417. this._copy.uvs.z = 1.0;
  46418. this._copy.uvs.w = 1.0;
  46419. this._copy.color = null;
  46420. };
  46421. // _meshBuilder : inserts the shape model in the global SPS mesh
  46422. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  46423. var i;
  46424. var u = 0;
  46425. var c = 0;
  46426. var n = 0;
  46427. this._resetCopy();
  46428. if (options && options.positionFunction) {
  46429. options.positionFunction(this._copy, idx, idxInShape);
  46430. this._mustUnrotateFixedNormals = true;
  46431. }
  46432. if (this._copy.rotationQuaternion) {
  46433. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  46434. }
  46435. else {
  46436. this._yaw = this._copy.rotation.y;
  46437. this._pitch = this._copy.rotation.x;
  46438. this._roll = this._copy.rotation.z;
  46439. this._quaternionRotationYPR();
  46440. }
  46441. this._quaternionToRotationMatrix();
  46442. for (i = 0; i < shape.length; i++) {
  46443. this._vertex.x = shape[i].x;
  46444. this._vertex.y = shape[i].y;
  46445. this._vertex.z = shape[i].z;
  46446. if (options && options.vertexFunction) {
  46447. options.vertexFunction(this._copy, this._vertex, i);
  46448. }
  46449. this._vertex.x *= this._copy.scaling.x;
  46450. this._vertex.y *= this._copy.scaling.y;
  46451. this._vertex.z *= this._copy.scaling.z;
  46452. this._vertex.x += this._copy.pivot.x;
  46453. this._vertex.y += this._copy.pivot.y;
  46454. this._vertex.z += this._copy.pivot.z;
  46455. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  46456. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  46457. if (meshUV) {
  46458. 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);
  46459. u += 2;
  46460. }
  46461. if (this._copy.color) {
  46462. this._color = this._copy.color;
  46463. }
  46464. else if (meshCol && meshCol[c] !== undefined) {
  46465. this._color.r = meshCol[c];
  46466. this._color.g = meshCol[c + 1];
  46467. this._color.b = meshCol[c + 2];
  46468. this._color.a = meshCol[c + 3];
  46469. }
  46470. else {
  46471. this._color.r = 1.0;
  46472. this._color.g = 1.0;
  46473. this._color.b = 1.0;
  46474. this._color.a = 1.0;
  46475. }
  46476. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  46477. c += 4;
  46478. if (!this.recomputeNormals && meshNor) {
  46479. this._normal.x = meshNor[n];
  46480. this._normal.y = meshNor[n + 1];
  46481. this._normal.z = meshNor[n + 2];
  46482. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  46483. normals.push(this._normal.x, this._normal.y, this._normal.z);
  46484. n += 3;
  46485. }
  46486. }
  46487. for (i = 0; i < meshInd.length; i++) {
  46488. var current_ind = p + meshInd[i];
  46489. indices.push(current_ind);
  46490. if (current_ind > 65535) {
  46491. this._needs32Bits = true;
  46492. }
  46493. }
  46494. if (this._pickable) {
  46495. var nbfaces = meshInd.length / 3;
  46496. for (i = 0; i < nbfaces; i++) {
  46497. this.pickedParticles.push({ idx: idx, faceId: i });
  46498. }
  46499. }
  46500. if (this._depthSort) {
  46501. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  46502. }
  46503. return this._copy;
  46504. };
  46505. // returns a shape array from positions array
  46506. SolidParticleSystem.prototype._posToShape = function (positions) {
  46507. var shape = [];
  46508. for (var i = 0; i < positions.length; i += 3) {
  46509. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  46510. }
  46511. return shape;
  46512. };
  46513. // returns a shapeUV array from a Vector4 uvs
  46514. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  46515. var shapeUV = [];
  46516. if (uvs) {
  46517. for (var i = 0; i < uvs.length; i++)
  46518. shapeUV.push(uvs[i]);
  46519. }
  46520. return shapeUV;
  46521. };
  46522. // adds a new particle object in the particles array
  46523. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  46524. if (bInfo === void 0) { bInfo = null; }
  46525. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  46526. this.particles.push(sp);
  46527. return sp;
  46528. };
  46529. /**
  46530. * Adds some particles to the SPS from the model shape. Returns the shape id.
  46531. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  46532. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  46533. * `nb` (positive integer) the number of particles to be created from this model
  46534. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  46535. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  46536. */
  46537. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  46538. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46539. var meshInd = mesh.getIndices();
  46540. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  46541. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  46542. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  46543. var bbInfo;
  46544. if (this._particlesIntersect) {
  46545. bbInfo = mesh.getBoundingInfo();
  46546. }
  46547. var shape = this._posToShape(meshPos);
  46548. var shapeUV = this._uvsToShapeUV(meshUV);
  46549. var posfunc = options ? options.positionFunction : null;
  46550. var vtxfunc = options ? options.vertexFunction : null;
  46551. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  46552. // particles
  46553. var sp;
  46554. var currentCopy;
  46555. var idx = this.nbParticles;
  46556. for (var i = 0; i < nb; i++) {
  46557. var currentPos = this._positions.length;
  46558. var currentInd = this._indices.length;
  46559. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  46560. if (this._updatable) {
  46561. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  46562. sp.position.copyFrom(currentCopy.position);
  46563. sp.rotation.copyFrom(currentCopy.rotation);
  46564. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  46565. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  46566. }
  46567. if (currentCopy.color && sp.color) {
  46568. sp.color.copyFrom(currentCopy.color);
  46569. }
  46570. sp.scaling.copyFrom(currentCopy.scaling);
  46571. sp.uvs.copyFrom(currentCopy.uvs);
  46572. }
  46573. this._index += shape.length;
  46574. idx++;
  46575. }
  46576. this.nbParticles += nb;
  46577. this._shapeCounter++;
  46578. return this._shapeCounter - 1;
  46579. };
  46580. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  46581. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  46582. this._resetCopy();
  46583. if (particle._model._positionFunction) {
  46584. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  46585. }
  46586. if (this._copy.rotationQuaternion) {
  46587. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  46588. }
  46589. else {
  46590. this._yaw = this._copy.rotation.y;
  46591. this._pitch = this._copy.rotation.x;
  46592. this._roll = this._copy.rotation.z;
  46593. this._quaternionRotationYPR();
  46594. }
  46595. this._quaternionToRotationMatrix();
  46596. this._shape = particle._model._shape;
  46597. for (var pt = 0; pt < this._shape.length; pt++) {
  46598. this._vertex.x = this._shape[pt].x;
  46599. this._vertex.y = this._shape[pt].y;
  46600. this._vertex.z = this._shape[pt].z;
  46601. if (particle._model._vertexFunction) {
  46602. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  46603. }
  46604. this._vertex.x *= this._copy.scaling.x;
  46605. this._vertex.y *= this._copy.scaling.y;
  46606. this._vertex.z *= this._copy.scaling.z;
  46607. this._vertex.x += this._copy.pivot.x;
  46608. this._vertex.y += this._copy.pivot.y;
  46609. this._vertex.z += this._copy.pivot.z;
  46610. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  46611. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  46612. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  46613. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  46614. }
  46615. particle.position.x = 0.0;
  46616. particle.position.y = 0.0;
  46617. particle.position.z = 0.0;
  46618. particle.rotation.x = 0.0;
  46619. particle.rotation.y = 0.0;
  46620. particle.rotation.z = 0.0;
  46621. particle.rotationQuaternion = null;
  46622. particle.scaling.x = 1.0;
  46623. particle.scaling.y = 1.0;
  46624. particle.scaling.z = 1.0;
  46625. };
  46626. /**
  46627. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  46628. * Returns the SPS.
  46629. */
  46630. SolidParticleSystem.prototype.rebuildMesh = function () {
  46631. for (var p = 0; p < this.particles.length; p++) {
  46632. this._rebuildParticle(this.particles[p]);
  46633. }
  46634. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  46635. return this;
  46636. };
  46637. /**
  46638. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  46639. * This method calls `updateParticle()` for each particle of the SPS.
  46640. * For an animated SPS, it is usually called within the render loop.
  46641. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  46642. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  46643. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  46644. * Returns the SPS.
  46645. */
  46646. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  46647. if (start === void 0) { start = 0; }
  46648. if (end === void 0) { end = this.nbParticles - 1; }
  46649. if (update === void 0) { update = true; }
  46650. if (!this._updatable) {
  46651. return this;
  46652. }
  46653. // custom beforeUpdate
  46654. this.beforeUpdateParticles(start, end, update);
  46655. this._cam_axisX.x = 1.0;
  46656. this._cam_axisX.y = 0.0;
  46657. this._cam_axisX.z = 0.0;
  46658. this._cam_axisY.x = 0.0;
  46659. this._cam_axisY.y = 1.0;
  46660. this._cam_axisY.z = 0.0;
  46661. this._cam_axisZ.x = 0.0;
  46662. this._cam_axisZ.y = 0.0;
  46663. this._cam_axisZ.z = 1.0;
  46664. // cases when the World Matrix is to be computed first
  46665. if (this.billboard || this._depthSort) {
  46666. this.mesh.computeWorldMatrix(true);
  46667. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  46668. }
  46669. // if the particles will always face the camera
  46670. if (this.billboard) {
  46671. // compute the camera position and un-rotate it by the current mesh rotation
  46672. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  46673. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  46674. this._cam_axisZ.normalize();
  46675. // same for camera up vector extracted from the cam view matrix
  46676. var view = this._camera.getViewMatrix(true);
  46677. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  46678. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  46679. this._cam_axisY.normalize();
  46680. this._cam_axisX.normalize();
  46681. }
  46682. // if depthSort, compute the camera global position in the mesh local system
  46683. if (this._depthSort) {
  46684. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  46685. }
  46686. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  46687. var idx = 0; // current position index in the global array positions32
  46688. var index = 0; // position start index in the global array positions32 of the current particle
  46689. var colidx = 0; // current color index in the global array colors32
  46690. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  46691. var uvidx = 0; // current uv index in the global array uvs32
  46692. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  46693. var pt = 0; // current index in the particle model shape
  46694. if (this.mesh.isFacetDataEnabled) {
  46695. this._computeBoundingBox = true;
  46696. }
  46697. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  46698. if (this._computeBoundingBox) {
  46699. if (start == 0 && end == this.nbParticles - 1) {
  46700. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  46701. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  46702. }
  46703. else {
  46704. if (this.mesh._boundingInfo) {
  46705. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  46706. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  46707. }
  46708. }
  46709. }
  46710. // particle loop
  46711. index = this.particles[start]._pos;
  46712. var vpos = (index / 3) | 0;
  46713. colorIndex = vpos * 4;
  46714. uvIndex = vpos * 2;
  46715. for (var p = start; p <= end; p++) {
  46716. this._particle = this.particles[p];
  46717. this._shape = this._particle._model._shape;
  46718. this._shapeUV = this._particle._model._shapeUV;
  46719. // call to custom user function to update the particle properties
  46720. this.updateParticle(this._particle);
  46721. // camera-particle distance for depth sorting
  46722. if (this._depthSort && this._depthSortParticles) {
  46723. var dsp = this.depthSortedParticles[p];
  46724. dsp.ind = this._particle._ind;
  46725. dsp.indicesLength = this._particle._model._indicesLength;
  46726. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  46727. }
  46728. // skip the computations for inactive or already invisible particles
  46729. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  46730. // increment indexes for the next particle
  46731. pt = this._shape.length;
  46732. index += pt * 3;
  46733. colorIndex += pt * 4;
  46734. uvIndex += pt * 2;
  46735. continue;
  46736. }
  46737. if (this._particle.isVisible) {
  46738. this._particle._stillInvisible = false; // un-mark permanent invisibility
  46739. // particle rotation matrix
  46740. if (this.billboard) {
  46741. this._particle.rotation.x = 0.0;
  46742. this._particle.rotation.y = 0.0;
  46743. }
  46744. if (this._computeParticleRotation || this.billboard) {
  46745. if (this._particle.rotationQuaternion) {
  46746. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  46747. }
  46748. else {
  46749. this._yaw = this._particle.rotation.y;
  46750. this._pitch = this._particle.rotation.x;
  46751. this._roll = this._particle.rotation.z;
  46752. this._quaternionRotationYPR();
  46753. }
  46754. this._quaternionToRotationMatrix();
  46755. }
  46756. // particle vertex loop
  46757. for (pt = 0; pt < this._shape.length; pt++) {
  46758. idx = index + pt * 3;
  46759. colidx = colorIndex + pt * 4;
  46760. uvidx = uvIndex + pt * 2;
  46761. this._vertex.x = this._shape[pt].x;
  46762. this._vertex.y = this._shape[pt].y;
  46763. this._vertex.z = this._shape[pt].z;
  46764. if (this._computeParticleVertex) {
  46765. this.updateParticleVertex(this._particle, this._vertex, pt);
  46766. }
  46767. // positions
  46768. this._vertex.x *= this._particle.scaling.x;
  46769. this._vertex.y *= this._particle.scaling.y;
  46770. this._vertex.z *= this._particle.scaling.z;
  46771. this._vertex.x += this._particle.pivot.x;
  46772. this._vertex.y += this._particle.pivot.y;
  46773. this._vertex.z += this._particle.pivot.z;
  46774. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  46775. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  46776. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  46777. 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;
  46778. 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;
  46779. 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;
  46780. if (this._computeBoundingBox) {
  46781. if (this._positions32[idx] < this._minimum.x) {
  46782. this._minimum.x = this._positions32[idx];
  46783. }
  46784. if (this._positions32[idx] > this._maximum.x) {
  46785. this._maximum.x = this._positions32[idx];
  46786. }
  46787. if (this._positions32[idx + 1] < this._minimum.y) {
  46788. this._minimum.y = this._positions32[idx + 1];
  46789. }
  46790. if (this._positions32[idx + 1] > this._maximum.y) {
  46791. this._maximum.y = this._positions32[idx + 1];
  46792. }
  46793. if (this._positions32[idx + 2] < this._minimum.z) {
  46794. this._minimum.z = this._positions32[idx + 2];
  46795. }
  46796. if (this._positions32[idx + 2] > this._maximum.z) {
  46797. this._maximum.z = this._positions32[idx + 2];
  46798. }
  46799. }
  46800. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  46801. if (!this._computeParticleVertex) {
  46802. this._normal.x = this._fixedNormal32[idx];
  46803. this._normal.y = this._fixedNormal32[idx + 1];
  46804. this._normal.z = this._fixedNormal32[idx + 2];
  46805. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  46806. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  46807. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  46808. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  46809. 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;
  46810. 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;
  46811. }
  46812. if (this._computeParticleColor && this._particle.color) {
  46813. this._colors32[colidx] = this._particle.color.r;
  46814. this._colors32[colidx + 1] = this._particle.color.g;
  46815. this._colors32[colidx + 2] = this._particle.color.b;
  46816. this._colors32[colidx + 3] = this._particle.color.a;
  46817. }
  46818. if (this._computeParticleTexture) {
  46819. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  46820. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  46821. }
  46822. }
  46823. }
  46824. else {
  46825. this._particle._stillInvisible = true; // mark the particle as invisible
  46826. for (pt = 0; pt < this._shape.length; pt++) {
  46827. idx = index + pt * 3;
  46828. colidx = colorIndex + pt * 4;
  46829. uvidx = uvIndex + pt * 2;
  46830. this._positions32[idx] = 0.0;
  46831. this._positions32[idx + 1] = 0.0;
  46832. this._positions32[idx + 2] = 0.0;
  46833. this._normals32[idx] = 0.0;
  46834. this._normals32[idx + 1] = 0.0;
  46835. this._normals32[idx + 2] = 0.0;
  46836. if (this._computeParticleColor && this._particle.color) {
  46837. this._colors32[colidx] = this._particle.color.r;
  46838. this._colors32[colidx + 1] = this._particle.color.g;
  46839. this._colors32[colidx + 2] = this._particle.color.b;
  46840. this._colors32[colidx + 3] = this._particle.color.a;
  46841. }
  46842. if (this._computeParticleTexture) {
  46843. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  46844. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  46845. }
  46846. }
  46847. }
  46848. // if the particle intersections must be computed : update the bbInfo
  46849. if (this._particlesIntersect) {
  46850. var bInfo = this._particle._boundingInfo;
  46851. var bBox = bInfo.boundingBox;
  46852. var bSphere = bInfo.boundingSphere;
  46853. if (!this._bSphereOnly) {
  46854. // place, scale and rotate the particle bbox within the SPS local system, then update it
  46855. for (var b = 0; b < bBox.vectors.length; b++) {
  46856. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  46857. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  46858. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  46859. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  46860. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  46861. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  46862. 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;
  46863. 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;
  46864. 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;
  46865. }
  46866. bBox._update(this.mesh._worldMatrix);
  46867. }
  46868. // place and scale the particle bouding sphere in the SPS local system, then update it
  46869. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  46870. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  46871. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  46872. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  46873. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  46874. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  46875. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  46876. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  46877. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  46878. 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));
  46879. bSphere._update(this.mesh._worldMatrix);
  46880. }
  46881. // increment indexes for the next particle
  46882. index = idx + 3;
  46883. colorIndex = colidx + 4;
  46884. uvIndex = uvidx + 2;
  46885. }
  46886. // if the VBO must be updated
  46887. if (update) {
  46888. if (this._computeParticleColor) {
  46889. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  46890. }
  46891. if (this._computeParticleTexture) {
  46892. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  46893. }
  46894. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  46895. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  46896. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  46897. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  46898. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  46899. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  46900. for (var i = 0; i < this._normals32.length; i++) {
  46901. this._fixedNormal32[i] = this._normals32[i];
  46902. }
  46903. }
  46904. if (!this.mesh.areNormalsFrozen) {
  46905. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  46906. }
  46907. }
  46908. if (this._depthSort && this._depthSortParticles) {
  46909. this.depthSortedParticles.sort(this._depthSortFunction);
  46910. var dspl = this.depthSortedParticles.length;
  46911. var sorted = 0;
  46912. var lind = 0;
  46913. var sind = 0;
  46914. var sid = 0;
  46915. for (sorted = 0; sorted < dspl; sorted++) {
  46916. lind = this.depthSortedParticles[sorted].indicesLength;
  46917. sind = this.depthSortedParticles[sorted].ind;
  46918. for (var i = 0; i < lind; i++) {
  46919. this._indices32[sid] = this._indices[sind + i];
  46920. sid++;
  46921. }
  46922. }
  46923. this.mesh.updateIndices(this._indices32);
  46924. }
  46925. }
  46926. if (this._computeBoundingBox) {
  46927. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  46928. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  46929. }
  46930. this.afterUpdateParticles(start, end, update);
  46931. return this;
  46932. };
  46933. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  46934. this._halfroll = this._roll * 0.5;
  46935. this._halfpitch = this._pitch * 0.5;
  46936. this._halfyaw = this._yaw * 0.5;
  46937. this._sinRoll = Math.sin(this._halfroll);
  46938. this._cosRoll = Math.cos(this._halfroll);
  46939. this._sinPitch = Math.sin(this._halfpitch);
  46940. this._cosPitch = Math.cos(this._halfpitch);
  46941. this._sinYaw = Math.sin(this._halfyaw);
  46942. this._cosYaw = Math.cos(this._halfyaw);
  46943. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  46944. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  46945. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  46946. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  46947. };
  46948. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  46949. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  46950. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  46951. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  46952. this._rotMatrix.m[3] = 0;
  46953. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  46954. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  46955. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  46956. this._rotMatrix.m[7] = 0;
  46957. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  46958. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  46959. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  46960. this._rotMatrix.m[11] = 0;
  46961. this._rotMatrix.m[12] = 0;
  46962. this._rotMatrix.m[13] = 0;
  46963. this._rotMatrix.m[14] = 0;
  46964. this._rotMatrix.m[15] = 1.0;
  46965. };
  46966. /**
  46967. * Disposes the SPS.
  46968. * Returns nothing.
  46969. */
  46970. SolidParticleSystem.prototype.dispose = function () {
  46971. this.mesh.dispose();
  46972. this.vars = null;
  46973. // drop references to internal big arrays for the GC
  46974. this._positions = null;
  46975. this._indices = null;
  46976. this._normals = null;
  46977. this._uvs = null;
  46978. this._colors = null;
  46979. this._indices32 = null;
  46980. this._positions32 = null;
  46981. this._normals32 = null;
  46982. this._fixedNormal32 = null;
  46983. this._uvs32 = null;
  46984. this._colors32 = null;
  46985. this.pickedParticles = null;
  46986. };
  46987. /**
  46988. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  46989. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  46990. * Returns the SPS.
  46991. */
  46992. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  46993. if (!this._isVisibilityBoxLocked) {
  46994. this.mesh.refreshBoundingInfo();
  46995. }
  46996. return this;
  46997. };
  46998. /**
  46999. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  47000. * @param size the size (float) of the visibility box
  47001. * note : this doesn't lock the SPS mesh bounding box.
  47002. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47003. */
  47004. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  47005. var vis = size / 2;
  47006. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  47007. };
  47008. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  47009. // getter and setter
  47010. get: function () {
  47011. return this._alwaysVisible;
  47012. },
  47013. /**
  47014. * Sets the SPS as always visible or not
  47015. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47016. */
  47017. set: function (val) {
  47018. this._alwaysVisible = val;
  47019. this.mesh.alwaysSelectAsActiveMesh = val;
  47020. },
  47021. enumerable: true,
  47022. configurable: true
  47023. });
  47024. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  47025. get: function () {
  47026. return this._isVisibilityBoxLocked;
  47027. },
  47028. /**
  47029. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  47030. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47031. */
  47032. set: function (val) {
  47033. this._isVisibilityBoxLocked = val;
  47034. var boundingInfo = this.mesh.getBoundingInfo();
  47035. boundingInfo.isLocked = val;
  47036. },
  47037. enumerable: true,
  47038. configurable: true
  47039. });
  47040. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  47041. // getters
  47042. get: function () {
  47043. return this._computeParticleRotation;
  47044. },
  47045. // Optimizer setters
  47046. /**
  47047. * Tells to `setParticles()` to compute the particle rotations or not.
  47048. * Default value : true. The SPS is faster when it's set to false.
  47049. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  47050. */
  47051. set: function (val) {
  47052. this._computeParticleRotation = val;
  47053. },
  47054. enumerable: true,
  47055. configurable: true
  47056. });
  47057. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  47058. get: function () {
  47059. return this._computeParticleColor;
  47060. },
  47061. /**
  47062. * Tells to `setParticles()` to compute the particle colors or not.
  47063. * Default value : true. The SPS is faster when it's set to false.
  47064. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  47065. */
  47066. set: function (val) {
  47067. this._computeParticleColor = val;
  47068. },
  47069. enumerable: true,
  47070. configurable: true
  47071. });
  47072. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  47073. get: function () {
  47074. return this._computeParticleTexture;
  47075. },
  47076. /**
  47077. * Tells to `setParticles()` to compute the particle textures or not.
  47078. * Default value : true. The SPS is faster when it's set to false.
  47079. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  47080. */
  47081. set: function (val) {
  47082. this._computeParticleTexture = val;
  47083. },
  47084. enumerable: true,
  47085. configurable: true
  47086. });
  47087. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  47088. get: function () {
  47089. return this._computeParticleVertex;
  47090. },
  47091. /**
  47092. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  47093. * Default value : false. The SPS is faster when it's set to false.
  47094. * Note : the particle custom vertex positions aren't stored values.
  47095. */
  47096. set: function (val) {
  47097. this._computeParticleVertex = val;
  47098. },
  47099. enumerable: true,
  47100. configurable: true
  47101. });
  47102. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  47103. get: function () {
  47104. return this._computeBoundingBox;
  47105. },
  47106. /**
  47107. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  47108. */
  47109. set: function (val) {
  47110. this._computeBoundingBox = val;
  47111. },
  47112. enumerable: true,
  47113. configurable: true
  47114. });
  47115. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  47116. get: function () {
  47117. return this._depthSortParticles;
  47118. },
  47119. /**
  47120. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  47121. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  47122. * Default : `true`
  47123. */
  47124. set: function (val) {
  47125. this._depthSortParticles = val;
  47126. },
  47127. enumerable: true,
  47128. configurable: true
  47129. });
  47130. // =======================================================================
  47131. // Particle behavior logic
  47132. // these following methods may be overwritten by the user to fit his needs
  47133. /**
  47134. * This function does nothing. It may be overwritten to set all the particle first values.
  47135. * The SPS doesn't call this function, you may have to call it by your own.
  47136. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  47137. */
  47138. SolidParticleSystem.prototype.initParticles = function () {
  47139. };
  47140. /**
  47141. * This function does nothing. It may be overwritten to recycle a particle.
  47142. * The SPS doesn't call this function, you may have to call it by your own.
  47143. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  47144. */
  47145. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  47146. return particle;
  47147. };
  47148. /**
  47149. * Updates a particle : this function should be overwritten by the user.
  47150. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  47151. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  47152. * ex : just set a particle position or velocity and recycle conditions
  47153. */
  47154. SolidParticleSystem.prototype.updateParticle = function (particle) {
  47155. return particle;
  47156. };
  47157. /**
  47158. * Updates a vertex of a particle : it can be overwritten by the user.
  47159. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  47160. * @param particle the current particle
  47161. * @param vertex the current index of the current particle
  47162. * @param pt the index of the current vertex in the particle shape
  47163. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  47164. * ex : just set a vertex particle position
  47165. */
  47166. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  47167. return vertex;
  47168. };
  47169. /**
  47170. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  47171. * This does nothing and may be overwritten by the user.
  47172. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  47173. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  47174. * @param update the boolean update value actually passed to setParticles()
  47175. */
  47176. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  47177. };
  47178. /**
  47179. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  47180. * This will be passed three parameters.
  47181. * This does nothing and may be overwritten by the user.
  47182. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  47183. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  47184. * @param update the boolean update value actually passed to setParticles()
  47185. */
  47186. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  47187. };
  47188. return SolidParticleSystem;
  47189. }());
  47190. BABYLON.SolidParticleSystem = SolidParticleSystem;
  47191. })(BABYLON || (BABYLON = {}));
  47192. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  47193. var BABYLON;
  47194. (function (BABYLON) {
  47195. var GroundMesh = /** @class */ (function (_super) {
  47196. __extends(GroundMesh, _super);
  47197. function GroundMesh(name, scene) {
  47198. var _this = _super.call(this, name, scene) || this;
  47199. _this.generateOctree = false;
  47200. return _this;
  47201. }
  47202. GroundMesh.prototype.getClassName = function () {
  47203. return "GroundMesh";
  47204. };
  47205. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  47206. get: function () {
  47207. return Math.min(this._subdivisionsX, this._subdivisionsY);
  47208. },
  47209. enumerable: true,
  47210. configurable: true
  47211. });
  47212. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  47213. get: function () {
  47214. return this._subdivisionsX;
  47215. },
  47216. enumerable: true,
  47217. configurable: true
  47218. });
  47219. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  47220. get: function () {
  47221. return this._subdivisionsY;
  47222. },
  47223. enumerable: true,
  47224. configurable: true
  47225. });
  47226. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  47227. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  47228. this._subdivisionsX = chunksCount;
  47229. this._subdivisionsY = chunksCount;
  47230. this.subdivide(chunksCount);
  47231. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  47232. };
  47233. /**
  47234. * Returns a height (y) value in the Worl system :
  47235. * the ground altitude at the coordinates (x, z) expressed in the World system.
  47236. * Returns the ground y position if (x, z) are outside the ground surface.
  47237. */
  47238. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  47239. var world = this.getWorldMatrix();
  47240. var invMat = BABYLON.Tmp.Matrix[5];
  47241. world.invertToRef(invMat);
  47242. var tmpVect = BABYLON.Tmp.Vector3[8];
  47243. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  47244. x = tmpVect.x;
  47245. z = tmpVect.z;
  47246. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  47247. return this.position.y;
  47248. }
  47249. if (!this._heightQuads || this._heightQuads.length == 0) {
  47250. this._initHeightQuads();
  47251. this._computeHeightQuads();
  47252. }
  47253. var facet = this._getFacetAt(x, z);
  47254. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  47255. // return y in the World system
  47256. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  47257. return tmpVect.y;
  47258. };
  47259. /**
  47260. * Returns a normalized vector (Vector3) orthogonal to the ground
  47261. * at the ground coordinates (x, z) expressed in the World system.
  47262. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  47263. */
  47264. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  47265. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  47266. this.getNormalAtCoordinatesToRef(x, z, normal);
  47267. return normal;
  47268. };
  47269. /**
  47270. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  47271. * at the ground coordinates (x, z) expressed in the World system.
  47272. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  47273. * Returns the GroundMesh.
  47274. */
  47275. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  47276. var world = this.getWorldMatrix();
  47277. var tmpMat = BABYLON.Tmp.Matrix[5];
  47278. world.invertToRef(tmpMat);
  47279. var tmpVect = BABYLON.Tmp.Vector3[8];
  47280. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  47281. x = tmpVect.x;
  47282. z = tmpVect.z;
  47283. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  47284. return this;
  47285. }
  47286. if (!this._heightQuads || this._heightQuads.length == 0) {
  47287. this._initHeightQuads();
  47288. this._computeHeightQuads();
  47289. }
  47290. var facet = this._getFacetAt(x, z);
  47291. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  47292. return this;
  47293. };
  47294. /**
  47295. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  47296. * if the ground has been updated.
  47297. * This can be used in the render loop.
  47298. * Returns the GroundMesh.
  47299. */
  47300. GroundMesh.prototype.updateCoordinateHeights = function () {
  47301. if (!this._heightQuads || this._heightQuads.length == 0) {
  47302. this._initHeightQuads();
  47303. }
  47304. this._computeHeightQuads();
  47305. return this;
  47306. };
  47307. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  47308. GroundMesh.prototype._getFacetAt = function (x, z) {
  47309. // retrieve col and row from x, z coordinates in the ground local system
  47310. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  47311. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  47312. var quad = this._heightQuads[row * this._subdivisionsX + col];
  47313. var facet;
  47314. if (z < quad.slope.x * x + quad.slope.y) {
  47315. facet = quad.facet1;
  47316. }
  47317. else {
  47318. facet = quad.facet2;
  47319. }
  47320. return facet;
  47321. };
  47322. // Creates and populates the heightMap array with "facet" elements :
  47323. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  47324. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  47325. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  47326. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  47327. // Returns the GroundMesh.
  47328. GroundMesh.prototype._initHeightQuads = function () {
  47329. var subdivisionsX = this._subdivisionsX;
  47330. var subdivisionsY = this._subdivisionsY;
  47331. this._heightQuads = new Array();
  47332. for (var row = 0; row < subdivisionsY; row++) {
  47333. for (var col = 0; col < subdivisionsX; col++) {
  47334. 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) };
  47335. this._heightQuads[row * subdivisionsX + col] = quad;
  47336. }
  47337. }
  47338. return this;
  47339. };
  47340. // Compute each quad element values and update the the heightMap array :
  47341. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  47342. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  47343. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  47344. // Returns the GroundMesh.
  47345. GroundMesh.prototype._computeHeightQuads = function () {
  47346. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47347. if (!positions) {
  47348. return this;
  47349. }
  47350. var v1 = BABYLON.Tmp.Vector3[3];
  47351. var v2 = BABYLON.Tmp.Vector3[2];
  47352. var v3 = BABYLON.Tmp.Vector3[1];
  47353. var v4 = BABYLON.Tmp.Vector3[0];
  47354. var v1v2 = BABYLON.Tmp.Vector3[4];
  47355. var v1v3 = BABYLON.Tmp.Vector3[5];
  47356. var v1v4 = BABYLON.Tmp.Vector3[6];
  47357. var norm1 = BABYLON.Tmp.Vector3[7];
  47358. var norm2 = BABYLON.Tmp.Vector3[8];
  47359. var i = 0;
  47360. var j = 0;
  47361. var k = 0;
  47362. var cd = 0; // 2D slope coefficient : z = cd * x + h
  47363. var h = 0;
  47364. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  47365. var d2 = 0;
  47366. var subdivisionsX = this._subdivisionsX;
  47367. var subdivisionsY = this._subdivisionsY;
  47368. for (var row = 0; row < subdivisionsY; row++) {
  47369. for (var col = 0; col < subdivisionsX; col++) {
  47370. i = col * 3;
  47371. j = row * (subdivisionsX + 1) * 3;
  47372. k = (row + 1) * (subdivisionsX + 1) * 3;
  47373. v1.x = positions[j + i];
  47374. v1.y = positions[j + i + 1];
  47375. v1.z = positions[j + i + 2];
  47376. v2.x = positions[j + i + 3];
  47377. v2.y = positions[j + i + 4];
  47378. v2.z = positions[j + i + 5];
  47379. v3.x = positions[k + i];
  47380. v3.y = positions[k + i + 1];
  47381. v3.z = positions[k + i + 2];
  47382. v4.x = positions[k + i + 3];
  47383. v4.y = positions[k + i + 4];
  47384. v4.z = positions[k + i + 5];
  47385. // 2D slope V1V4
  47386. cd = (v4.z - v1.z) / (v4.x - v1.x);
  47387. h = v1.z - cd * v1.x; // v1 belongs to the slope
  47388. // facet equations :
  47389. // we compute each facet normal vector
  47390. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  47391. // we compute the value d by applying the equation to v1 which belongs to the plane
  47392. // then we store the facet equation in a Vector4
  47393. v2.subtractToRef(v1, v1v2);
  47394. v3.subtractToRef(v1, v1v3);
  47395. v4.subtractToRef(v1, v1v4);
  47396. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  47397. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  47398. norm1.normalize();
  47399. norm2.normalize();
  47400. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  47401. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  47402. var quad = this._heightQuads[row * subdivisionsX + col];
  47403. quad.slope.copyFromFloats(cd, h);
  47404. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  47405. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  47406. }
  47407. }
  47408. return this;
  47409. };
  47410. GroundMesh.prototype.serialize = function (serializationObject) {
  47411. _super.prototype.serialize.call(this, serializationObject);
  47412. serializationObject.subdivisionsX = this._subdivisionsX;
  47413. serializationObject.subdivisionsY = this._subdivisionsY;
  47414. serializationObject.minX = this._minX;
  47415. serializationObject.maxX = this._maxX;
  47416. serializationObject.minZ = this._minZ;
  47417. serializationObject.maxZ = this._maxZ;
  47418. serializationObject.width = this._width;
  47419. serializationObject.height = this._height;
  47420. };
  47421. GroundMesh.Parse = function (parsedMesh, scene) {
  47422. var result = new GroundMesh(parsedMesh.name, scene);
  47423. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  47424. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  47425. result._minX = parsedMesh.minX;
  47426. result._maxX = parsedMesh.maxX;
  47427. result._minZ = parsedMesh.minZ;
  47428. result._maxZ = parsedMesh.maxZ;
  47429. result._width = parsedMesh.width;
  47430. result._height = parsedMesh.height;
  47431. return result;
  47432. };
  47433. return GroundMesh;
  47434. }(BABYLON.Mesh));
  47435. BABYLON.GroundMesh = GroundMesh;
  47436. })(BABYLON || (BABYLON = {}));
  47437. //# sourceMappingURL=babylon.groundMesh.js.map
  47438. var BABYLON;
  47439. (function (BABYLON) {
  47440. /**
  47441. * Creates an instance based on a source mesh.
  47442. */
  47443. var InstancedMesh = /** @class */ (function (_super) {
  47444. __extends(InstancedMesh, _super);
  47445. function InstancedMesh(name, source) {
  47446. var _this = _super.call(this, name, source.getScene()) || this;
  47447. source.instances.push(_this);
  47448. _this._sourceMesh = source;
  47449. _this.position.copyFrom(source.position);
  47450. _this.rotation.copyFrom(source.rotation);
  47451. _this.scaling.copyFrom(source.scaling);
  47452. if (source.rotationQuaternion) {
  47453. _this.rotationQuaternion = source.rotationQuaternion.clone();
  47454. }
  47455. _this.infiniteDistance = source.infiniteDistance;
  47456. _this.setPivotMatrix(source.getPivotMatrix());
  47457. _this.refreshBoundingInfo();
  47458. _this._syncSubMeshes();
  47459. return _this;
  47460. }
  47461. /**
  47462. * Returns the string "InstancedMesh".
  47463. */
  47464. InstancedMesh.prototype.getClassName = function () {
  47465. return "InstancedMesh";
  47466. };
  47467. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  47468. // Methods
  47469. get: function () {
  47470. return this._sourceMesh.receiveShadows;
  47471. },
  47472. enumerable: true,
  47473. configurable: true
  47474. });
  47475. Object.defineProperty(InstancedMesh.prototype, "material", {
  47476. get: function () {
  47477. return this._sourceMesh.material;
  47478. },
  47479. enumerable: true,
  47480. configurable: true
  47481. });
  47482. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  47483. get: function () {
  47484. return this._sourceMesh.visibility;
  47485. },
  47486. enumerable: true,
  47487. configurable: true
  47488. });
  47489. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  47490. get: function () {
  47491. return this._sourceMesh.skeleton;
  47492. },
  47493. enumerable: true,
  47494. configurable: true
  47495. });
  47496. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  47497. get: function () {
  47498. return this._sourceMesh.renderingGroupId;
  47499. },
  47500. enumerable: true,
  47501. configurable: true
  47502. });
  47503. /**
  47504. * Returns the total number of vertices (integer).
  47505. */
  47506. InstancedMesh.prototype.getTotalVertices = function () {
  47507. return this._sourceMesh.getTotalVertices();
  47508. };
  47509. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  47510. get: function () {
  47511. return this._sourceMesh;
  47512. },
  47513. enumerable: true,
  47514. configurable: true
  47515. });
  47516. /**
  47517. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  47518. */
  47519. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  47520. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  47521. };
  47522. /**
  47523. * Sets the vertex data of the mesh geometry for the requested `kind`.
  47524. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  47525. * The `data` are either a numeric array either a Float32Array.
  47526. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  47527. * 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).
  47528. * Note that a new underlying VertexBuffer object is created each call.
  47529. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  47530. *
  47531. * Possible `kind` values :
  47532. * - BABYLON.VertexBuffer.PositionKind
  47533. * - BABYLON.VertexBuffer.UVKind
  47534. * - BABYLON.VertexBuffer.UV2Kind
  47535. * - BABYLON.VertexBuffer.UV3Kind
  47536. * - BABYLON.VertexBuffer.UV4Kind
  47537. * - BABYLON.VertexBuffer.UV5Kind
  47538. * - BABYLON.VertexBuffer.UV6Kind
  47539. * - BABYLON.VertexBuffer.ColorKind
  47540. * - BABYLON.VertexBuffer.MatricesIndicesKind
  47541. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  47542. * - BABYLON.VertexBuffer.MatricesWeightsKind
  47543. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  47544. *
  47545. * Returns the Mesh.
  47546. */
  47547. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  47548. if (this.sourceMesh) {
  47549. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  47550. }
  47551. return this.sourceMesh;
  47552. };
  47553. /**
  47554. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  47555. * If the mesh has no geometry, it is simply returned as it is.
  47556. * The `data` are either a numeric array either a Float32Array.
  47557. * No new underlying VertexBuffer object is created.
  47558. * 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.
  47559. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  47560. *
  47561. * Possible `kind` values :
  47562. * - BABYLON.VertexBuffer.PositionKind
  47563. * - BABYLON.VertexBuffer.UVKind
  47564. * - BABYLON.VertexBuffer.UV2Kind
  47565. * - BABYLON.VertexBuffer.UV3Kind
  47566. * - BABYLON.VertexBuffer.UV4Kind
  47567. * - BABYLON.VertexBuffer.UV5Kind
  47568. * - BABYLON.VertexBuffer.UV6Kind
  47569. * - BABYLON.VertexBuffer.ColorKind
  47570. * - BABYLON.VertexBuffer.MatricesIndicesKind
  47571. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  47572. * - BABYLON.VertexBuffer.MatricesWeightsKind
  47573. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  47574. *
  47575. * Returns the Mesh.
  47576. */
  47577. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  47578. if (this.sourceMesh) {
  47579. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  47580. }
  47581. return this.sourceMesh;
  47582. };
  47583. /**
  47584. * Sets the mesh indices.
  47585. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  47586. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  47587. * This method creates a new index buffer each call.
  47588. * Returns the Mesh.
  47589. */
  47590. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  47591. if (totalVertices === void 0) { totalVertices = null; }
  47592. if (this.sourceMesh) {
  47593. this.sourceMesh.setIndices(indices, totalVertices);
  47594. }
  47595. return this.sourceMesh;
  47596. };
  47597. /**
  47598. * Boolean : True if the mesh owns the requested kind of data.
  47599. */
  47600. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  47601. return this._sourceMesh.isVerticesDataPresent(kind);
  47602. };
  47603. /**
  47604. * Returns an array of indices (IndicesArray).
  47605. */
  47606. InstancedMesh.prototype.getIndices = function () {
  47607. return this._sourceMesh.getIndices();
  47608. };
  47609. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  47610. get: function () {
  47611. return this._sourceMesh._positions;
  47612. },
  47613. enumerable: true,
  47614. configurable: true
  47615. });
  47616. /**
  47617. * Sets a new updated BoundingInfo to the mesh.
  47618. * Returns the mesh.
  47619. */
  47620. InstancedMesh.prototype.refreshBoundingInfo = function () {
  47621. var meshBB = this._sourceMesh.getBoundingInfo();
  47622. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  47623. this._updateBoundingInfo();
  47624. return this;
  47625. };
  47626. InstancedMesh.prototype._preActivate = function () {
  47627. if (this._currentLOD) {
  47628. this._currentLOD._preActivate();
  47629. }
  47630. return this;
  47631. };
  47632. InstancedMesh.prototype._activate = function (renderId) {
  47633. if (this._currentLOD) {
  47634. this._currentLOD._registerInstanceForRenderId(this, renderId);
  47635. }
  47636. return this;
  47637. };
  47638. /**
  47639. * Returns the current associated LOD AbstractMesh.
  47640. */
  47641. InstancedMesh.prototype.getLOD = function (camera) {
  47642. if (!camera) {
  47643. return this;
  47644. }
  47645. var boundingInfo = this.getBoundingInfo();
  47646. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  47647. if (this._currentLOD === this.sourceMesh) {
  47648. return this;
  47649. }
  47650. return this._currentLOD;
  47651. };
  47652. InstancedMesh.prototype._syncSubMeshes = function () {
  47653. this.releaseSubMeshes();
  47654. if (this._sourceMesh.subMeshes) {
  47655. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  47656. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  47657. }
  47658. }
  47659. return this;
  47660. };
  47661. InstancedMesh.prototype._generatePointsArray = function () {
  47662. return this._sourceMesh._generatePointsArray();
  47663. };
  47664. /**
  47665. * Creates a new InstancedMesh from the current mesh.
  47666. * - name (string) : the cloned mesh name
  47667. * - newParent (optional Node) : the optional Node to parent the clone to.
  47668. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  47669. *
  47670. * Returns the clone.
  47671. */
  47672. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  47673. var result = this._sourceMesh.createInstance(name);
  47674. // Deep copy
  47675. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  47676. // Bounding info
  47677. this.refreshBoundingInfo();
  47678. // Parent
  47679. if (newParent) {
  47680. result.parent = newParent;
  47681. }
  47682. if (!doNotCloneChildren) {
  47683. // Children
  47684. for (var index = 0; index < this.getScene().meshes.length; index++) {
  47685. var mesh = this.getScene().meshes[index];
  47686. if (mesh.parent === this) {
  47687. mesh.clone(mesh.name, result);
  47688. }
  47689. }
  47690. }
  47691. result.computeWorldMatrix(true);
  47692. return result;
  47693. };
  47694. /**
  47695. * Disposes the InstancedMesh.
  47696. * Returns nothing.
  47697. */
  47698. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  47699. // Remove from mesh
  47700. var index = this._sourceMesh.instances.indexOf(this);
  47701. this._sourceMesh.instances.splice(index, 1);
  47702. _super.prototype.dispose.call(this, doNotRecurse);
  47703. };
  47704. return InstancedMesh;
  47705. }(BABYLON.AbstractMesh));
  47706. BABYLON.InstancedMesh = InstancedMesh;
  47707. })(BABYLON || (BABYLON = {}));
  47708. //# sourceMappingURL=babylon.instancedMesh.js.map
  47709. var BABYLON;
  47710. (function (BABYLON) {
  47711. var LinesMesh = /** @class */ (function (_super) {
  47712. __extends(LinesMesh, _super);
  47713. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  47714. if (scene === void 0) { scene = null; }
  47715. if (parent === void 0) { parent = null; }
  47716. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  47717. _this.useVertexColor = useVertexColor;
  47718. _this.useVertexAlpha = useVertexAlpha;
  47719. _this.color = new BABYLON.Color3(1, 1, 1);
  47720. _this.alpha = 1;
  47721. if (source) {
  47722. _this.color = source.color.clone();
  47723. _this.alpha = source.alpha;
  47724. _this.useVertexColor = source.useVertexColor;
  47725. _this.useVertexAlpha = source.useVertexAlpha;
  47726. }
  47727. _this._intersectionThreshold = 0.1;
  47728. var defines = [];
  47729. var options = {
  47730. attributes: [BABYLON.VertexBuffer.PositionKind],
  47731. uniforms: ["world", "viewProjection"],
  47732. needAlphaBlending: true,
  47733. defines: defines
  47734. };
  47735. if (useVertexAlpha === false) {
  47736. options.needAlphaBlending = false;
  47737. }
  47738. if (!useVertexColor) {
  47739. options.uniforms.push("color");
  47740. }
  47741. else {
  47742. options.defines.push("#define VERTEXCOLOR");
  47743. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  47744. }
  47745. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  47746. return _this;
  47747. }
  47748. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  47749. /**
  47750. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  47751. * This margin is expressed in world space coordinates, so its value may vary.
  47752. * Default value is 0.1
  47753. * @returns the intersection Threshold value.
  47754. */
  47755. get: function () {
  47756. return this._intersectionThreshold;
  47757. },
  47758. /**
  47759. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  47760. * This margin is expressed in world space coordinates, so its value may vary.
  47761. * @param value the new threshold to apply
  47762. */
  47763. set: function (value) {
  47764. if (this._intersectionThreshold === value) {
  47765. return;
  47766. }
  47767. this._intersectionThreshold = value;
  47768. if (this.geometry) {
  47769. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  47770. }
  47771. },
  47772. enumerable: true,
  47773. configurable: true
  47774. });
  47775. /**
  47776. * Returns the string "LineMesh"
  47777. */
  47778. LinesMesh.prototype.getClassName = function () {
  47779. return "LinesMesh";
  47780. };
  47781. Object.defineProperty(LinesMesh.prototype, "material", {
  47782. get: function () {
  47783. return this._colorShader;
  47784. },
  47785. set: function (value) {
  47786. // Do nothing
  47787. },
  47788. enumerable: true,
  47789. configurable: true
  47790. });
  47791. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  47792. get: function () {
  47793. return false;
  47794. },
  47795. enumerable: true,
  47796. configurable: true
  47797. });
  47798. LinesMesh.prototype.createInstance = function (name) {
  47799. throw new Error("LinesMeshes do not support createInstance.");
  47800. };
  47801. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  47802. if (!this._geometry) {
  47803. return this;
  47804. }
  47805. // VBOs
  47806. this._geometry._bind(this._colorShader.getEffect());
  47807. // Color
  47808. if (!this.useVertexColor) {
  47809. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  47810. }
  47811. return this;
  47812. };
  47813. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  47814. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  47815. return this;
  47816. }
  47817. var engine = this.getScene().getEngine();
  47818. // Draw order
  47819. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  47820. return this;
  47821. };
  47822. LinesMesh.prototype.dispose = function (doNotRecurse) {
  47823. this._colorShader.dispose();
  47824. _super.prototype.dispose.call(this, doNotRecurse);
  47825. };
  47826. /**
  47827. * Returns a new LineMesh object cloned from the current one.
  47828. */
  47829. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  47830. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  47831. };
  47832. return LinesMesh;
  47833. }(BABYLON.Mesh));
  47834. BABYLON.LinesMesh = LinesMesh;
  47835. })(BABYLON || (BABYLON = {}));
  47836. //# sourceMappingURL=babylon.linesMesh.js.map
  47837. var BABYLON;
  47838. (function (BABYLON) {
  47839. var ShaderMaterial = /** @class */ (function (_super) {
  47840. __extends(ShaderMaterial, _super);
  47841. function ShaderMaterial(name, scene, shaderPath, options) {
  47842. var _this = _super.call(this, name, scene) || this;
  47843. _this._textures = {};
  47844. _this._textureArrays = {};
  47845. _this._floats = {};
  47846. _this._ints = {};
  47847. _this._floatsArrays = {};
  47848. _this._colors3 = {};
  47849. _this._colors3Arrays = {};
  47850. _this._colors4 = {};
  47851. _this._vectors2 = {};
  47852. _this._vectors3 = {};
  47853. _this._vectors4 = {};
  47854. _this._matrices = {};
  47855. _this._matrices3x3 = {};
  47856. _this._matrices2x2 = {};
  47857. _this._vectors2Arrays = {};
  47858. _this._vectors3Arrays = {};
  47859. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  47860. _this._shaderPath = shaderPath;
  47861. options.needAlphaBlending = options.needAlphaBlending || false;
  47862. options.needAlphaTesting = options.needAlphaTesting || false;
  47863. options.attributes = options.attributes || ["position", "normal", "uv"];
  47864. options.uniforms = options.uniforms || ["worldViewProjection"];
  47865. options.uniformBuffers = options.uniformBuffers || [];
  47866. options.samplers = options.samplers || [];
  47867. options.defines = options.defines || [];
  47868. _this._options = options;
  47869. return _this;
  47870. }
  47871. ShaderMaterial.prototype.getClassName = function () {
  47872. return "ShaderMaterial";
  47873. };
  47874. ShaderMaterial.prototype.needAlphaBlending = function () {
  47875. return this._options.needAlphaBlending;
  47876. };
  47877. ShaderMaterial.prototype.needAlphaTesting = function () {
  47878. return this._options.needAlphaTesting;
  47879. };
  47880. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  47881. if (this._options.uniforms.indexOf(uniformName) === -1) {
  47882. this._options.uniforms.push(uniformName);
  47883. }
  47884. };
  47885. ShaderMaterial.prototype.setTexture = function (name, texture) {
  47886. if (this._options.samplers.indexOf(name) === -1) {
  47887. this._options.samplers.push(name);
  47888. }
  47889. this._textures[name] = texture;
  47890. return this;
  47891. };
  47892. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  47893. if (this._options.samplers.indexOf(name) === -1) {
  47894. this._options.samplers.push(name);
  47895. }
  47896. this._checkUniform(name);
  47897. this._textureArrays[name] = textures;
  47898. return this;
  47899. };
  47900. ShaderMaterial.prototype.setFloat = function (name, value) {
  47901. this._checkUniform(name);
  47902. this._floats[name] = value;
  47903. return this;
  47904. };
  47905. ShaderMaterial.prototype.setInt = function (name, value) {
  47906. this._checkUniform(name);
  47907. this._ints[name] = value;
  47908. return this;
  47909. };
  47910. ShaderMaterial.prototype.setFloats = function (name, value) {
  47911. this._checkUniform(name);
  47912. this._floatsArrays[name] = value;
  47913. return this;
  47914. };
  47915. ShaderMaterial.prototype.setColor3 = function (name, value) {
  47916. this._checkUniform(name);
  47917. this._colors3[name] = value;
  47918. return this;
  47919. };
  47920. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  47921. this._checkUniform(name);
  47922. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  47923. color.toArray(arr, arr.length);
  47924. return arr;
  47925. }, []);
  47926. return this;
  47927. };
  47928. ShaderMaterial.prototype.setColor4 = function (name, value) {
  47929. this._checkUniform(name);
  47930. this._colors4[name] = value;
  47931. return this;
  47932. };
  47933. ShaderMaterial.prototype.setVector2 = function (name, value) {
  47934. this._checkUniform(name);
  47935. this._vectors2[name] = value;
  47936. return this;
  47937. };
  47938. ShaderMaterial.prototype.setVector3 = function (name, value) {
  47939. this._checkUniform(name);
  47940. this._vectors3[name] = value;
  47941. return this;
  47942. };
  47943. ShaderMaterial.prototype.setVector4 = function (name, value) {
  47944. this._checkUniform(name);
  47945. this._vectors4[name] = value;
  47946. return this;
  47947. };
  47948. ShaderMaterial.prototype.setMatrix = function (name, value) {
  47949. this._checkUniform(name);
  47950. this._matrices[name] = value;
  47951. return this;
  47952. };
  47953. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  47954. this._checkUniform(name);
  47955. this._matrices3x3[name] = value;
  47956. return this;
  47957. };
  47958. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  47959. this._checkUniform(name);
  47960. this._matrices2x2[name] = value;
  47961. return this;
  47962. };
  47963. ShaderMaterial.prototype.setArray2 = function (name, value) {
  47964. this._checkUniform(name);
  47965. this._vectors2Arrays[name] = value;
  47966. return this;
  47967. };
  47968. ShaderMaterial.prototype.setArray3 = function (name, value) {
  47969. this._checkUniform(name);
  47970. this._vectors3Arrays[name] = value;
  47971. return this;
  47972. };
  47973. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  47974. if (!mesh) {
  47975. return true;
  47976. }
  47977. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  47978. return false;
  47979. }
  47980. return false;
  47981. };
  47982. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  47983. var scene = this.getScene();
  47984. var engine = scene.getEngine();
  47985. if (!this.checkReadyOnEveryCall) {
  47986. if (this._renderId === scene.getRenderId()) {
  47987. if (this._checkCache(scene, mesh, useInstances)) {
  47988. return true;
  47989. }
  47990. }
  47991. }
  47992. // Instances
  47993. var defines = [];
  47994. var attribs = [];
  47995. var fallbacks = new BABYLON.EffectFallbacks();
  47996. if (useInstances) {
  47997. defines.push("#define INSTANCES");
  47998. }
  47999. for (var index = 0; index < this._options.defines.length; index++) {
  48000. defines.push(this._options.defines[index]);
  48001. }
  48002. for (var index = 0; index < this._options.attributes.length; index++) {
  48003. attribs.push(this._options.attributes[index]);
  48004. }
  48005. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  48006. attribs.push(BABYLON.VertexBuffer.ColorKind);
  48007. defines.push("#define VERTEXCOLOR");
  48008. }
  48009. // Bones
  48010. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  48011. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  48012. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  48013. if (mesh.numBoneInfluencers > 4) {
  48014. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  48015. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  48016. }
  48017. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  48018. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  48019. fallbacks.addCPUSkinningFallback(0, mesh);
  48020. if (this._options.uniforms.indexOf("mBones") === -1) {
  48021. this._options.uniforms.push("mBones");
  48022. }
  48023. }
  48024. else {
  48025. defines.push("#define NUM_BONE_INFLUENCERS 0");
  48026. }
  48027. // Textures
  48028. for (var name in this._textures) {
  48029. if (!this._textures[name].isReady()) {
  48030. return false;
  48031. }
  48032. }
  48033. // Alpha test
  48034. if (engine.getAlphaTesting()) {
  48035. defines.push("#define ALPHATEST");
  48036. }
  48037. var previousEffect = this._effect;
  48038. var join = defines.join("\n");
  48039. this._effect = engine.createEffect(this._shaderPath, {
  48040. attributes: attribs,
  48041. uniformsNames: this._options.uniforms,
  48042. uniformBuffersNames: this._options.uniformBuffers,
  48043. samplers: this._options.samplers,
  48044. defines: join,
  48045. fallbacks: fallbacks,
  48046. onCompiled: this.onCompiled,
  48047. onError: this.onError
  48048. }, engine);
  48049. if (!this._effect.isReady()) {
  48050. return false;
  48051. }
  48052. if (previousEffect !== this._effect) {
  48053. scene.resetCachedMaterial();
  48054. }
  48055. this._renderId = scene.getRenderId();
  48056. return true;
  48057. };
  48058. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  48059. var scene = this.getScene();
  48060. if (!this._effect) {
  48061. return;
  48062. }
  48063. if (this._options.uniforms.indexOf("world") !== -1) {
  48064. this._effect.setMatrix("world", world);
  48065. }
  48066. if (this._options.uniforms.indexOf("worldView") !== -1) {
  48067. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  48068. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  48069. }
  48070. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  48071. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  48072. }
  48073. };
  48074. ShaderMaterial.prototype.bind = function (world, mesh) {
  48075. // Std values
  48076. this.bindOnlyWorldMatrix(world);
  48077. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  48078. if (this._options.uniforms.indexOf("view") !== -1) {
  48079. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  48080. }
  48081. if (this._options.uniforms.indexOf("projection") !== -1) {
  48082. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  48083. }
  48084. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  48085. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  48086. }
  48087. // Bones
  48088. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  48089. var name;
  48090. // Texture
  48091. for (name in this._textures) {
  48092. this._effect.setTexture(name, this._textures[name]);
  48093. }
  48094. // Texture arrays
  48095. for (name in this._textureArrays) {
  48096. this._effect.setTextureArray(name, this._textureArrays[name]);
  48097. }
  48098. // Int
  48099. for (name in this._ints) {
  48100. this._effect.setInt(name, this._ints[name]);
  48101. }
  48102. // Float
  48103. for (name in this._floats) {
  48104. this._effect.setFloat(name, this._floats[name]);
  48105. }
  48106. // Floats
  48107. for (name in this._floatsArrays) {
  48108. this._effect.setArray(name, this._floatsArrays[name]);
  48109. }
  48110. // Color3
  48111. for (name in this._colors3) {
  48112. this._effect.setColor3(name, this._colors3[name]);
  48113. }
  48114. for (name in this._colors3Arrays) {
  48115. this._effect.setArray3(name, this._colors3Arrays[name]);
  48116. }
  48117. // Color4
  48118. for (name in this._colors4) {
  48119. var color = this._colors4[name];
  48120. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  48121. }
  48122. // Vector2
  48123. for (name in this._vectors2) {
  48124. this._effect.setVector2(name, this._vectors2[name]);
  48125. }
  48126. // Vector3
  48127. for (name in this._vectors3) {
  48128. this._effect.setVector3(name, this._vectors3[name]);
  48129. }
  48130. // Vector4
  48131. for (name in this._vectors4) {
  48132. this._effect.setVector4(name, this._vectors4[name]);
  48133. }
  48134. // Matrix
  48135. for (name in this._matrices) {
  48136. this._effect.setMatrix(name, this._matrices[name]);
  48137. }
  48138. // Matrix 3x3
  48139. for (name in this._matrices3x3) {
  48140. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  48141. }
  48142. // Matrix 2x2
  48143. for (name in this._matrices2x2) {
  48144. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  48145. }
  48146. // Vector2Array
  48147. for (name in this._vectors2Arrays) {
  48148. this._effect.setArray2(name, this._vectors2Arrays[name]);
  48149. }
  48150. // Vector3Array
  48151. for (name in this._vectors3Arrays) {
  48152. this._effect.setArray3(name, this._vectors3Arrays[name]);
  48153. }
  48154. }
  48155. this._afterBind(mesh);
  48156. };
  48157. ShaderMaterial.prototype.getActiveTextures = function () {
  48158. var activeTextures = _super.prototype.getActiveTextures.call(this);
  48159. for (var name in this._textures) {
  48160. activeTextures.push(this._textures[name]);
  48161. }
  48162. for (var name in this._textureArrays) {
  48163. var array = this._textureArrays[name];
  48164. for (var index = 0; index < array.length; index++) {
  48165. activeTextures.push(array[index]);
  48166. }
  48167. }
  48168. return activeTextures;
  48169. };
  48170. ShaderMaterial.prototype.hasTexture = function (texture) {
  48171. if (_super.prototype.hasTexture.call(this, texture)) {
  48172. return true;
  48173. }
  48174. for (var name in this._textures) {
  48175. if (this._textures[name] === texture) {
  48176. return true;
  48177. }
  48178. }
  48179. for (var name in this._textureArrays) {
  48180. var array = this._textureArrays[name];
  48181. for (var index = 0; index < array.length; index++) {
  48182. if (array[index] === texture) {
  48183. return true;
  48184. }
  48185. }
  48186. }
  48187. return false;
  48188. };
  48189. ShaderMaterial.prototype.clone = function (name) {
  48190. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  48191. return newShaderMaterial;
  48192. };
  48193. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  48194. if (forceDisposeTextures) {
  48195. var name;
  48196. for (name in this._textures) {
  48197. this._textures[name].dispose();
  48198. }
  48199. for (name in this._textureArrays) {
  48200. var array = this._textureArrays[name];
  48201. for (var index = 0; index < array.length; index++) {
  48202. array[index].dispose();
  48203. }
  48204. }
  48205. }
  48206. this._textures = {};
  48207. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  48208. };
  48209. ShaderMaterial.prototype.serialize = function () {
  48210. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  48211. serializationObject.customType = "BABYLON.ShaderMaterial";
  48212. serializationObject.options = this._options;
  48213. serializationObject.shaderPath = this._shaderPath;
  48214. var name;
  48215. // Texture
  48216. serializationObject.textures = {};
  48217. for (name in this._textures) {
  48218. serializationObject.textures[name] = this._textures[name].serialize();
  48219. }
  48220. // Texture arrays
  48221. serializationObject.textureArrays = {};
  48222. for (name in this._textureArrays) {
  48223. serializationObject.textureArrays[name] = [];
  48224. var array = this._textureArrays[name];
  48225. for (var index = 0; index < array.length; index++) {
  48226. serializationObject.textureArrays[name].push(array[index].serialize());
  48227. }
  48228. }
  48229. // Float
  48230. serializationObject.floats = {};
  48231. for (name in this._floats) {
  48232. serializationObject.floats[name] = this._floats[name];
  48233. }
  48234. // Float s
  48235. serializationObject.FloatArrays = {};
  48236. for (name in this._floatsArrays) {
  48237. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  48238. }
  48239. // Color3
  48240. serializationObject.colors3 = {};
  48241. for (name in this._colors3) {
  48242. serializationObject.colors3[name] = this._colors3[name].asArray();
  48243. }
  48244. // Color3 array
  48245. serializationObject.colors3Arrays = {};
  48246. for (name in this._colors3Arrays) {
  48247. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  48248. }
  48249. // Color4
  48250. serializationObject.colors4 = {};
  48251. for (name in this._colors4) {
  48252. serializationObject.colors4[name] = this._colors4[name].asArray();
  48253. }
  48254. // Vector2
  48255. serializationObject.vectors2 = {};
  48256. for (name in this._vectors2) {
  48257. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  48258. }
  48259. // Vector3
  48260. serializationObject.vectors3 = {};
  48261. for (name in this._vectors3) {
  48262. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  48263. }
  48264. // Vector4
  48265. serializationObject.vectors4 = {};
  48266. for (name in this._vectors4) {
  48267. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  48268. }
  48269. // Matrix
  48270. serializationObject.matrices = {};
  48271. for (name in this._matrices) {
  48272. serializationObject.matrices[name] = this._matrices[name].asArray();
  48273. }
  48274. // Matrix 3x3
  48275. serializationObject.matrices3x3 = {};
  48276. for (name in this._matrices3x3) {
  48277. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  48278. }
  48279. // Matrix 2x2
  48280. serializationObject.matrices2x2 = {};
  48281. for (name in this._matrices2x2) {
  48282. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  48283. }
  48284. // Vector2Array
  48285. serializationObject.vectors2Arrays = {};
  48286. for (name in this._vectors2Arrays) {
  48287. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  48288. }
  48289. // Vector3Array
  48290. serializationObject.vectors3Arrays = {};
  48291. for (name in this._vectors3Arrays) {
  48292. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  48293. }
  48294. return serializationObject;
  48295. };
  48296. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  48297. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  48298. var name;
  48299. // Texture
  48300. for (name in source.textures) {
  48301. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  48302. }
  48303. // Texture arrays
  48304. for (name in source.textureArrays) {
  48305. var array = source.textureArrays[name];
  48306. var textureArray = new Array();
  48307. for (var index = 0; index < array.length; index++) {
  48308. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  48309. }
  48310. material.setTextureArray(name, textureArray);
  48311. }
  48312. // Float
  48313. for (name in source.floats) {
  48314. material.setFloat(name, source.floats[name]);
  48315. }
  48316. // Float s
  48317. for (name in source.floatsArrays) {
  48318. material.setFloats(name, source.floatsArrays[name]);
  48319. }
  48320. // Color3
  48321. for (name in source.colors3) {
  48322. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  48323. }
  48324. // Color3 arrays
  48325. for (name in source.colors3Arrays) {
  48326. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  48327. if (i % 3 === 0) {
  48328. arr.push([num]);
  48329. }
  48330. else {
  48331. arr[arr.length - 1].push(num);
  48332. }
  48333. return arr;
  48334. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  48335. material.setColor3Array(name, colors);
  48336. }
  48337. // Color4
  48338. for (name in source.colors4) {
  48339. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  48340. }
  48341. // Vector2
  48342. for (name in source.vectors2) {
  48343. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  48344. }
  48345. // Vector3
  48346. for (name in source.vectors3) {
  48347. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  48348. }
  48349. // Vector4
  48350. for (name in source.vectors4) {
  48351. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  48352. }
  48353. // Matrix
  48354. for (name in source.matrices) {
  48355. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  48356. }
  48357. // Matrix 3x3
  48358. for (name in source.matrices3x3) {
  48359. material.setMatrix3x3(name, source.matrices3x3[name]);
  48360. }
  48361. // Matrix 2x2
  48362. for (name in source.matrices2x2) {
  48363. material.setMatrix2x2(name, source.matrices2x2[name]);
  48364. }
  48365. // Vector2Array
  48366. for (name in source.vectors2Arrays) {
  48367. material.setArray2(name, source.vectors2Arrays[name]);
  48368. }
  48369. // Vector3Array
  48370. for (name in source.vectors3Arrays) {
  48371. material.setArray3(name, source.vectors3Arrays[name]);
  48372. }
  48373. return material;
  48374. };
  48375. return ShaderMaterial;
  48376. }(BABYLON.Material));
  48377. BABYLON.ShaderMaterial = ShaderMaterial;
  48378. })(BABYLON || (BABYLON = {}));
  48379. //# sourceMappingURL=babylon.shaderMaterial.js.map
  48380. var BABYLON;
  48381. (function (BABYLON) {
  48382. var MeshBuilder = /** @class */ (function () {
  48383. function MeshBuilder() {
  48384. }
  48385. MeshBuilder.updateSideOrientation = function (orientation) {
  48386. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  48387. return BABYLON.Mesh.DOUBLESIDE;
  48388. }
  48389. if (orientation === undefined || orientation === null) {
  48390. return BABYLON.Mesh.FRONTSIDE;
  48391. }
  48392. return orientation;
  48393. };
  48394. /**
  48395. * Creates a box mesh.
  48396. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  48397. * The parameter `size` sets the size (float) of each box side (default 1).
  48398. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  48399. * 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).
  48400. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  48401. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48402. * 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).
  48403. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48404. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48405. */
  48406. MeshBuilder.CreateBox = function (name, options, scene) {
  48407. if (scene === void 0) { scene = null; }
  48408. var box = new BABYLON.Mesh(name, scene);
  48409. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48410. box._originalBuilderSideOrientation = options.sideOrientation;
  48411. var vertexData = BABYLON.VertexData.CreateBox(options);
  48412. vertexData.applyToMesh(box, options.updatable);
  48413. return box;
  48414. };
  48415. /**
  48416. * Creates a sphere mesh.
  48417. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  48418. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  48419. * 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`).
  48420. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  48421. * 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
  48422. * 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).
  48423. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48424. * 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).
  48425. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48426. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48427. */
  48428. MeshBuilder.CreateSphere = function (name, options, scene) {
  48429. var sphere = new BABYLON.Mesh(name, scene);
  48430. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48431. sphere._originalBuilderSideOrientation = options.sideOrientation;
  48432. var vertexData = BABYLON.VertexData.CreateSphere(options);
  48433. vertexData.applyToMesh(sphere, options.updatable);
  48434. return sphere;
  48435. };
  48436. /**
  48437. * Creates a plane polygonal mesh. By default, this is a disc.
  48438. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  48439. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  48440. * 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.
  48441. * 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
  48442. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48443. * 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).
  48444. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48445. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48446. */
  48447. MeshBuilder.CreateDisc = function (name, options, scene) {
  48448. if (scene === void 0) { scene = null; }
  48449. var disc = new BABYLON.Mesh(name, scene);
  48450. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48451. disc._originalBuilderSideOrientation = options.sideOrientation;
  48452. var vertexData = BABYLON.VertexData.CreateDisc(options);
  48453. vertexData.applyToMesh(disc, options.updatable);
  48454. return disc;
  48455. };
  48456. /**
  48457. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  48458. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  48459. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  48460. * 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`).
  48461. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  48462. * 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.
  48463. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48464. * 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).
  48465. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48466. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48467. */
  48468. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  48469. var sphere = new BABYLON.Mesh(name, scene);
  48470. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48471. sphere._originalBuilderSideOrientation = options.sideOrientation;
  48472. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  48473. vertexData.applyToMesh(sphere, options.updatable);
  48474. return sphere;
  48475. };
  48476. ;
  48477. /**
  48478. * Creates a ribbon mesh.
  48479. * 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.
  48480. *
  48481. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  48482. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  48483. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  48484. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  48485. * 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.
  48486. * 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.
  48487. * 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
  48488. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48489. * 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).
  48490. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48491. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  48492. * 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.
  48493. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  48494. * 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
  48495. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  48496. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  48497. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48498. */
  48499. MeshBuilder.CreateRibbon = function (name, options, scene) {
  48500. if (scene === void 0) { scene = null; }
  48501. var pathArray = options.pathArray;
  48502. var closeArray = options.closeArray;
  48503. var closePath = options.closePath;
  48504. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48505. var instance = options.instance;
  48506. var updatable = options.updatable;
  48507. if (instance) {
  48508. // positionFunction : ribbon case
  48509. // only pathArray and sideOrientation parameters are taken into account for positions update
  48510. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  48511. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  48512. var positionFunction = function (positions) {
  48513. var minlg = pathArray[0].length;
  48514. var i = 0;
  48515. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  48516. for (var si = 1; si <= ns; si++) {
  48517. for (var p = 0; p < pathArray.length; p++) {
  48518. var path = pathArray[p];
  48519. var l = path.length;
  48520. minlg = (minlg < l) ? minlg : l;
  48521. var j = 0;
  48522. while (j < minlg) {
  48523. positions[i] = path[j].x;
  48524. positions[i + 1] = path[j].y;
  48525. positions[i + 2] = path[j].z;
  48526. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  48527. BABYLON.Tmp.Vector3[0].x = path[j].x;
  48528. }
  48529. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  48530. BABYLON.Tmp.Vector3[1].x = path[j].x;
  48531. }
  48532. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  48533. BABYLON.Tmp.Vector3[0].y = path[j].y;
  48534. }
  48535. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  48536. BABYLON.Tmp.Vector3[1].y = path[j].y;
  48537. }
  48538. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  48539. BABYLON.Tmp.Vector3[0].z = path[j].z;
  48540. }
  48541. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  48542. BABYLON.Tmp.Vector3[1].z = path[j].z;
  48543. }
  48544. j++;
  48545. i += 3;
  48546. }
  48547. if (instance._closePath) {
  48548. positions[i] = path[0].x;
  48549. positions[i + 1] = path[0].y;
  48550. positions[i + 2] = path[0].z;
  48551. i += 3;
  48552. }
  48553. }
  48554. }
  48555. };
  48556. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48557. positionFunction(positions);
  48558. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  48559. instance._boundingInfo.update(instance._worldMatrix);
  48560. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  48561. if (options.colors) {
  48562. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  48563. for (var c = 0; c < options.colors.length; c++) {
  48564. colors[c * 4] = options.colors[c].r;
  48565. colors[c * 4 + 1] = options.colors[c].g;
  48566. colors[c * 4 + 2] = options.colors[c].b;
  48567. colors[c * 4 + 3] = options.colors[c].a;
  48568. }
  48569. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  48570. }
  48571. if (options.uvs) {
  48572. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  48573. for (var i = 0; i < options.uvs.length; i++) {
  48574. uvs[i * 2] = options.uvs[i].x;
  48575. uvs[i * 2 + 1] = options.uvs[i].y;
  48576. }
  48577. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  48578. }
  48579. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  48580. var indices = instance.getIndices();
  48581. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  48582. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  48583. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  48584. if (instance._closePath) {
  48585. var indexFirst = 0;
  48586. var indexLast = 0;
  48587. for (var p = 0; p < pathArray.length; p++) {
  48588. indexFirst = instance._idx[p] * 3;
  48589. if (p + 1 < pathArray.length) {
  48590. indexLast = (instance._idx[p + 1] - 1) * 3;
  48591. }
  48592. else {
  48593. indexLast = normals.length - 3;
  48594. }
  48595. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  48596. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  48597. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  48598. normals[indexLast] = normals[indexFirst];
  48599. normals[indexLast + 1] = normals[indexFirst + 1];
  48600. normals[indexLast + 2] = normals[indexFirst + 2];
  48601. }
  48602. }
  48603. if (!(instance.areNormalsFrozen)) {
  48604. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  48605. }
  48606. }
  48607. return instance;
  48608. }
  48609. else {
  48610. var ribbon = new BABYLON.Mesh(name, scene);
  48611. ribbon._originalBuilderSideOrientation = sideOrientation;
  48612. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  48613. if (closePath) {
  48614. ribbon._idx = vertexData._idx;
  48615. }
  48616. ribbon._closePath = closePath;
  48617. ribbon._closeArray = closeArray;
  48618. vertexData.applyToMesh(ribbon, updatable);
  48619. return ribbon;
  48620. }
  48621. };
  48622. /**
  48623. * Creates a cylinder or a cone mesh.
  48624. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  48625. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  48626. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  48627. * 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.
  48628. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  48629. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  48630. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  48631. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  48632. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  48633. * 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).
  48634. * 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
  48635. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  48636. * 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
  48637. * 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.
  48638. * If `enclose` is false, a ring surface is one element.
  48639. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  48640. * 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
  48641. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48642. * 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).
  48643. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48644. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48645. */
  48646. MeshBuilder.CreateCylinder = function (name, options, scene) {
  48647. var cylinder = new BABYLON.Mesh(name, scene);
  48648. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48649. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  48650. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  48651. vertexData.applyToMesh(cylinder, options.updatable);
  48652. return cylinder;
  48653. };
  48654. /**
  48655. * Creates a torus mesh.
  48656. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  48657. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  48658. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  48659. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  48660. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48661. * 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).
  48662. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48663. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48664. */
  48665. MeshBuilder.CreateTorus = function (name, options, scene) {
  48666. var torus = new BABYLON.Mesh(name, scene);
  48667. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48668. torus._originalBuilderSideOrientation = options.sideOrientation;
  48669. var vertexData = BABYLON.VertexData.CreateTorus(options);
  48670. vertexData.applyToMesh(torus, options.updatable);
  48671. return torus;
  48672. };
  48673. /**
  48674. * Creates a torus knot mesh.
  48675. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  48676. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  48677. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  48678. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  48679. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  48680. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48681. * 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).
  48682. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48683. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48684. */
  48685. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  48686. var torusKnot = new BABYLON.Mesh(name, scene);
  48687. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48688. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  48689. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  48690. vertexData.applyToMesh(torusKnot, options.updatable);
  48691. return torusKnot;
  48692. };
  48693. /**
  48694. * Creates a line system mesh.
  48695. * A line system is a pool of many lines gathered in a single mesh.
  48696. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  48697. * 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.
  48698. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  48699. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  48700. * 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
  48701. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  48702. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  48703. * 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
  48704. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  48705. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48706. */
  48707. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  48708. var instance = options.instance;
  48709. var lines = options.lines;
  48710. var colors = options.colors;
  48711. if (instance) {
  48712. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48713. var vertexColor;
  48714. var lineColors;
  48715. if (colors) {
  48716. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  48717. }
  48718. var i = 0;
  48719. var c = 0;
  48720. for (var l = 0; l < lines.length; l++) {
  48721. var points = lines[l];
  48722. for (var p = 0; p < points.length; p++) {
  48723. positions[i] = points[p].x;
  48724. positions[i + 1] = points[p].y;
  48725. positions[i + 2] = points[p].z;
  48726. if (colors && vertexColor) {
  48727. lineColors = colors[l];
  48728. vertexColor[c] = lineColors[p].r;
  48729. vertexColor[c + 1] = lineColors[p].g;
  48730. vertexColor[c + 2] = lineColors[p].b;
  48731. vertexColor[c + 3] = lineColors[p].a;
  48732. c += 4;
  48733. }
  48734. i += 3;
  48735. }
  48736. }
  48737. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  48738. if (colors && vertexColor) {
  48739. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  48740. }
  48741. return instance;
  48742. }
  48743. // line system creation
  48744. var useVertexColor = (colors) ? true : false;
  48745. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  48746. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  48747. vertexData.applyToMesh(lineSystem, options.updatable);
  48748. return lineSystem;
  48749. };
  48750. /**
  48751. * Creates a line mesh.
  48752. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  48753. * 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.
  48754. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  48755. * The parameter `points` is an array successive Vector3.
  48756. * 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
  48757. * The optional parameter `colors` is an array of successive Color4, one per line point.
  48758. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  48759. * When updating an instance, remember that only point positions can change, not the number of points.
  48760. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48761. */
  48762. MeshBuilder.CreateLines = function (name, options, scene) {
  48763. if (scene === void 0) { scene = null; }
  48764. var colors = (options.colors) ? [options.colors] : null;
  48765. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  48766. return lines;
  48767. };
  48768. /**
  48769. * Creates a dashed line mesh.
  48770. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  48771. * 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.
  48772. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  48773. * The parameter `points` is an array successive Vector3.
  48774. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  48775. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  48776. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  48777. * 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
  48778. * When updating an instance, remember that only point positions can change, not the number of points.
  48779. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48780. */
  48781. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  48782. if (scene === void 0) { scene = null; }
  48783. var points = options.points;
  48784. var instance = options.instance;
  48785. var gapSize = options.gapSize || 1;
  48786. var dashSize = options.dashSize || 3;
  48787. if (instance) {
  48788. var positionFunction = function (positions) {
  48789. var curvect = BABYLON.Vector3.Zero();
  48790. var nbSeg = positions.length / 6;
  48791. var lg = 0;
  48792. var nb = 0;
  48793. var shft = 0;
  48794. var dashshft = 0;
  48795. var curshft = 0;
  48796. var p = 0;
  48797. var i = 0;
  48798. var j = 0;
  48799. for (i = 0; i < points.length - 1; i++) {
  48800. points[i + 1].subtractToRef(points[i], curvect);
  48801. lg += curvect.length();
  48802. }
  48803. shft = lg / nbSeg;
  48804. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  48805. for (i = 0; i < points.length - 1; i++) {
  48806. points[i + 1].subtractToRef(points[i], curvect);
  48807. nb = Math.floor(curvect.length() / shft);
  48808. curvect.normalize();
  48809. j = 0;
  48810. while (j < nb && p < positions.length) {
  48811. curshft = shft * j;
  48812. positions[p] = points[i].x + curshft * curvect.x;
  48813. positions[p + 1] = points[i].y + curshft * curvect.y;
  48814. positions[p + 2] = points[i].z + curshft * curvect.z;
  48815. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  48816. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  48817. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  48818. p += 6;
  48819. j++;
  48820. }
  48821. }
  48822. while (p < positions.length) {
  48823. positions[p] = points[i].x;
  48824. positions[p + 1] = points[i].y;
  48825. positions[p + 2] = points[i].z;
  48826. p += 3;
  48827. }
  48828. };
  48829. instance.updateMeshPositions(positionFunction, false);
  48830. return instance;
  48831. }
  48832. // dashed lines creation
  48833. var dashedLines = new BABYLON.LinesMesh(name, scene);
  48834. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  48835. vertexData.applyToMesh(dashedLines, options.updatable);
  48836. dashedLines.dashSize = dashSize;
  48837. dashedLines.gapSize = gapSize;
  48838. return dashedLines;
  48839. };
  48840. /**
  48841. * Creates an extruded shape mesh.
  48842. * 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.
  48843. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  48844. *
  48845. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  48846. * 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
  48847. * extruded along the Z axis.
  48848. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  48849. * 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.
  48850. * The parameter `scale` (float, default 1) is the value to scale the shape.
  48851. * 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
  48852. * 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
  48853. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  48854. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48855. * 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).
  48856. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48857. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  48858. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48859. */
  48860. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  48861. if (scene === void 0) { scene = null; }
  48862. var path = options.path;
  48863. var shape = options.shape;
  48864. var scale = options.scale || 1;
  48865. var rotation = options.rotation || 0;
  48866. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  48867. var updatable = options.updatable;
  48868. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48869. var instance = options.instance || null;
  48870. var invertUV = options.invertUV || false;
  48871. 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);
  48872. };
  48873. /**
  48874. * Creates an custom extruded shape mesh.
  48875. * 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.
  48876. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  48877. *
  48878. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  48879. * 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
  48880. * extruded along the Z axis.
  48881. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  48882. * 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
  48883. * and the distance of this point from the begining of the path :
  48884. * ```javascript
  48885. * var rotationFunction = function(i, distance) {
  48886. * // do things
  48887. * return rotationValue; }
  48888. * ```
  48889. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  48890. * 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
  48891. * and the distance of this point from the begining of the path :
  48892. * ```javascript
  48893. * var scaleFunction = function(i, distance) {
  48894. * // do things
  48895. * return scaleValue;}
  48896. * ```
  48897. * It must returns a float value that will be the scale value applied to the shape on each path point.
  48898. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  48899. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  48900. * 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
  48901. * 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
  48902. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  48903. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48904. * 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).
  48905. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48906. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  48907. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48908. */
  48909. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  48910. var path = options.path;
  48911. var shape = options.shape;
  48912. var scaleFunction = options.scaleFunction || (function () { return 1; });
  48913. var rotationFunction = options.rotationFunction || (function () { return 0; });
  48914. var ribbonCloseArray = options.ribbonCloseArray || false;
  48915. var ribbonClosePath = options.ribbonClosePath || false;
  48916. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  48917. var updatable = options.updatable;
  48918. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48919. var instance = options.instance;
  48920. var invertUV = options.invertUV || false;
  48921. 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);
  48922. };
  48923. /**
  48924. * Creates lathe mesh.
  48925. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  48926. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  48927. *
  48928. * 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
  48929. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  48930. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  48931. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  48932. * 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.
  48933. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  48934. * 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
  48935. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48936. * 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).
  48937. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48938. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  48939. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48940. */
  48941. MeshBuilder.CreateLathe = function (name, options, scene) {
  48942. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  48943. var closed = (options.closed === undefined) ? true : options.closed;
  48944. var shape = options.shape;
  48945. var radius = options.radius || 1;
  48946. var tessellation = options.tessellation || 64;
  48947. var updatable = options.updatable;
  48948. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48949. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  48950. var pi2 = Math.PI * 2;
  48951. var paths = new Array();
  48952. var invertUV = options.invertUV || false;
  48953. var i = 0;
  48954. var p = 0;
  48955. var step = pi2 / tessellation * arc;
  48956. var rotated;
  48957. var path = new Array();
  48958. ;
  48959. for (i = 0; i <= tessellation; i++) {
  48960. var path = [];
  48961. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  48962. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  48963. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  48964. }
  48965. for (p = 0; p < shape.length; p++) {
  48966. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  48967. path.push(rotated);
  48968. }
  48969. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  48970. 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));
  48971. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  48972. }
  48973. paths.push(path);
  48974. }
  48975. // lathe ribbon
  48976. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  48977. return lathe;
  48978. };
  48979. /**
  48980. * Creates a plane mesh.
  48981. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  48982. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  48983. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  48984. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  48985. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48986. * 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).
  48987. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48988. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48989. */
  48990. MeshBuilder.CreatePlane = function (name, options, scene) {
  48991. var plane = new BABYLON.Mesh(name, scene);
  48992. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48993. plane._originalBuilderSideOrientation = options.sideOrientation;
  48994. var vertexData = BABYLON.VertexData.CreatePlane(options);
  48995. vertexData.applyToMesh(plane, options.updatable);
  48996. if (options.sourcePlane) {
  48997. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  48998. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  48999. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  49000. plane.rotate(vectorProduct, product);
  49001. }
  49002. return plane;
  49003. };
  49004. /**
  49005. * Creates a ground mesh.
  49006. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  49007. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  49008. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  49009. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49010. */
  49011. MeshBuilder.CreateGround = function (name, options, scene) {
  49012. var ground = new BABYLON.GroundMesh(name, scene);
  49013. ground._setReady(false);
  49014. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  49015. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  49016. ground._width = options.width || 1;
  49017. ground._height = options.height || 1;
  49018. ground._maxX = ground._width / 2;
  49019. ground._maxZ = ground._height / 2;
  49020. ground._minX = -ground._maxX;
  49021. ground._minZ = -ground._maxZ;
  49022. var vertexData = BABYLON.VertexData.CreateGround(options);
  49023. vertexData.applyToMesh(ground, options.updatable);
  49024. ground._setReady(true);
  49025. return ground;
  49026. };
  49027. /**
  49028. * Creates a tiled ground mesh.
  49029. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  49030. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  49031. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  49032. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  49033. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  49034. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  49035. * numbers of subdivisions on the ground width and height of each tile.
  49036. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49037. */
  49038. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  49039. var tiledGround = new BABYLON.Mesh(name, scene);
  49040. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  49041. vertexData.applyToMesh(tiledGround, options.updatable);
  49042. return tiledGround;
  49043. };
  49044. /**
  49045. * Creates a ground mesh from a height map.
  49046. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  49047. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  49048. * The parameter `url` sets the URL of the height map image resource.
  49049. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  49050. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  49051. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  49052. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  49053. * 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.
  49054. * 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).
  49055. * This function is passed the newly built mesh :
  49056. * ```javascript
  49057. * function(mesh) { // do things
  49058. * return; }
  49059. * ```
  49060. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49061. */
  49062. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  49063. var width = options.width || 10.0;
  49064. var height = options.height || 10.0;
  49065. var subdivisions = options.subdivisions || 1 | 0;
  49066. var minHeight = options.minHeight || 0.0;
  49067. var maxHeight = options.maxHeight || 1.0;
  49068. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  49069. var updatable = options.updatable;
  49070. var onReady = options.onReady;
  49071. var ground = new BABYLON.GroundMesh(name, scene);
  49072. ground._subdivisionsX = subdivisions;
  49073. ground._subdivisionsY = subdivisions;
  49074. ground._width = width;
  49075. ground._height = height;
  49076. ground._maxX = ground._width / 2.0;
  49077. ground._maxZ = ground._height / 2.0;
  49078. ground._minX = -ground._maxX;
  49079. ground._minZ = -ground._maxZ;
  49080. ground._setReady(false);
  49081. var onload = function (img) {
  49082. // Getting height map data
  49083. var canvas = document.createElement("canvas");
  49084. var context = canvas.getContext("2d");
  49085. if (!context) {
  49086. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  49087. }
  49088. var bufferWidth = img.width;
  49089. var bufferHeight = img.height;
  49090. canvas.width = bufferWidth;
  49091. canvas.height = bufferHeight;
  49092. context.drawImage(img, 0, 0);
  49093. // Create VertexData from map data
  49094. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  49095. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  49096. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  49097. width: width, height: height,
  49098. subdivisions: subdivisions,
  49099. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  49100. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  49101. });
  49102. vertexData.applyToMesh(ground, updatable);
  49103. ground._setReady(true);
  49104. //execute ready callback, if set
  49105. if (onReady) {
  49106. onReady(ground);
  49107. }
  49108. };
  49109. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  49110. return ground;
  49111. };
  49112. /**
  49113. * Creates a polygon mesh.
  49114. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  49115. * 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.
  49116. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49117. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49118. * 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).
  49119. * Remember you can only change the shape positions, not their number when updating a polygon.
  49120. */
  49121. MeshBuilder.CreatePolygon = function (name, options, scene) {
  49122. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49123. var shape = options.shape;
  49124. var holes = options.holes || [];
  49125. var depth = options.depth || 0;
  49126. var contours = [];
  49127. var hole = [];
  49128. for (var i = 0; i < shape.length; i++) {
  49129. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  49130. }
  49131. var epsilon = 0.00000001;
  49132. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  49133. contours.pop();
  49134. }
  49135. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  49136. for (var hNb = 0; hNb < holes.length; hNb++) {
  49137. hole = [];
  49138. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  49139. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  49140. }
  49141. polygonTriangulation.addHole(hole);
  49142. }
  49143. var polygon = polygonTriangulation.build(options.updatable, depth);
  49144. polygon._originalBuilderSideOrientation = options.sideOrientation;
  49145. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  49146. vertexData.applyToMesh(polygon, options.updatable);
  49147. return polygon;
  49148. };
  49149. ;
  49150. /**
  49151. * Creates an extruded polygon mesh, with depth in the Y direction.
  49152. * 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).
  49153. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  49154. */
  49155. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  49156. return MeshBuilder.CreatePolygon(name, options, scene);
  49157. };
  49158. ;
  49159. /**
  49160. * Creates a tube mesh.
  49161. * 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.
  49162. *
  49163. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  49164. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  49165. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  49166. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  49167. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  49168. * 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.
  49169. * It must return a radius value (positive float) :
  49170. * ```javascript
  49171. * var radiusFunction = function(i, distance) {
  49172. * // do things
  49173. * return radius; }
  49174. * ```
  49175. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  49176. * 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
  49177. * 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
  49178. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49179. * 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).
  49180. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49181. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49182. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49183. */
  49184. MeshBuilder.CreateTube = function (name, options, scene) {
  49185. var path = options.path;
  49186. var instance = options.instance;
  49187. var radius = 1.0;
  49188. if (instance) {
  49189. radius = instance.radius;
  49190. }
  49191. if (options.radius !== undefined) {
  49192. radius = options.radius;
  49193. }
  49194. ;
  49195. var tessellation = options.tessellation || 64 | 0;
  49196. var radiusFunction = options.radiusFunction || null;
  49197. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  49198. var invertUV = options.invertUV || false;
  49199. var updatable = options.updatable;
  49200. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49201. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  49202. // tube geometry
  49203. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  49204. var tangents = path3D.getTangents();
  49205. var normals = path3D.getNormals();
  49206. var distances = path3D.getDistances();
  49207. var pi2 = Math.PI * 2;
  49208. var step = pi2 / tessellation * arc;
  49209. var returnRadius = function () { return radius; };
  49210. var radiusFunctionFinal = radiusFunction || returnRadius;
  49211. var circlePath;
  49212. var rad;
  49213. var normal;
  49214. var rotated;
  49215. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  49216. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  49217. for (var i = 0; i < path.length; i++) {
  49218. rad = radiusFunctionFinal(i, distances[i]); // current radius
  49219. circlePath = Array(); // current circle array
  49220. normal = normals[i]; // current normal
  49221. for (var t = 0; t < tessellation; t++) {
  49222. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  49223. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  49224. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  49225. rotated.scaleInPlace(rad).addInPlace(path[i]);
  49226. circlePath[t] = rotated;
  49227. }
  49228. circlePaths[index] = circlePath;
  49229. index++;
  49230. }
  49231. // cap
  49232. var capPath = function (nbPoints, pathIndex) {
  49233. var pointCap = Array();
  49234. for (var i = 0; i < nbPoints; i++) {
  49235. pointCap.push(path[pathIndex]);
  49236. }
  49237. return pointCap;
  49238. };
  49239. switch (cap) {
  49240. case BABYLON.Mesh.NO_CAP:
  49241. break;
  49242. case BABYLON.Mesh.CAP_START:
  49243. circlePaths[0] = capPath(tessellation, 0);
  49244. circlePaths[1] = circlePaths[2].slice(0);
  49245. break;
  49246. case BABYLON.Mesh.CAP_END:
  49247. circlePaths[index] = circlePaths[index - 1].slice(0);
  49248. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  49249. break;
  49250. case BABYLON.Mesh.CAP_ALL:
  49251. circlePaths[0] = capPath(tessellation, 0);
  49252. circlePaths[1] = circlePaths[2].slice(0);
  49253. circlePaths[index] = circlePaths[index - 1].slice(0);
  49254. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  49255. break;
  49256. default:
  49257. break;
  49258. }
  49259. return circlePaths;
  49260. };
  49261. var path3D;
  49262. var pathArray;
  49263. if (instance) {
  49264. var arc = options.arc || instance.arc;
  49265. path3D = (instance.path3D).update(path);
  49266. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  49267. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  49268. instance.path3D = path3D;
  49269. instance.pathArray = pathArray;
  49270. instance.arc = arc;
  49271. instance.radius = radius;
  49272. return instance;
  49273. }
  49274. // tube creation
  49275. path3D = new BABYLON.Path3D(path);
  49276. var newPathArray = new Array();
  49277. cap = (cap < 0 || cap > 3) ? 0 : cap;
  49278. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  49279. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  49280. tube.pathArray = pathArray;
  49281. tube.path3D = path3D;
  49282. tube.tessellation = tessellation;
  49283. tube.cap = cap;
  49284. tube.arc = options.arc;
  49285. tube.radius = radius;
  49286. return tube;
  49287. };
  49288. /**
  49289. * Creates a polyhedron mesh.
  49290. *
  49291. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  49292. * 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
  49293. * to choose the wanted type.
  49294. * The parameter `size` (positive float, default 1) sets the polygon size.
  49295. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  49296. * 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`.
  49297. * 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
  49298. * 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)`).
  49299. * 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
  49300. * 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.
  49301. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49302. * 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).
  49303. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49304. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49305. */
  49306. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  49307. var polyhedron = new BABYLON.Mesh(name, scene);
  49308. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49309. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  49310. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  49311. vertexData.applyToMesh(polyhedron, options.updatable);
  49312. return polyhedron;
  49313. };
  49314. /**
  49315. * Creates a decal mesh.
  49316. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  49317. * 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.
  49318. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  49319. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  49320. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  49321. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  49322. */
  49323. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  49324. var indices = sourceMesh.getIndices();
  49325. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49326. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49327. var position = options.position || BABYLON.Vector3.Zero();
  49328. var normal = options.normal || BABYLON.Vector3.Up();
  49329. var size = options.size || BABYLON.Vector3.One();
  49330. var angle = options.angle || 0;
  49331. // Getting correct rotation
  49332. if (!normal) {
  49333. var target = new BABYLON.Vector3(0, 0, 1);
  49334. var camera = sourceMesh.getScene().activeCamera;
  49335. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  49336. normal = camera.globalPosition.subtract(cameraWorldTarget);
  49337. }
  49338. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  49339. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  49340. var pitch = Math.atan2(normal.y, len);
  49341. // Matrix
  49342. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  49343. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  49344. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  49345. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  49346. var vertexData = new BABYLON.VertexData();
  49347. vertexData.indices = [];
  49348. vertexData.positions = [];
  49349. vertexData.normals = [];
  49350. vertexData.uvs = [];
  49351. var currentVertexDataIndex = 0;
  49352. var extractDecalVector3 = function (indexId) {
  49353. var result = new BABYLON.PositionNormalVertex();
  49354. if (!indices || !positions || !normals) {
  49355. return result;
  49356. }
  49357. var vertexId = indices[indexId];
  49358. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  49359. // Send vector to decal local world
  49360. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  49361. // Get normal
  49362. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  49363. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  49364. return result;
  49365. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  49366. var clip = function (vertices, axis) {
  49367. if (vertices.length === 0) {
  49368. return vertices;
  49369. }
  49370. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  49371. var clipVertices = function (v0, v1) {
  49372. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  49373. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  49374. };
  49375. var result = new Array();
  49376. for (var index = 0; index < vertices.length; index += 3) {
  49377. var v1Out;
  49378. var v2Out;
  49379. var v3Out;
  49380. var total = 0;
  49381. var nV1 = null;
  49382. var nV2 = null;
  49383. var nV3 = null;
  49384. var nV4 = null;
  49385. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  49386. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  49387. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  49388. v1Out = d1 > 0;
  49389. v2Out = d2 > 0;
  49390. v3Out = d3 > 0;
  49391. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  49392. switch (total) {
  49393. case 0:
  49394. result.push(vertices[index]);
  49395. result.push(vertices[index + 1]);
  49396. result.push(vertices[index + 2]);
  49397. break;
  49398. case 1:
  49399. if (v1Out) {
  49400. nV1 = vertices[index + 1];
  49401. nV2 = vertices[index + 2];
  49402. nV3 = clipVertices(vertices[index], nV1);
  49403. nV4 = clipVertices(vertices[index], nV2);
  49404. }
  49405. if (v2Out) {
  49406. nV1 = vertices[index];
  49407. nV2 = vertices[index + 2];
  49408. nV3 = clipVertices(vertices[index + 1], nV1);
  49409. nV4 = clipVertices(vertices[index + 1], nV2);
  49410. result.push(nV3);
  49411. result.push(nV2.clone());
  49412. result.push(nV1.clone());
  49413. result.push(nV2.clone());
  49414. result.push(nV3.clone());
  49415. result.push(nV4);
  49416. break;
  49417. }
  49418. if (v3Out) {
  49419. nV1 = vertices[index];
  49420. nV2 = vertices[index + 1];
  49421. nV3 = clipVertices(vertices[index + 2], nV1);
  49422. nV4 = clipVertices(vertices[index + 2], nV2);
  49423. }
  49424. if (nV1 && nV2 && nV3 && nV4) {
  49425. result.push(nV1.clone());
  49426. result.push(nV2.clone());
  49427. result.push(nV3);
  49428. result.push(nV4);
  49429. result.push(nV3.clone());
  49430. result.push(nV2.clone());
  49431. }
  49432. break;
  49433. case 2:
  49434. if (!v1Out) {
  49435. nV1 = vertices[index].clone();
  49436. nV2 = clipVertices(nV1, vertices[index + 1]);
  49437. nV3 = clipVertices(nV1, vertices[index + 2]);
  49438. result.push(nV1);
  49439. result.push(nV2);
  49440. result.push(nV3);
  49441. }
  49442. if (!v2Out) {
  49443. nV1 = vertices[index + 1].clone();
  49444. nV2 = clipVertices(nV1, vertices[index + 2]);
  49445. nV3 = clipVertices(nV1, vertices[index]);
  49446. result.push(nV1);
  49447. result.push(nV2);
  49448. result.push(nV3);
  49449. }
  49450. if (!v3Out) {
  49451. nV1 = vertices[index + 2].clone();
  49452. nV2 = clipVertices(nV1, vertices[index]);
  49453. nV3 = clipVertices(nV1, vertices[index + 1]);
  49454. result.push(nV1);
  49455. result.push(nV2);
  49456. result.push(nV3);
  49457. }
  49458. break;
  49459. case 3:
  49460. break;
  49461. }
  49462. }
  49463. return result;
  49464. };
  49465. for (var index = 0; index < indices.length; index += 3) {
  49466. var faceVertices = new Array();
  49467. faceVertices.push(extractDecalVector3(index));
  49468. faceVertices.push(extractDecalVector3(index + 1));
  49469. faceVertices.push(extractDecalVector3(index + 2));
  49470. // Clip
  49471. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  49472. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  49473. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  49474. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  49475. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  49476. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  49477. if (faceVertices.length === 0) {
  49478. continue;
  49479. }
  49480. // Add UVs and get back to world
  49481. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  49482. var vertex = faceVertices[vIndex];
  49483. //TODO check for Int32Array | Uint32Array | Uint16Array
  49484. vertexData.indices.push(currentVertexDataIndex);
  49485. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  49486. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  49487. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  49488. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  49489. currentVertexDataIndex++;
  49490. }
  49491. }
  49492. // Return mesh
  49493. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  49494. vertexData.applyToMesh(decal);
  49495. decal.position = position.clone();
  49496. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  49497. return decal;
  49498. };
  49499. // Privates
  49500. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  49501. // extrusion geometry
  49502. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  49503. var tangents = path3D.getTangents();
  49504. var normals = path3D.getNormals();
  49505. var binormals = path3D.getBinormals();
  49506. var distances = path3D.getDistances();
  49507. var angle = 0;
  49508. var returnScale = function () { return scale !== null ? scale : 1; };
  49509. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  49510. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  49511. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  49512. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  49513. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  49514. for (var i = 0; i < curve.length; i++) {
  49515. var shapePath = new Array();
  49516. var angleStep = rotate(i, distances[i]);
  49517. var scaleRatio = scl(i, distances[i]);
  49518. for (var p = 0; p < shape.length; p++) {
  49519. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  49520. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  49521. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  49522. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  49523. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  49524. shapePath[p] = rotated;
  49525. }
  49526. shapePaths[index] = shapePath;
  49527. angle += angleStep;
  49528. index++;
  49529. }
  49530. // cap
  49531. var capPath = function (shapePath) {
  49532. var pointCap = Array();
  49533. var barycenter = BABYLON.Vector3.Zero();
  49534. var i;
  49535. for (i = 0; i < shapePath.length; i++) {
  49536. barycenter.addInPlace(shapePath[i]);
  49537. }
  49538. barycenter.scaleInPlace(1.0 / shapePath.length);
  49539. for (i = 0; i < shapePath.length; i++) {
  49540. pointCap.push(barycenter);
  49541. }
  49542. return pointCap;
  49543. };
  49544. switch (cap) {
  49545. case BABYLON.Mesh.NO_CAP:
  49546. break;
  49547. case BABYLON.Mesh.CAP_START:
  49548. shapePaths[0] = capPath(shapePaths[2]);
  49549. shapePaths[1] = shapePaths[2];
  49550. break;
  49551. case BABYLON.Mesh.CAP_END:
  49552. shapePaths[index] = shapePaths[index - 1];
  49553. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  49554. break;
  49555. case BABYLON.Mesh.CAP_ALL:
  49556. shapePaths[0] = capPath(shapePaths[2]);
  49557. shapePaths[1] = shapePaths[2];
  49558. shapePaths[index] = shapePaths[index - 1];
  49559. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  49560. break;
  49561. default:
  49562. break;
  49563. }
  49564. return shapePaths;
  49565. };
  49566. var path3D;
  49567. var pathArray;
  49568. if (instance) {
  49569. path3D = (instance.path3D).update(curve);
  49570. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  49571. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  49572. return instance;
  49573. }
  49574. // extruded shape creation
  49575. path3D = new BABYLON.Path3D(curve);
  49576. var newShapePaths = new Array();
  49577. cap = (cap < 0 || cap > 3) ? 0 : cap;
  49578. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  49579. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  49580. extrudedGeneric.pathArray = pathArray;
  49581. extrudedGeneric.path3D = path3D;
  49582. extrudedGeneric.cap = cap;
  49583. return extrudedGeneric;
  49584. };
  49585. return MeshBuilder;
  49586. }());
  49587. BABYLON.MeshBuilder = MeshBuilder;
  49588. })(BABYLON || (BABYLON = {}));
  49589. //# sourceMappingURL=babylon.meshBuilder.js.map
  49590. var BABYLON;
  49591. (function (BABYLON) {
  49592. var AudioEngine = /** @class */ (function () {
  49593. function AudioEngine() {
  49594. this._audioContext = null;
  49595. this._audioContextInitialized = false;
  49596. this.canUseWebAudio = false;
  49597. this.WarnedWebAudioUnsupported = false;
  49598. this.unlocked = false;
  49599. this.isMP3supported = false;
  49600. this.isOGGsupported = false;
  49601. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  49602. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  49603. this.canUseWebAudio = true;
  49604. }
  49605. var audioElem = document.createElement('audio');
  49606. try {
  49607. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  49608. this.isMP3supported = true;
  49609. }
  49610. }
  49611. catch (e) {
  49612. // protect error during capability check.
  49613. }
  49614. try {
  49615. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  49616. this.isOGGsupported = true;
  49617. }
  49618. }
  49619. catch (e) {
  49620. // protect error during capability check.
  49621. }
  49622. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  49623. this._unlockiOSaudio();
  49624. }
  49625. else {
  49626. this.unlocked = true;
  49627. }
  49628. }
  49629. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  49630. get: function () {
  49631. if (!this._audioContextInitialized) {
  49632. this._initializeAudioContext();
  49633. }
  49634. return this._audioContext;
  49635. },
  49636. enumerable: true,
  49637. configurable: true
  49638. });
  49639. AudioEngine.prototype._unlockiOSaudio = function () {
  49640. var _this = this;
  49641. var unlockaudio = function () {
  49642. if (!_this.audioContext) {
  49643. return;
  49644. }
  49645. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  49646. var source = _this.audioContext.createBufferSource();
  49647. source.buffer = buffer;
  49648. source.connect(_this.audioContext.destination);
  49649. source.start(0);
  49650. setTimeout(function () {
  49651. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  49652. _this.unlocked = true;
  49653. window.removeEventListener('touchend', unlockaudio, false);
  49654. if (_this.onAudioUnlocked) {
  49655. _this.onAudioUnlocked();
  49656. }
  49657. }
  49658. }, 0);
  49659. };
  49660. window.addEventListener('touchend', unlockaudio, false);
  49661. };
  49662. AudioEngine.prototype._initializeAudioContext = function () {
  49663. try {
  49664. if (this.canUseWebAudio) {
  49665. this._audioContext = new AudioContext();
  49666. // create a global volume gain node
  49667. this.masterGain = this._audioContext.createGain();
  49668. this.masterGain.gain.value = 1;
  49669. this.masterGain.connect(this._audioContext.destination);
  49670. this._audioContextInitialized = true;
  49671. }
  49672. }
  49673. catch (e) {
  49674. this.canUseWebAudio = false;
  49675. BABYLON.Tools.Error("Web Audio: " + e.message);
  49676. }
  49677. };
  49678. AudioEngine.prototype.dispose = function () {
  49679. if (this.canUseWebAudio && this._audioContextInitialized) {
  49680. if (this._connectedAnalyser && this._audioContext) {
  49681. this._connectedAnalyser.stopDebugCanvas();
  49682. this._connectedAnalyser.dispose();
  49683. this.masterGain.disconnect();
  49684. this.masterGain.connect(this._audioContext.destination);
  49685. this._connectedAnalyser = null;
  49686. }
  49687. this.masterGain.gain.value = 1;
  49688. }
  49689. this.WarnedWebAudioUnsupported = false;
  49690. };
  49691. AudioEngine.prototype.getGlobalVolume = function () {
  49692. if (this.canUseWebAudio && this._audioContextInitialized) {
  49693. return this.masterGain.gain.value;
  49694. }
  49695. else {
  49696. return -1;
  49697. }
  49698. };
  49699. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  49700. if (this.canUseWebAudio && this._audioContextInitialized) {
  49701. this.masterGain.gain.value = newVolume;
  49702. }
  49703. };
  49704. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  49705. if (this._connectedAnalyser) {
  49706. this._connectedAnalyser.stopDebugCanvas();
  49707. }
  49708. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  49709. this._connectedAnalyser = analyser;
  49710. this.masterGain.disconnect();
  49711. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  49712. }
  49713. };
  49714. return AudioEngine;
  49715. }());
  49716. BABYLON.AudioEngine = AudioEngine;
  49717. })(BABYLON || (BABYLON = {}));
  49718. //# sourceMappingURL=babylon.audioEngine.js.map
  49719. var BABYLON;
  49720. (function (BABYLON) {
  49721. var Sound = /** @class */ (function () {
  49722. /**
  49723. * Create a sound and attach it to a scene
  49724. * @param name Name of your sound
  49725. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  49726. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  49727. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  49728. */
  49729. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  49730. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  49731. var _this = this;
  49732. this.autoplay = false;
  49733. this.loop = false;
  49734. this.useCustomAttenuation = false;
  49735. this.spatialSound = false;
  49736. this.refDistance = 1;
  49737. this.rolloffFactor = 1;
  49738. this.maxDistance = 100;
  49739. this.distanceModel = "linear";
  49740. this._panningModel = "equalpower";
  49741. this._playbackRate = 1;
  49742. this._streaming = false;
  49743. this._startTime = 0;
  49744. this._startOffset = 0;
  49745. this._position = BABYLON.Vector3.Zero();
  49746. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  49747. this._volume = 1;
  49748. this._isReadyToPlay = false;
  49749. this.isPlaying = false;
  49750. this.isPaused = false;
  49751. this._isDirectional = false;
  49752. // Used if you'd like to create a directional sound.
  49753. // If not set, the sound will be omnidirectional
  49754. this._coneInnerAngle = 360;
  49755. this._coneOuterAngle = 360;
  49756. this._coneOuterGain = 0;
  49757. this._isOutputConnected = false;
  49758. this._urlType = "Unknown";
  49759. this.name = name;
  49760. this._scene = scene;
  49761. this._readyToPlayCallback = readyToPlayCallback;
  49762. // Default custom attenuation function is a linear attenuation
  49763. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  49764. if (currentDistance < maxDistance) {
  49765. return currentVolume * (1 - currentDistance / maxDistance);
  49766. }
  49767. else {
  49768. return 0;
  49769. }
  49770. };
  49771. if (options) {
  49772. this.autoplay = options.autoplay || false;
  49773. this.loop = options.loop || false;
  49774. // if volume === 0, we need another way to check this option
  49775. if (options.volume !== undefined) {
  49776. this._volume = options.volume;
  49777. }
  49778. this.spatialSound = options.spatialSound || false;
  49779. this.maxDistance = options.maxDistance || 100;
  49780. this.useCustomAttenuation = options.useCustomAttenuation || false;
  49781. this.rolloffFactor = options.rolloffFactor || 1;
  49782. this.refDistance = options.refDistance || 1;
  49783. this.distanceModel = options.distanceModel || "linear";
  49784. this._playbackRate = options.playbackRate || 1;
  49785. this._streaming = options.streaming || false;
  49786. }
  49787. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  49788. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  49789. this._soundGain.gain.value = this._volume;
  49790. this._inputAudioNode = this._soundGain;
  49791. this._ouputAudioNode = this._soundGain;
  49792. if (this.spatialSound) {
  49793. this._createSpatialParameters();
  49794. }
  49795. this._scene.mainSoundTrack.AddSound(this);
  49796. var validParameter = true;
  49797. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  49798. if (urlOrArrayBuffer) {
  49799. if (typeof (urlOrArrayBuffer) === "string")
  49800. this._urlType = "String";
  49801. if (Array.isArray(urlOrArrayBuffer))
  49802. this._urlType = "Array";
  49803. if (urlOrArrayBuffer instanceof ArrayBuffer)
  49804. this._urlType = "ArrayBuffer";
  49805. var urls = [];
  49806. var codecSupportedFound = false;
  49807. switch (this._urlType) {
  49808. case "ArrayBuffer":
  49809. if (urlOrArrayBuffer.byteLength > 0) {
  49810. codecSupportedFound = true;
  49811. this._soundLoaded(urlOrArrayBuffer);
  49812. }
  49813. break;
  49814. case "String":
  49815. urls.push(urlOrArrayBuffer);
  49816. case "Array":
  49817. if (urls.length === 0)
  49818. urls = urlOrArrayBuffer;
  49819. // If we found a supported format, we load it immediately and stop the loop
  49820. for (var i = 0; i < urls.length; i++) {
  49821. var url = urls[i];
  49822. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  49823. codecSupportedFound = true;
  49824. }
  49825. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  49826. codecSupportedFound = true;
  49827. }
  49828. if (url.indexOf(".wav", url.length - 4) !== -1) {
  49829. codecSupportedFound = true;
  49830. }
  49831. if (url.indexOf("blob:") !== -1) {
  49832. codecSupportedFound = true;
  49833. }
  49834. if (codecSupportedFound) {
  49835. // Loading sound using XHR2
  49836. if (!this._streaming) {
  49837. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, undefined, this._scene.database, true);
  49838. }
  49839. else {
  49840. this._htmlAudioElement = new Audio(url);
  49841. this._htmlAudioElement.controls = false;
  49842. this._htmlAudioElement.loop = this.loop;
  49843. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  49844. this._htmlAudioElement.preload = "auto";
  49845. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  49846. _this._isReadyToPlay = true;
  49847. if (_this.autoplay) {
  49848. _this.play();
  49849. }
  49850. if (_this._readyToPlayCallback) {
  49851. _this._readyToPlayCallback();
  49852. }
  49853. });
  49854. document.body.appendChild(this._htmlAudioElement);
  49855. }
  49856. break;
  49857. }
  49858. }
  49859. break;
  49860. default:
  49861. validParameter = false;
  49862. break;
  49863. }
  49864. if (!validParameter) {
  49865. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  49866. }
  49867. else {
  49868. if (!codecSupportedFound) {
  49869. this._isReadyToPlay = true;
  49870. // Simulating a ready to play event to avoid breaking code path
  49871. if (this._readyToPlayCallback) {
  49872. window.setTimeout(function () {
  49873. if (_this._readyToPlayCallback) {
  49874. _this._readyToPlayCallback();
  49875. }
  49876. }, 1000);
  49877. }
  49878. }
  49879. }
  49880. }
  49881. }
  49882. else {
  49883. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  49884. this._scene.mainSoundTrack.AddSound(this);
  49885. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  49886. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  49887. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  49888. }
  49889. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  49890. if (this._readyToPlayCallback) {
  49891. window.setTimeout(function () {
  49892. if (_this._readyToPlayCallback) {
  49893. _this._readyToPlayCallback();
  49894. }
  49895. }, 1000);
  49896. }
  49897. }
  49898. }
  49899. Sound.prototype.dispose = function () {
  49900. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  49901. if (this.isPlaying) {
  49902. this.stop();
  49903. }
  49904. this._isReadyToPlay = false;
  49905. if (this.soundTrackId === -1) {
  49906. this._scene.mainSoundTrack.RemoveSound(this);
  49907. }
  49908. else {
  49909. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  49910. }
  49911. if (this._soundGain) {
  49912. this._soundGain.disconnect();
  49913. this._soundGain = null;
  49914. }
  49915. if (this._soundPanner) {
  49916. this._soundPanner.disconnect();
  49917. this._soundPanner = null;
  49918. }
  49919. if (this._soundSource) {
  49920. this._soundSource.disconnect();
  49921. this._soundSource = null;
  49922. }
  49923. this._audioBuffer = null;
  49924. if (this._htmlAudioElement) {
  49925. this._htmlAudioElement.pause();
  49926. this._htmlAudioElement.src = "";
  49927. document.body.removeChild(this._htmlAudioElement);
  49928. }
  49929. if (this._connectedMesh && this._registerFunc) {
  49930. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  49931. this._connectedMesh = null;
  49932. }
  49933. }
  49934. };
  49935. Sound.prototype.isReady = function () {
  49936. return this._isReadyToPlay;
  49937. };
  49938. Sound.prototype._soundLoaded = function (audioData) {
  49939. var _this = this;
  49940. if (!BABYLON.Engine.audioEngine.audioContext) {
  49941. return;
  49942. }
  49943. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  49944. _this._audioBuffer = buffer;
  49945. _this._isReadyToPlay = true;
  49946. if (_this.autoplay) {
  49947. _this.play();
  49948. }
  49949. if (_this._readyToPlayCallback) {
  49950. _this._readyToPlayCallback();
  49951. }
  49952. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  49953. };
  49954. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  49955. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49956. this._audioBuffer = audioBuffer;
  49957. this._isReadyToPlay = true;
  49958. }
  49959. };
  49960. Sound.prototype.updateOptions = function (options) {
  49961. if (options) {
  49962. this.loop = options.loop || this.loop;
  49963. this.maxDistance = options.maxDistance || this.maxDistance;
  49964. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  49965. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  49966. this.refDistance = options.refDistance || this.refDistance;
  49967. this.distanceModel = options.distanceModel || this.distanceModel;
  49968. this._playbackRate = options.playbackRate || this._playbackRate;
  49969. this._updateSpatialParameters();
  49970. if (this.isPlaying) {
  49971. if (this._streaming) {
  49972. this._htmlAudioElement.playbackRate = this._playbackRate;
  49973. }
  49974. else {
  49975. if (this._soundSource) {
  49976. this._soundSource.playbackRate.value = this._playbackRate;
  49977. }
  49978. }
  49979. }
  49980. }
  49981. };
  49982. Sound.prototype._createSpatialParameters = function () {
  49983. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  49984. if (this._scene.headphone) {
  49985. this._panningModel = "HRTF";
  49986. }
  49987. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  49988. this._updateSpatialParameters();
  49989. this._soundPanner.connect(this._ouputAudioNode);
  49990. this._inputAudioNode = this._soundPanner;
  49991. }
  49992. };
  49993. Sound.prototype._updateSpatialParameters = function () {
  49994. if (this.spatialSound && this._soundPanner) {
  49995. if (this.useCustomAttenuation) {
  49996. // Tricks to disable in a way embedded Web Audio attenuation
  49997. this._soundPanner.distanceModel = "linear";
  49998. this._soundPanner.maxDistance = Number.MAX_VALUE;
  49999. this._soundPanner.refDistance = 1;
  50000. this._soundPanner.rolloffFactor = 1;
  50001. this._soundPanner.panningModel = this._panningModel;
  50002. }
  50003. else {
  50004. this._soundPanner.distanceModel = this.distanceModel;
  50005. this._soundPanner.maxDistance = this.maxDistance;
  50006. this._soundPanner.refDistance = this.refDistance;
  50007. this._soundPanner.rolloffFactor = this.rolloffFactor;
  50008. this._soundPanner.panningModel = this._panningModel;
  50009. }
  50010. }
  50011. };
  50012. Sound.prototype.switchPanningModelToHRTF = function () {
  50013. this._panningModel = "HRTF";
  50014. this._switchPanningModel();
  50015. };
  50016. Sound.prototype.switchPanningModelToEqualPower = function () {
  50017. this._panningModel = "equalpower";
  50018. this._switchPanningModel();
  50019. };
  50020. Sound.prototype._switchPanningModel = function () {
  50021. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  50022. this._soundPanner.panningModel = this._panningModel;
  50023. }
  50024. };
  50025. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  50026. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  50027. if (this._isOutputConnected) {
  50028. this._ouputAudioNode.disconnect();
  50029. }
  50030. this._ouputAudioNode.connect(soundTrackAudioNode);
  50031. this._isOutputConnected = true;
  50032. }
  50033. };
  50034. /**
  50035. * Transform this sound into a directional source
  50036. * @param coneInnerAngle Size of the inner cone in degree
  50037. * @param coneOuterAngle Size of the outer cone in degree
  50038. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  50039. */
  50040. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  50041. if (coneOuterAngle < coneInnerAngle) {
  50042. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  50043. return;
  50044. }
  50045. this._coneInnerAngle = coneInnerAngle;
  50046. this._coneOuterAngle = coneOuterAngle;
  50047. this._coneOuterGain = coneOuterGain;
  50048. this._isDirectional = true;
  50049. if (this.isPlaying && this.loop) {
  50050. this.stop();
  50051. this.play();
  50052. }
  50053. };
  50054. Sound.prototype.setPosition = function (newPosition) {
  50055. this._position = newPosition;
  50056. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  50057. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  50058. }
  50059. };
  50060. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  50061. this._localDirection = newLocalDirection;
  50062. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  50063. this._updateDirection();
  50064. }
  50065. };
  50066. Sound.prototype._updateDirection = function () {
  50067. if (!this._connectedMesh || !this._soundPanner) {
  50068. return;
  50069. }
  50070. var mat = this._connectedMesh.getWorldMatrix();
  50071. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  50072. direction.normalize();
  50073. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  50074. };
  50075. Sound.prototype.updateDistanceFromListener = function () {
  50076. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  50077. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  50078. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  50079. }
  50080. };
  50081. Sound.prototype.setAttenuationFunction = function (callback) {
  50082. this._customAttenuationFunction = callback;
  50083. };
  50084. /**
  50085. * Play the sound
  50086. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  50087. * @param offset (optional) Start the sound setting it at a specific time
  50088. */
  50089. Sound.prototype.play = function (time, offset) {
  50090. var _this = this;
  50091. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  50092. try {
  50093. if (this._startOffset < 0) {
  50094. time = -this._startOffset;
  50095. this._startOffset = 0;
  50096. }
  50097. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  50098. if (!this._soundSource || !this._streamingSource) {
  50099. if (this.spatialSound && this._soundPanner) {
  50100. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  50101. if (this._isDirectional) {
  50102. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  50103. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  50104. this._soundPanner.coneOuterGain = this._coneOuterGain;
  50105. if (this._connectedMesh) {
  50106. this._updateDirection();
  50107. }
  50108. else {
  50109. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  50110. }
  50111. }
  50112. }
  50113. }
  50114. if (this._streaming) {
  50115. if (!this._streamingSource) {
  50116. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  50117. this._htmlAudioElement.onended = function () { _this._onended(); };
  50118. this._htmlAudioElement.playbackRate = this._playbackRate;
  50119. }
  50120. this._streamingSource.disconnect();
  50121. this._streamingSource.connect(this._inputAudioNode);
  50122. this._htmlAudioElement.play();
  50123. }
  50124. else {
  50125. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  50126. this._soundSource.buffer = this._audioBuffer;
  50127. this._soundSource.connect(this._inputAudioNode);
  50128. this._soundSource.loop = this.loop;
  50129. this._soundSource.playbackRate.value = this._playbackRate;
  50130. this._soundSource.onended = function () { _this._onended(); };
  50131. if (this._soundSource.buffer) {
  50132. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  50133. }
  50134. }
  50135. this._startTime = startTime;
  50136. this.isPlaying = true;
  50137. this.isPaused = false;
  50138. }
  50139. catch (ex) {
  50140. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  50141. }
  50142. }
  50143. };
  50144. Sound.prototype._onended = function () {
  50145. this.isPlaying = false;
  50146. if (this.onended) {
  50147. this.onended();
  50148. }
  50149. };
  50150. /**
  50151. * Stop the sound
  50152. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  50153. */
  50154. Sound.prototype.stop = function (time) {
  50155. if (this.isPlaying) {
  50156. if (this._streaming) {
  50157. this._htmlAudioElement.pause();
  50158. // Test needed for Firefox or it will generate an Invalid State Error
  50159. if (this._htmlAudioElement.currentTime > 0) {
  50160. this._htmlAudioElement.currentTime = 0;
  50161. }
  50162. }
  50163. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  50164. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  50165. this._soundSource.stop(stopTime);
  50166. this._soundSource.onended = function () { };
  50167. if (!this.isPaused) {
  50168. this._startOffset = 0;
  50169. }
  50170. }
  50171. this.isPlaying = false;
  50172. }
  50173. };
  50174. Sound.prototype.pause = function () {
  50175. if (this.isPlaying) {
  50176. this.isPaused = true;
  50177. if (this._streaming) {
  50178. this._htmlAudioElement.pause();
  50179. }
  50180. else if (BABYLON.Engine.audioEngine.audioContext) {
  50181. this.stop(0);
  50182. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  50183. }
  50184. }
  50185. };
  50186. Sound.prototype.setVolume = function (newVolume, time) {
  50187. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  50188. if (time && BABYLON.Engine.audioEngine.audioContext) {
  50189. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  50190. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  50191. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  50192. }
  50193. else {
  50194. this._soundGain.gain.value = newVolume;
  50195. }
  50196. }
  50197. this._volume = newVolume;
  50198. };
  50199. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  50200. this._playbackRate = newPlaybackRate;
  50201. if (this.isPlaying) {
  50202. if (this._streaming) {
  50203. this._htmlAudioElement.playbackRate = this._playbackRate;
  50204. }
  50205. else if (this._soundSource) {
  50206. this._soundSource.playbackRate.value = this._playbackRate;
  50207. }
  50208. }
  50209. };
  50210. Sound.prototype.getVolume = function () {
  50211. return this._volume;
  50212. };
  50213. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  50214. var _this = this;
  50215. if (this._connectedMesh && this._registerFunc) {
  50216. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  50217. this._registerFunc = null;
  50218. }
  50219. this._connectedMesh = meshToConnectTo;
  50220. if (!this.spatialSound) {
  50221. this.spatialSound = true;
  50222. this._createSpatialParameters();
  50223. if (this.isPlaying && this.loop) {
  50224. this.stop();
  50225. this.play();
  50226. }
  50227. }
  50228. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  50229. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  50230. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  50231. };
  50232. Sound.prototype.detachFromMesh = function () {
  50233. if (this._connectedMesh && this._registerFunc) {
  50234. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  50235. this._registerFunc = null;
  50236. this._connectedMesh = null;
  50237. }
  50238. };
  50239. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  50240. if (!node.getBoundingInfo) {
  50241. return;
  50242. }
  50243. var mesh = node;
  50244. var boundingInfo = mesh.getBoundingInfo();
  50245. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  50246. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  50247. this._updateDirection();
  50248. }
  50249. };
  50250. Sound.prototype.clone = function () {
  50251. var _this = this;
  50252. if (!this._streaming) {
  50253. var setBufferAndRun = function () {
  50254. if (_this._isReadyToPlay) {
  50255. clonedSound._audioBuffer = _this.getAudioBuffer();
  50256. clonedSound._isReadyToPlay = true;
  50257. if (clonedSound.autoplay) {
  50258. clonedSound.play();
  50259. }
  50260. }
  50261. else {
  50262. window.setTimeout(setBufferAndRun, 300);
  50263. }
  50264. };
  50265. var currentOptions = {
  50266. autoplay: this.autoplay, loop: this.loop,
  50267. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  50268. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  50269. refDistance: this.refDistance, distanceModel: this.distanceModel
  50270. };
  50271. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  50272. if (this.useCustomAttenuation) {
  50273. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  50274. }
  50275. clonedSound.setPosition(this._position);
  50276. clonedSound.setPlaybackRate(this._playbackRate);
  50277. setBufferAndRun();
  50278. return clonedSound;
  50279. }
  50280. else {
  50281. return null;
  50282. }
  50283. };
  50284. Sound.prototype.getAudioBuffer = function () {
  50285. return this._audioBuffer;
  50286. };
  50287. Sound.prototype.serialize = function () {
  50288. var serializationObject = {
  50289. name: this.name,
  50290. url: this.name,
  50291. autoplay: this.autoplay,
  50292. loop: this.loop,
  50293. volume: this._volume,
  50294. spatialSound: this.spatialSound,
  50295. maxDistance: this.maxDistance,
  50296. rolloffFactor: this.rolloffFactor,
  50297. refDistance: this.refDistance,
  50298. distanceModel: this.distanceModel,
  50299. playbackRate: this._playbackRate,
  50300. panningModel: this._panningModel,
  50301. soundTrackId: this.soundTrackId
  50302. };
  50303. if (this.spatialSound) {
  50304. if (this._connectedMesh)
  50305. serializationObject.connectedMeshId = this._connectedMesh.id;
  50306. serializationObject.position = this._position.asArray();
  50307. serializationObject.refDistance = this.refDistance;
  50308. serializationObject.distanceModel = this.distanceModel;
  50309. serializationObject.isDirectional = this._isDirectional;
  50310. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  50311. serializationObject.coneInnerAngle = this._coneInnerAngle;
  50312. serializationObject.coneOuterAngle = this._coneOuterAngle;
  50313. serializationObject.coneOuterGain = this._coneOuterGain;
  50314. }
  50315. return serializationObject;
  50316. };
  50317. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  50318. var soundName = parsedSound.name;
  50319. var soundUrl;
  50320. if (parsedSound.url) {
  50321. soundUrl = rootUrl + parsedSound.url;
  50322. }
  50323. else {
  50324. soundUrl = rootUrl + soundName;
  50325. }
  50326. var options = {
  50327. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  50328. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  50329. rolloffFactor: parsedSound.rolloffFactor,
  50330. refDistance: parsedSound.refDistance,
  50331. distanceModel: parsedSound.distanceModel,
  50332. playbackRate: parsedSound.playbackRate
  50333. };
  50334. var newSound;
  50335. if (!sourceSound) {
  50336. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  50337. scene._addPendingData(newSound);
  50338. }
  50339. else {
  50340. var setBufferAndRun = function () {
  50341. if (sourceSound._isReadyToPlay) {
  50342. newSound._audioBuffer = sourceSound.getAudioBuffer();
  50343. newSound._isReadyToPlay = true;
  50344. if (newSound.autoplay) {
  50345. newSound.play();
  50346. }
  50347. }
  50348. else {
  50349. window.setTimeout(setBufferAndRun, 300);
  50350. }
  50351. };
  50352. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  50353. setBufferAndRun();
  50354. }
  50355. if (parsedSound.position) {
  50356. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  50357. newSound.setPosition(soundPosition);
  50358. }
  50359. if (parsedSound.isDirectional) {
  50360. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  50361. if (parsedSound.localDirectionToMesh) {
  50362. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  50363. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  50364. }
  50365. }
  50366. if (parsedSound.connectedMeshId) {
  50367. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  50368. if (connectedMesh) {
  50369. newSound.attachToMesh(connectedMesh);
  50370. }
  50371. }
  50372. return newSound;
  50373. };
  50374. return Sound;
  50375. }());
  50376. BABYLON.Sound = Sound;
  50377. })(BABYLON || (BABYLON = {}));
  50378. //# sourceMappingURL=babylon.sound.js.map
  50379. var BABYLON;
  50380. (function (BABYLON) {
  50381. var SoundTrack = /** @class */ (function () {
  50382. function SoundTrack(scene, options) {
  50383. this.id = -1;
  50384. this._isMainTrack = false;
  50385. this._isInitialized = false;
  50386. this._scene = scene;
  50387. this.soundCollection = new Array();
  50388. this._options = options;
  50389. if (!this._isMainTrack) {
  50390. this._scene.soundTracks.push(this);
  50391. this.id = this._scene.soundTracks.length - 1;
  50392. }
  50393. }
  50394. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  50395. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  50396. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  50397. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  50398. if (this._options) {
  50399. if (this._options.volume) {
  50400. this._outputAudioNode.gain.value = this._options.volume;
  50401. }
  50402. if (this._options.mainTrack) {
  50403. this._isMainTrack = this._options.mainTrack;
  50404. }
  50405. }
  50406. this._isInitialized = true;
  50407. }
  50408. };
  50409. SoundTrack.prototype.dispose = function () {
  50410. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  50411. if (this._connectedAnalyser) {
  50412. this._connectedAnalyser.stopDebugCanvas();
  50413. }
  50414. while (this.soundCollection.length) {
  50415. this.soundCollection[0].dispose();
  50416. }
  50417. if (this._outputAudioNode) {
  50418. this._outputAudioNode.disconnect();
  50419. }
  50420. this._outputAudioNode = null;
  50421. }
  50422. };
  50423. SoundTrack.prototype.AddSound = function (sound) {
  50424. if (!this._isInitialized) {
  50425. this._initializeSoundTrackAudioGraph();
  50426. }
  50427. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  50428. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  50429. }
  50430. if (sound.soundTrackId) {
  50431. if (sound.soundTrackId === -1) {
  50432. this._scene.mainSoundTrack.RemoveSound(sound);
  50433. }
  50434. else {
  50435. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  50436. }
  50437. }
  50438. this.soundCollection.push(sound);
  50439. sound.soundTrackId = this.id;
  50440. };
  50441. SoundTrack.prototype.RemoveSound = function (sound) {
  50442. var index = this.soundCollection.indexOf(sound);
  50443. if (index !== -1) {
  50444. this.soundCollection.splice(index, 1);
  50445. }
  50446. };
  50447. SoundTrack.prototype.setVolume = function (newVolume) {
  50448. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  50449. this._outputAudioNode.gain.value = newVolume;
  50450. }
  50451. };
  50452. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  50453. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  50454. for (var i = 0; i < this.soundCollection.length; i++) {
  50455. this.soundCollection[i].switchPanningModelToHRTF();
  50456. }
  50457. }
  50458. };
  50459. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  50460. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  50461. for (var i = 0; i < this.soundCollection.length; i++) {
  50462. this.soundCollection[i].switchPanningModelToEqualPower();
  50463. }
  50464. }
  50465. };
  50466. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  50467. if (this._connectedAnalyser) {
  50468. this._connectedAnalyser.stopDebugCanvas();
  50469. }
  50470. this._connectedAnalyser = analyser;
  50471. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  50472. this._outputAudioNode.disconnect();
  50473. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  50474. }
  50475. };
  50476. return SoundTrack;
  50477. }());
  50478. BABYLON.SoundTrack = SoundTrack;
  50479. })(BABYLON || (BABYLON = {}));
  50480. //# sourceMappingURL=babylon.soundtrack.js.map
  50481. var BABYLON;
  50482. (function (BABYLON) {
  50483. var Analyser = /** @class */ (function () {
  50484. function Analyser(scene) {
  50485. this.SMOOTHING = 0.75;
  50486. this.FFT_SIZE = 512;
  50487. this.BARGRAPHAMPLITUDE = 256;
  50488. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  50489. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  50490. this._scene = scene;
  50491. this._audioEngine = BABYLON.Engine.audioEngine;
  50492. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  50493. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  50494. this._webAudioAnalyser.minDecibels = -140;
  50495. this._webAudioAnalyser.maxDecibels = 0;
  50496. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  50497. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  50498. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  50499. }
  50500. }
  50501. Analyser.prototype.getFrequencyBinCount = function () {
  50502. if (this._audioEngine.canUseWebAudio) {
  50503. return this._webAudioAnalyser.frequencyBinCount;
  50504. }
  50505. else {
  50506. return 0;
  50507. }
  50508. };
  50509. Analyser.prototype.getByteFrequencyData = function () {
  50510. if (this._audioEngine.canUseWebAudio) {
  50511. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  50512. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  50513. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  50514. }
  50515. return this._byteFreqs;
  50516. };
  50517. Analyser.prototype.getByteTimeDomainData = function () {
  50518. if (this._audioEngine.canUseWebAudio) {
  50519. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  50520. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  50521. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  50522. }
  50523. return this._byteTime;
  50524. };
  50525. Analyser.prototype.getFloatFrequencyData = function () {
  50526. if (this._audioEngine.canUseWebAudio) {
  50527. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  50528. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  50529. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  50530. }
  50531. return this._floatFreqs;
  50532. };
  50533. Analyser.prototype.drawDebugCanvas = function () {
  50534. var _this = this;
  50535. if (this._audioEngine.canUseWebAudio) {
  50536. if (!this._debugCanvas) {
  50537. this._debugCanvas = document.createElement("canvas");
  50538. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  50539. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  50540. this._debugCanvas.style.position = "absolute";
  50541. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  50542. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  50543. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  50544. document.body.appendChild(this._debugCanvas);
  50545. this._registerFunc = function () {
  50546. _this.drawDebugCanvas();
  50547. };
  50548. this._scene.registerBeforeRender(this._registerFunc);
  50549. }
  50550. if (this._registerFunc && this._debugCanvasContext) {
  50551. var workingArray = this.getByteFrequencyData();
  50552. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  50553. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  50554. // Draw the frequency domain chart.
  50555. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  50556. var value = workingArray[i];
  50557. var percent = value / this.BARGRAPHAMPLITUDE;
  50558. var height = this.DEBUGCANVASSIZE.height * percent;
  50559. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  50560. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  50561. var hue = i / this.getFrequencyBinCount() * 360;
  50562. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  50563. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  50564. }
  50565. }
  50566. }
  50567. };
  50568. Analyser.prototype.stopDebugCanvas = function () {
  50569. if (this._debugCanvas) {
  50570. if (this._registerFunc) {
  50571. this._scene.unregisterBeforeRender(this._registerFunc);
  50572. this._registerFunc = null;
  50573. }
  50574. document.body.removeChild(this._debugCanvas);
  50575. this._debugCanvas = null;
  50576. this._debugCanvasContext = null;
  50577. }
  50578. };
  50579. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  50580. if (this._audioEngine.canUseWebAudio) {
  50581. inputAudioNode.connect(this._webAudioAnalyser);
  50582. this._webAudioAnalyser.connect(outputAudioNode);
  50583. }
  50584. };
  50585. Analyser.prototype.dispose = function () {
  50586. if (this._audioEngine.canUseWebAudio) {
  50587. this._webAudioAnalyser.disconnect();
  50588. }
  50589. };
  50590. return Analyser;
  50591. }());
  50592. BABYLON.Analyser = Analyser;
  50593. })(BABYLON || (BABYLON = {}));
  50594. //# sourceMappingURL=babylon.analyser.js.map
  50595. var BABYLON;
  50596. (function (BABYLON) {
  50597. var CubeTexture = /** @class */ (function (_super) {
  50598. __extends(CubeTexture, _super);
  50599. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  50600. if (extensions === void 0) { extensions = null; }
  50601. if (noMipmap === void 0) { noMipmap = false; }
  50602. if (files === void 0) { files = null; }
  50603. if (onLoad === void 0) { onLoad = null; }
  50604. if (onError === void 0) { onError = null; }
  50605. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  50606. if (prefiltered === void 0) { prefiltered = false; }
  50607. if (forcedExtension === void 0) { forcedExtension = null; }
  50608. var _this = _super.call(this, scene) || this;
  50609. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  50610. _this.name = rootUrl;
  50611. _this.url = rootUrl;
  50612. _this._noMipmap = noMipmap;
  50613. _this.hasAlpha = false;
  50614. _this._format = format;
  50615. _this._prefiltered = prefiltered;
  50616. _this.isCube = true;
  50617. _this._textureMatrix = BABYLON.Matrix.Identity();
  50618. if (prefiltered) {
  50619. _this.gammaSpace = false;
  50620. }
  50621. if (!rootUrl && !files) {
  50622. return _this;
  50623. }
  50624. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  50625. var lastDot = rootUrl.lastIndexOf(".");
  50626. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  50627. var isDDS = (extension === ".dds");
  50628. if (!files) {
  50629. if (!isDDS && !extensions) {
  50630. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  50631. }
  50632. files = [];
  50633. if (extensions) {
  50634. for (var index = 0; index < extensions.length; index++) {
  50635. files.push(rootUrl + extensions[index]);
  50636. }
  50637. }
  50638. }
  50639. _this._files = files;
  50640. if (!_this._texture) {
  50641. if (!scene.useDelayedTextureLoading) {
  50642. if (prefiltered) {
  50643. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  50644. }
  50645. else {
  50646. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  50647. }
  50648. }
  50649. else {
  50650. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  50651. }
  50652. }
  50653. else if (onLoad) {
  50654. if (_this._texture.isReady) {
  50655. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  50656. }
  50657. else {
  50658. _this._texture.onLoadedObservable.add(onLoad);
  50659. }
  50660. }
  50661. return _this;
  50662. }
  50663. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  50664. return new CubeTexture("", scene, null, noMipmap, files);
  50665. };
  50666. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  50667. if (forcedExtension === void 0) { forcedExtension = null; }
  50668. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  50669. };
  50670. // Methods
  50671. CubeTexture.prototype.delayLoad = function () {
  50672. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  50673. return;
  50674. }
  50675. var scene = this.getScene();
  50676. if (!scene) {
  50677. return;
  50678. }
  50679. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  50680. this._texture = this._getFromCache(this.url, this._noMipmap);
  50681. if (!this._texture) {
  50682. if (this._prefiltered) {
  50683. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  50684. }
  50685. else {
  50686. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  50687. }
  50688. }
  50689. };
  50690. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  50691. return this._textureMatrix;
  50692. };
  50693. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  50694. this._textureMatrix = value;
  50695. };
  50696. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  50697. var texture = BABYLON.SerializationHelper.Parse(function () {
  50698. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  50699. }, parsedTexture, scene);
  50700. // Animations
  50701. if (parsedTexture.animations) {
  50702. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  50703. var parsedAnimation = parsedTexture.animations[animationIndex];
  50704. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  50705. }
  50706. }
  50707. return texture;
  50708. };
  50709. CubeTexture.prototype.clone = function () {
  50710. var _this = this;
  50711. return BABYLON.SerializationHelper.Clone(function () {
  50712. var scene = _this.getScene();
  50713. if (!scene) {
  50714. return _this;
  50715. }
  50716. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  50717. }, this);
  50718. };
  50719. return CubeTexture;
  50720. }(BABYLON.BaseTexture));
  50721. BABYLON.CubeTexture = CubeTexture;
  50722. })(BABYLON || (BABYLON = {}));
  50723. //# sourceMappingURL=babylon.cubeTexture.js.map
  50724. var BABYLON;
  50725. (function (BABYLON) {
  50726. var RenderTargetTexture = /** @class */ (function (_super) {
  50727. __extends(RenderTargetTexture, _super);
  50728. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  50729. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  50730. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50731. if (isCube === void 0) { isCube = false; }
  50732. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50733. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  50734. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  50735. if (isMulti === void 0) { isMulti = false; }
  50736. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  50737. _this.isCube = isCube;
  50738. /**
  50739. * Use this list to define the list of mesh you want to render.
  50740. */
  50741. _this.renderList = new Array();
  50742. _this.renderParticles = true;
  50743. _this.renderSprites = false;
  50744. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  50745. _this.ignoreCameraViewport = false;
  50746. // Events
  50747. /**
  50748. * An event triggered when the texture is unbind.
  50749. * @type {BABYLON.Observable}
  50750. */
  50751. _this.onBeforeBindObservable = new BABYLON.Observable();
  50752. /**
  50753. * An event triggered when the texture is unbind.
  50754. * @type {BABYLON.Observable}
  50755. */
  50756. _this.onAfterUnbindObservable = new BABYLON.Observable();
  50757. /**
  50758. * An event triggered before rendering the texture
  50759. * @type {BABYLON.Observable}
  50760. */
  50761. _this.onBeforeRenderObservable = new BABYLON.Observable();
  50762. /**
  50763. * An event triggered after rendering the texture
  50764. * @type {BABYLON.Observable}
  50765. */
  50766. _this.onAfterRenderObservable = new BABYLON.Observable();
  50767. /**
  50768. * An event triggered after the texture clear
  50769. * @type {BABYLON.Observable}
  50770. */
  50771. _this.onClearObservable = new BABYLON.Observable();
  50772. _this._currentRefreshId = -1;
  50773. _this._refreshRate = 1;
  50774. _this._samples = 1;
  50775. scene = _this.getScene();
  50776. if (!scene) {
  50777. return _this;
  50778. }
  50779. _this._engine = scene.getEngine();
  50780. _this.name = name;
  50781. _this.isRenderTarget = true;
  50782. _this._initialSizeParameter = size;
  50783. _this._processSizeParameter(size);
  50784. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  50785. });
  50786. _this._generateMipMaps = generateMipMaps ? true : false;
  50787. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  50788. // Rendering groups
  50789. _this._renderingManager = new BABYLON.RenderingManager(scene);
  50790. if (isMulti) {
  50791. return _this;
  50792. }
  50793. _this._renderTargetOptions = {
  50794. generateMipMaps: generateMipMaps,
  50795. type: type,
  50796. samplingMode: samplingMode,
  50797. generateDepthBuffer: generateDepthBuffer,
  50798. generateStencilBuffer: generateStencilBuffer
  50799. };
  50800. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  50801. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50802. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50803. }
  50804. if (isCube) {
  50805. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  50806. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  50807. _this._textureMatrix = BABYLON.Matrix.Identity();
  50808. }
  50809. else {
  50810. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  50811. }
  50812. return _this;
  50813. }
  50814. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  50815. get: function () {
  50816. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  50817. },
  50818. enumerable: true,
  50819. configurable: true
  50820. });
  50821. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  50822. get: function () {
  50823. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  50824. },
  50825. enumerable: true,
  50826. configurable: true
  50827. });
  50828. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  50829. get: function () {
  50830. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  50831. },
  50832. enumerable: true,
  50833. configurable: true
  50834. });
  50835. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  50836. set: function (callback) {
  50837. if (this._onAfterUnbindObserver) {
  50838. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  50839. }
  50840. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  50841. },
  50842. enumerable: true,
  50843. configurable: true
  50844. });
  50845. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  50846. set: function (callback) {
  50847. if (this._onBeforeRenderObserver) {
  50848. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  50849. }
  50850. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  50851. },
  50852. enumerable: true,
  50853. configurable: true
  50854. });
  50855. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  50856. set: function (callback) {
  50857. if (this._onAfterRenderObserver) {
  50858. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  50859. }
  50860. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  50861. },
  50862. enumerable: true,
  50863. configurable: true
  50864. });
  50865. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  50866. set: function (callback) {
  50867. if (this._onClearObserver) {
  50868. this.onClearObservable.remove(this._onClearObserver);
  50869. }
  50870. this._onClearObserver = this.onClearObservable.add(callback);
  50871. },
  50872. enumerable: true,
  50873. configurable: true
  50874. });
  50875. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  50876. get: function () {
  50877. return this._renderTargetOptions;
  50878. },
  50879. enumerable: true,
  50880. configurable: true
  50881. });
  50882. RenderTargetTexture.prototype._onRatioRescale = function () {
  50883. if (this._sizeRatio) {
  50884. this.resize(this._initialSizeParameter);
  50885. }
  50886. };
  50887. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  50888. if (size.ratio) {
  50889. this._sizeRatio = size.ratio;
  50890. this._size = {
  50891. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  50892. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  50893. };
  50894. }
  50895. else {
  50896. this._size = size;
  50897. }
  50898. };
  50899. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  50900. get: function () {
  50901. return this._samples;
  50902. },
  50903. set: function (value) {
  50904. if (this._samples === value) {
  50905. return;
  50906. }
  50907. var scene = this.getScene();
  50908. if (!scene) {
  50909. return;
  50910. }
  50911. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  50912. },
  50913. enumerable: true,
  50914. configurable: true
  50915. });
  50916. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  50917. this._currentRefreshId = -1;
  50918. };
  50919. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  50920. get: function () {
  50921. return this._refreshRate;
  50922. },
  50923. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  50924. set: function (value) {
  50925. this._refreshRate = value;
  50926. this.resetRefreshCounter();
  50927. },
  50928. enumerable: true,
  50929. configurable: true
  50930. });
  50931. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  50932. if (!this._postProcessManager) {
  50933. var scene = this.getScene();
  50934. if (!scene) {
  50935. return;
  50936. }
  50937. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  50938. this._postProcesses = new Array();
  50939. }
  50940. this._postProcesses.push(postProcess);
  50941. this._postProcesses[0].autoClear = false;
  50942. };
  50943. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  50944. if (!this._postProcesses) {
  50945. return;
  50946. }
  50947. if (dispose) {
  50948. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  50949. var postProcess = _a[_i];
  50950. postProcess.dispose();
  50951. }
  50952. }
  50953. this._postProcesses = [];
  50954. };
  50955. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  50956. if (!this._postProcesses) {
  50957. return;
  50958. }
  50959. var index = this._postProcesses.indexOf(postProcess);
  50960. if (index === -1) {
  50961. return;
  50962. }
  50963. this._postProcesses.splice(index, 1);
  50964. if (this._postProcesses.length > 0) {
  50965. this._postProcesses[0].autoClear = false;
  50966. }
  50967. };
  50968. RenderTargetTexture.prototype._shouldRender = function () {
  50969. if (this._currentRefreshId === -1) {
  50970. this._currentRefreshId = 1;
  50971. return true;
  50972. }
  50973. if (this.refreshRate === this._currentRefreshId) {
  50974. this._currentRefreshId = 1;
  50975. return true;
  50976. }
  50977. this._currentRefreshId++;
  50978. return false;
  50979. };
  50980. RenderTargetTexture.prototype.getRenderSize = function () {
  50981. if (this._size.width) {
  50982. return this._size.width;
  50983. }
  50984. return this._size;
  50985. };
  50986. RenderTargetTexture.prototype.getRenderWidth = function () {
  50987. if (this._size.width) {
  50988. return this._size.width;
  50989. }
  50990. return this._size;
  50991. };
  50992. RenderTargetTexture.prototype.getRenderHeight = function () {
  50993. if (this._size.width) {
  50994. return this._size.height;
  50995. }
  50996. return this._size;
  50997. };
  50998. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  50999. get: function () {
  51000. return true;
  51001. },
  51002. enumerable: true,
  51003. configurable: true
  51004. });
  51005. RenderTargetTexture.prototype.scale = function (ratio) {
  51006. var newSize = this.getRenderSize() * ratio;
  51007. this.resize(newSize);
  51008. };
  51009. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  51010. if (this.isCube) {
  51011. return this._textureMatrix;
  51012. }
  51013. return _super.prototype.getReflectionTextureMatrix.call(this);
  51014. };
  51015. RenderTargetTexture.prototype.resize = function (size) {
  51016. this.releaseInternalTexture();
  51017. var scene = this.getScene();
  51018. if (!scene) {
  51019. return;
  51020. }
  51021. this._processSizeParameter(size);
  51022. if (this.isCube) {
  51023. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  51024. }
  51025. else {
  51026. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  51027. }
  51028. };
  51029. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  51030. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  51031. if (dumpForDebug === void 0) { dumpForDebug = false; }
  51032. var scene = this.getScene();
  51033. if (!scene) {
  51034. return;
  51035. }
  51036. var engine = scene.getEngine();
  51037. if (this.useCameraPostProcesses !== undefined) {
  51038. useCameraPostProcess = this.useCameraPostProcesses;
  51039. }
  51040. if (this._waitingRenderList) {
  51041. this.renderList = [];
  51042. for (var index = 0; index < this._waitingRenderList.length; index++) {
  51043. var id = this._waitingRenderList[index];
  51044. var mesh_1 = scene.getMeshByID(id);
  51045. if (mesh_1) {
  51046. this.renderList.push(mesh_1);
  51047. }
  51048. }
  51049. delete this._waitingRenderList;
  51050. }
  51051. // Is predicate defined?
  51052. if (this.renderListPredicate) {
  51053. if (this.renderList) {
  51054. this.renderList.splice(0); // Clear previous renderList
  51055. }
  51056. else {
  51057. this.renderList = [];
  51058. }
  51059. var scene = this.getScene();
  51060. if (!scene) {
  51061. return;
  51062. }
  51063. var sceneMeshes = scene.meshes;
  51064. for (var index = 0; index < sceneMeshes.length; index++) {
  51065. var mesh = sceneMeshes[index];
  51066. if (this.renderListPredicate(mesh)) {
  51067. this.renderList.push(mesh);
  51068. }
  51069. }
  51070. }
  51071. this.onBeforeBindObservable.notifyObservers(this);
  51072. // Set custom projection.
  51073. // Needs to be before binding to prevent changing the aspect ratio.
  51074. var camera;
  51075. if (this.activeCamera) {
  51076. camera = this.activeCamera;
  51077. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  51078. if (this.activeCamera !== scene.activeCamera) {
  51079. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  51080. }
  51081. }
  51082. else {
  51083. camera = scene.activeCamera;
  51084. if (camera) {
  51085. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  51086. }
  51087. }
  51088. // Prepare renderingManager
  51089. this._renderingManager.reset();
  51090. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  51091. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  51092. var sceneRenderId = scene.getRenderId();
  51093. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  51094. var mesh = currentRenderList[meshIndex];
  51095. if (mesh) {
  51096. if (!mesh.isReady()) {
  51097. // Reset _currentRefreshId
  51098. this.resetRefreshCounter();
  51099. continue;
  51100. }
  51101. mesh._preActivateForIntermediateRendering(sceneRenderId);
  51102. var isMasked = void 0;
  51103. if (!this.renderList && camera) {
  51104. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  51105. }
  51106. else {
  51107. isMasked = false;
  51108. }
  51109. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  51110. mesh._activate(sceneRenderId);
  51111. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  51112. var subMesh = mesh.subMeshes[subIndex];
  51113. scene._activeIndices.addCount(subMesh.indexCount, false);
  51114. this._renderingManager.dispatch(subMesh);
  51115. }
  51116. }
  51117. }
  51118. }
  51119. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  51120. var particleSystem = scene.particleSystems[particleIndex];
  51121. var emitter = particleSystem.emitter;
  51122. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  51123. continue;
  51124. }
  51125. if (currentRenderList.indexOf(emitter) >= 0) {
  51126. this._renderingManager.dispatchParticles(particleSystem);
  51127. }
  51128. }
  51129. if (this.isCube) {
  51130. for (var face = 0; face < 6; face++) {
  51131. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  51132. scene.incrementRenderId();
  51133. scene.resetCachedMaterial();
  51134. }
  51135. }
  51136. else {
  51137. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  51138. }
  51139. this.onAfterUnbindObservable.notifyObservers(this);
  51140. if (scene.activeCamera) {
  51141. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  51142. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  51143. }
  51144. engine.setViewport(scene.activeCamera.viewport);
  51145. }
  51146. scene.resetCachedMaterial();
  51147. };
  51148. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  51149. var minimum = 128;
  51150. var x = renderDimension * scale;
  51151. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  51152. // Ensure we don't exceed the render dimension (while staying POT)
  51153. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  51154. };
  51155. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  51156. var _this = this;
  51157. var scene = this.getScene();
  51158. if (!scene) {
  51159. return;
  51160. }
  51161. var engine = scene.getEngine();
  51162. if (!this._texture) {
  51163. return;
  51164. }
  51165. // Bind
  51166. if (this._postProcessManager) {
  51167. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  51168. }
  51169. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  51170. if (this._texture) {
  51171. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  51172. }
  51173. }
  51174. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  51175. // Clear
  51176. if (this.onClearObservable.hasObservers()) {
  51177. this.onClearObservable.notifyObservers(engine);
  51178. }
  51179. else {
  51180. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  51181. }
  51182. if (!this._doNotChangeAspectRatio) {
  51183. scene.updateTransformMatrix(true);
  51184. }
  51185. // Render
  51186. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  51187. if (this._postProcessManager) {
  51188. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  51189. }
  51190. else if (useCameraPostProcess) {
  51191. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  51192. }
  51193. if (!this._doNotChangeAspectRatio) {
  51194. scene.updateTransformMatrix(true);
  51195. }
  51196. // Dump ?
  51197. if (dumpForDebug) {
  51198. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  51199. }
  51200. // Unbind
  51201. if (!this.isCube || faceIndex === 5) {
  51202. if (this.isCube) {
  51203. if (faceIndex === 5) {
  51204. engine.generateMipMapsForCubemap(this._texture);
  51205. }
  51206. }
  51207. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  51208. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  51209. });
  51210. }
  51211. else {
  51212. this.onAfterRenderObservable.notifyObservers(faceIndex);
  51213. }
  51214. };
  51215. /**
  51216. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  51217. * This allowed control for front to back rendering or reversly depending of the special needs.
  51218. *
  51219. * @param renderingGroupId The rendering group id corresponding to its index
  51220. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  51221. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  51222. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  51223. */
  51224. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  51225. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  51226. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  51227. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  51228. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  51229. };
  51230. /**
  51231. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  51232. *
  51233. * @param renderingGroupId The rendering group id corresponding to its index
  51234. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  51235. */
  51236. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  51237. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  51238. };
  51239. RenderTargetTexture.prototype.clone = function () {
  51240. var textureSize = this.getSize();
  51241. 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);
  51242. // Base texture
  51243. newTexture.hasAlpha = this.hasAlpha;
  51244. newTexture.level = this.level;
  51245. // RenderTarget Texture
  51246. newTexture.coordinatesMode = this.coordinatesMode;
  51247. if (this.renderList) {
  51248. newTexture.renderList = this.renderList.slice(0);
  51249. }
  51250. return newTexture;
  51251. };
  51252. RenderTargetTexture.prototype.serialize = function () {
  51253. if (!this.name) {
  51254. return null;
  51255. }
  51256. var serializationObject = _super.prototype.serialize.call(this);
  51257. serializationObject.renderTargetSize = this.getRenderSize();
  51258. serializationObject.renderList = [];
  51259. if (this.renderList) {
  51260. for (var index = 0; index < this.renderList.length; index++) {
  51261. serializationObject.renderList.push(this.renderList[index].id);
  51262. }
  51263. }
  51264. return serializationObject;
  51265. };
  51266. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  51267. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  51268. var objBuffer = this.getInternalTexture();
  51269. var scene = this.getScene();
  51270. if (objBuffer && scene) {
  51271. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  51272. }
  51273. };
  51274. RenderTargetTexture.prototype.dispose = function () {
  51275. if (this._postProcessManager) {
  51276. this._postProcessManager.dispose();
  51277. this._postProcessManager = null;
  51278. }
  51279. this.clearPostProcesses(true);
  51280. if (this._resizeObserver) {
  51281. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  51282. this._resizeObserver = null;
  51283. }
  51284. this.renderList = null;
  51285. // Remove from custom render targets
  51286. var scene = this.getScene();
  51287. if (!scene) {
  51288. return;
  51289. }
  51290. var index = scene.customRenderTargets.indexOf(this);
  51291. if (index >= 0) {
  51292. scene.customRenderTargets.splice(index, 1);
  51293. }
  51294. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  51295. var camera = _a[_i];
  51296. index = camera.customRenderTargets.indexOf(this);
  51297. if (index >= 0) {
  51298. camera.customRenderTargets.splice(index, 1);
  51299. }
  51300. }
  51301. _super.prototype.dispose.call(this);
  51302. };
  51303. RenderTargetTexture.prototype._rebuild = function () {
  51304. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  51305. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  51306. }
  51307. if (this._postProcessManager) {
  51308. this._postProcessManager._rebuild();
  51309. }
  51310. };
  51311. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  51312. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  51313. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  51314. return RenderTargetTexture;
  51315. }(BABYLON.Texture));
  51316. BABYLON.RenderTargetTexture = RenderTargetTexture;
  51317. })(BABYLON || (BABYLON = {}));
  51318. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  51319. var BABYLON;
  51320. (function (BABYLON) {
  51321. ;
  51322. var MultiRenderTarget = /** @class */ (function (_super) {
  51323. __extends(MultiRenderTarget, _super);
  51324. function MultiRenderTarget(name, size, count, scene, options) {
  51325. var _this = this;
  51326. options = options || {};
  51327. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  51328. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  51329. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  51330. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  51331. _this._engine = scene.getEngine();
  51332. if (!_this.isSupported) {
  51333. _this.dispose();
  51334. return;
  51335. }
  51336. var types = [];
  51337. var samplingModes = [];
  51338. for (var i = 0; i < count; i++) {
  51339. if (options.types && options.types[i]) {
  51340. types.push(options.types[i]);
  51341. }
  51342. else {
  51343. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  51344. }
  51345. if (options.samplingModes && options.samplingModes[i]) {
  51346. samplingModes.push(options.samplingModes[i]);
  51347. }
  51348. else {
  51349. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51350. }
  51351. }
  51352. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  51353. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  51354. _this._size = size;
  51355. _this._multiRenderTargetOptions = {
  51356. samplingModes: samplingModes,
  51357. generateMipMaps: generateMipMaps,
  51358. generateDepthBuffer: generateDepthBuffer,
  51359. generateStencilBuffer: generateStencilBuffer,
  51360. generateDepthTexture: generateDepthTexture,
  51361. types: types,
  51362. textureCount: count
  51363. };
  51364. _this._createInternalTextures();
  51365. _this._createTextures();
  51366. return _this;
  51367. }
  51368. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  51369. get: function () {
  51370. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  51371. },
  51372. enumerable: true,
  51373. configurable: true
  51374. });
  51375. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  51376. get: function () {
  51377. return this._textures;
  51378. },
  51379. enumerable: true,
  51380. configurable: true
  51381. });
  51382. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  51383. get: function () {
  51384. return this._textures[this._textures.length - 1];
  51385. },
  51386. enumerable: true,
  51387. configurable: true
  51388. });
  51389. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  51390. set: function (wrap) {
  51391. if (this._textures) {
  51392. for (var i = 0; i < this._textures.length; i++) {
  51393. this._textures[i].wrapU = wrap;
  51394. }
  51395. }
  51396. },
  51397. enumerable: true,
  51398. configurable: true
  51399. });
  51400. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  51401. set: function (wrap) {
  51402. if (this._textures) {
  51403. for (var i = 0; i < this._textures.length; i++) {
  51404. this._textures[i].wrapV = wrap;
  51405. }
  51406. }
  51407. },
  51408. enumerable: true,
  51409. configurable: true
  51410. });
  51411. MultiRenderTarget.prototype._rebuild = function () {
  51412. this.releaseInternalTextures();
  51413. this._createInternalTextures();
  51414. for (var i = 0; i < this._internalTextures.length; i++) {
  51415. var texture = this._textures[i];
  51416. texture._texture = this._internalTextures[i];
  51417. }
  51418. // Keeps references to frame buffer and stencil/depth buffer
  51419. this._texture = this._internalTextures[0];
  51420. };
  51421. MultiRenderTarget.prototype._createInternalTextures = function () {
  51422. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  51423. };
  51424. MultiRenderTarget.prototype._createTextures = function () {
  51425. this._textures = [];
  51426. for (var i = 0; i < this._internalTextures.length; i++) {
  51427. var texture = new BABYLON.Texture(null, this.getScene());
  51428. texture._texture = this._internalTextures[i];
  51429. this._textures.push(texture);
  51430. }
  51431. // Keeps references to frame buffer and stencil/depth buffer
  51432. this._texture = this._internalTextures[0];
  51433. };
  51434. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  51435. get: function () {
  51436. return this._samples;
  51437. },
  51438. set: function (value) {
  51439. if (this._samples === value) {
  51440. return;
  51441. }
  51442. for (var i = 0; i < this._internalTextures.length; i++) {
  51443. this._samples = this._engine.updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  51444. }
  51445. },
  51446. enumerable: true,
  51447. configurable: true
  51448. });
  51449. MultiRenderTarget.prototype.resize = function (size) {
  51450. this.releaseInternalTextures();
  51451. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  51452. this._createInternalTextures();
  51453. };
  51454. MultiRenderTarget.prototype.dispose = function () {
  51455. this.releaseInternalTextures();
  51456. _super.prototype.dispose.call(this);
  51457. };
  51458. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  51459. if (!this._internalTextures) {
  51460. return;
  51461. }
  51462. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  51463. if (this._internalTextures[i] !== undefined) {
  51464. this._internalTextures[i].dispose();
  51465. this._internalTextures.splice(i, 1);
  51466. }
  51467. }
  51468. };
  51469. return MultiRenderTarget;
  51470. }(BABYLON.RenderTargetTexture));
  51471. BABYLON.MultiRenderTarget = MultiRenderTarget;
  51472. })(BABYLON || (BABYLON = {}));
  51473. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  51474. var BABYLON;
  51475. (function (BABYLON) {
  51476. var MirrorTexture = /** @class */ (function (_super) {
  51477. __extends(MirrorTexture, _super);
  51478. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  51479. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51480. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  51481. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  51482. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  51483. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  51484. _this._transformMatrix = BABYLON.Matrix.Zero();
  51485. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  51486. _this._adaptiveBlurKernel = 0;
  51487. _this._blurKernelX = 0;
  51488. _this._blurKernelY = 0;
  51489. _this._blurRatio = 1.0;
  51490. _this.ignoreCameraViewport = true;
  51491. _this.onBeforeRenderObservable.add(function () {
  51492. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  51493. _this._savedViewMatrix = scene.getViewMatrix();
  51494. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  51495. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  51496. scene.clipPlane = _this.mirrorPlane;
  51497. scene.getEngine().cullBackFaces = false;
  51498. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  51499. });
  51500. _this.onAfterRenderObservable.add(function () {
  51501. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  51502. scene.getEngine().cullBackFaces = true;
  51503. scene._mirroredCameraPosition = null;
  51504. delete scene.clipPlane;
  51505. });
  51506. return _this;
  51507. }
  51508. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  51509. get: function () {
  51510. return this._blurRatio;
  51511. },
  51512. set: function (value) {
  51513. if (this._blurRatio === value) {
  51514. return;
  51515. }
  51516. this._blurRatio = value;
  51517. this._preparePostProcesses();
  51518. },
  51519. enumerable: true,
  51520. configurable: true
  51521. });
  51522. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  51523. set: function (value) {
  51524. this._adaptiveBlurKernel = value;
  51525. this._autoComputeBlurKernel();
  51526. },
  51527. enumerable: true,
  51528. configurable: true
  51529. });
  51530. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  51531. set: function (value) {
  51532. this.blurKernelX = value;
  51533. this.blurKernelY = value;
  51534. },
  51535. enumerable: true,
  51536. configurable: true
  51537. });
  51538. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  51539. get: function () {
  51540. return this._blurKernelX;
  51541. },
  51542. set: function (value) {
  51543. if (this._blurKernelX === value) {
  51544. return;
  51545. }
  51546. this._blurKernelX = value;
  51547. this._preparePostProcesses();
  51548. },
  51549. enumerable: true,
  51550. configurable: true
  51551. });
  51552. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  51553. get: function () {
  51554. return this._blurKernelY;
  51555. },
  51556. set: function (value) {
  51557. if (this._blurKernelY === value) {
  51558. return;
  51559. }
  51560. this._blurKernelY = value;
  51561. this._preparePostProcesses();
  51562. },
  51563. enumerable: true,
  51564. configurable: true
  51565. });
  51566. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  51567. var engine = this.getScene().getEngine();
  51568. var dw = this.getRenderWidth() / engine.getRenderWidth();
  51569. var dh = this.getRenderHeight() / engine.getRenderHeight();
  51570. this.blurKernelX = this._adaptiveBlurKernel * dw;
  51571. this.blurKernelY = this._adaptiveBlurKernel * dh;
  51572. };
  51573. MirrorTexture.prototype._onRatioRescale = function () {
  51574. if (this._sizeRatio) {
  51575. this.resize(this._initialSizeParameter);
  51576. if (!this._adaptiveBlurKernel) {
  51577. this._preparePostProcesses();
  51578. }
  51579. }
  51580. if (this._adaptiveBlurKernel) {
  51581. this._autoComputeBlurKernel();
  51582. }
  51583. };
  51584. MirrorTexture.prototype._preparePostProcesses = function () {
  51585. this.clearPostProcesses(true);
  51586. if (this._blurKernelX && this._blurKernelY) {
  51587. var engine = this.getScene().getEngine();
  51588. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  51589. 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);
  51590. this._blurX.autoClear = false;
  51591. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  51592. this._blurX.outputTexture = this._texture;
  51593. }
  51594. else {
  51595. this._blurX.alwaysForcePOT = true;
  51596. }
  51597. 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);
  51598. this._blurY.autoClear = false;
  51599. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  51600. this.addPostProcess(this._blurX);
  51601. this.addPostProcess(this._blurY);
  51602. }
  51603. else {
  51604. if (this._blurY) {
  51605. this.removePostProcess(this._blurY);
  51606. this._blurY.dispose();
  51607. this._blurY = null;
  51608. }
  51609. if (this._blurX) {
  51610. this.removePostProcess(this._blurX);
  51611. this._blurX.dispose();
  51612. this._blurX = null;
  51613. }
  51614. }
  51615. };
  51616. MirrorTexture.prototype.clone = function () {
  51617. var scene = this.getScene();
  51618. if (!scene) {
  51619. return this;
  51620. }
  51621. var textureSize = this.getSize();
  51622. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  51623. // Base texture
  51624. newTexture.hasAlpha = this.hasAlpha;
  51625. newTexture.level = this.level;
  51626. // Mirror Texture
  51627. newTexture.mirrorPlane = this.mirrorPlane.clone();
  51628. if (this.renderList) {
  51629. newTexture.renderList = this.renderList.slice(0);
  51630. }
  51631. return newTexture;
  51632. };
  51633. MirrorTexture.prototype.serialize = function () {
  51634. if (!this.name) {
  51635. return null;
  51636. }
  51637. var serializationObject = _super.prototype.serialize.call(this);
  51638. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  51639. return serializationObject;
  51640. };
  51641. return MirrorTexture;
  51642. }(BABYLON.RenderTargetTexture));
  51643. BABYLON.MirrorTexture = MirrorTexture;
  51644. })(BABYLON || (BABYLON = {}));
  51645. //# sourceMappingURL=babylon.mirrorTexture.js.map
  51646. var BABYLON;
  51647. (function (BABYLON) {
  51648. /**
  51649. * Creates a refraction texture used by refraction channel of the standard material.
  51650. * @param name the texture name
  51651. * @param size size of the underlying texture
  51652. * @param scene root scene
  51653. */
  51654. var RefractionTexture = /** @class */ (function (_super) {
  51655. __extends(RefractionTexture, _super);
  51656. function RefractionTexture(name, size, scene, generateMipMaps) {
  51657. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  51658. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  51659. _this.depth = 2.0;
  51660. _this.onBeforeRenderObservable.add(function () {
  51661. scene.clipPlane = _this.refractionPlane;
  51662. });
  51663. _this.onAfterRenderObservable.add(function () {
  51664. delete scene.clipPlane;
  51665. });
  51666. return _this;
  51667. }
  51668. RefractionTexture.prototype.clone = function () {
  51669. var scene = this.getScene();
  51670. if (!scene) {
  51671. return this;
  51672. }
  51673. var textureSize = this.getSize();
  51674. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  51675. // Base texture
  51676. newTexture.hasAlpha = this.hasAlpha;
  51677. newTexture.level = this.level;
  51678. // Refraction Texture
  51679. newTexture.refractionPlane = this.refractionPlane.clone();
  51680. if (this.renderList) {
  51681. newTexture.renderList = this.renderList.slice(0);
  51682. }
  51683. newTexture.depth = this.depth;
  51684. return newTexture;
  51685. };
  51686. RefractionTexture.prototype.serialize = function () {
  51687. if (!this.name) {
  51688. return null;
  51689. }
  51690. var serializationObject = _super.prototype.serialize.call(this);
  51691. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  51692. serializationObject.depth = this.depth;
  51693. return serializationObject;
  51694. };
  51695. return RefractionTexture;
  51696. }(BABYLON.RenderTargetTexture));
  51697. BABYLON.RefractionTexture = RefractionTexture;
  51698. })(BABYLON || (BABYLON = {}));
  51699. //# sourceMappingURL=babylon.refractionTexture.js.map
  51700. var BABYLON;
  51701. (function (BABYLON) {
  51702. var DynamicTexture = /** @class */ (function (_super) {
  51703. __extends(DynamicTexture, _super);
  51704. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  51705. if (scene === void 0) { scene = null; }
  51706. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51707. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  51708. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  51709. _this.name = name;
  51710. _this._engine = _this.getScene().getEngine();
  51711. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51712. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51713. _this._generateMipMaps = generateMipMaps;
  51714. if (options.getContext) {
  51715. _this._canvas = options;
  51716. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  51717. }
  51718. else {
  51719. _this._canvas = document.createElement("canvas");
  51720. if (options.width) {
  51721. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  51722. }
  51723. else {
  51724. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  51725. }
  51726. }
  51727. var textureSize = _this.getSize();
  51728. _this._canvas.width = textureSize.width;
  51729. _this._canvas.height = textureSize.height;
  51730. _this._context = _this._canvas.getContext("2d");
  51731. return _this;
  51732. }
  51733. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  51734. get: function () {
  51735. return true;
  51736. },
  51737. enumerable: true,
  51738. configurable: true
  51739. });
  51740. DynamicTexture.prototype._recreate = function (textureSize) {
  51741. this._canvas.width = textureSize.width;
  51742. this._canvas.height = textureSize.height;
  51743. this.releaseInternalTexture();
  51744. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  51745. };
  51746. DynamicTexture.prototype.scale = function (ratio) {
  51747. var textureSize = this.getSize();
  51748. textureSize.width *= ratio;
  51749. textureSize.height *= ratio;
  51750. this._recreate(textureSize);
  51751. };
  51752. DynamicTexture.prototype.scaleTo = function (width, height) {
  51753. var textureSize = this.getSize();
  51754. textureSize.width = width;
  51755. textureSize.height = height;
  51756. this._recreate(textureSize);
  51757. };
  51758. DynamicTexture.prototype.getContext = function () {
  51759. return this._context;
  51760. };
  51761. DynamicTexture.prototype.clear = function () {
  51762. var size = this.getSize();
  51763. this._context.fillRect(0, 0, size.width, size.height);
  51764. };
  51765. DynamicTexture.prototype.update = function (invertY) {
  51766. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  51767. };
  51768. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  51769. if (update === void 0) { update = true; }
  51770. var size = this.getSize();
  51771. if (clearColor) {
  51772. this._context.fillStyle = clearColor;
  51773. this._context.fillRect(0, 0, size.width, size.height);
  51774. }
  51775. this._context.font = font;
  51776. if (x === null || x === undefined) {
  51777. var textSize = this._context.measureText(text);
  51778. x = (size.width - textSize.width) / 2;
  51779. }
  51780. if (y === null || y === undefined) {
  51781. var fontSize = parseInt((font.replace(/\D/g, '')));
  51782. ;
  51783. y = (size.height / 2) + (fontSize / 3.65);
  51784. }
  51785. this._context.fillStyle = color;
  51786. this._context.fillText(text, x, y);
  51787. if (update) {
  51788. this.update(invertY);
  51789. }
  51790. };
  51791. DynamicTexture.prototype.clone = function () {
  51792. var scene = this.getScene();
  51793. if (!scene) {
  51794. return this;
  51795. }
  51796. var textureSize = this.getSize();
  51797. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  51798. // Base texture
  51799. newTexture.hasAlpha = this.hasAlpha;
  51800. newTexture.level = this.level;
  51801. // Dynamic Texture
  51802. newTexture.wrapU = this.wrapU;
  51803. newTexture.wrapV = this.wrapV;
  51804. return newTexture;
  51805. };
  51806. DynamicTexture.prototype._rebuild = function () {
  51807. this.update();
  51808. };
  51809. return DynamicTexture;
  51810. }(BABYLON.Texture));
  51811. BABYLON.DynamicTexture = DynamicTexture;
  51812. })(BABYLON || (BABYLON = {}));
  51813. //# sourceMappingURL=babylon.dynamicTexture.js.map
  51814. var BABYLON;
  51815. (function (BABYLON) {
  51816. var VideoTexture = /** @class */ (function (_super) {
  51817. __extends(VideoTexture, _super);
  51818. /**
  51819. * Creates a video texture.
  51820. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  51821. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  51822. * @param {BABYLON.Scene} scene is obviously the current scene.
  51823. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  51824. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  51825. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  51826. */
  51827. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  51828. if (generateMipMaps === void 0) { generateMipMaps = false; }
  51829. if (invertY === void 0) { invertY = false; }
  51830. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51831. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  51832. _this._autoLaunch = true;
  51833. var urls = null;
  51834. _this.name = name;
  51835. if (urlsOrVideo instanceof HTMLVideoElement) {
  51836. _this.video = urlsOrVideo;
  51837. }
  51838. else {
  51839. urls = urlsOrVideo;
  51840. _this.video = document.createElement("video");
  51841. _this.video.autoplay = false;
  51842. _this.video.loop = true;
  51843. BABYLON.Tools.SetCorsBehavior(urls, _this.video);
  51844. }
  51845. _this._engine = _this.getScene().getEngine();
  51846. _this._generateMipMaps = generateMipMaps;
  51847. _this._samplingMode = samplingMode;
  51848. if (!_this._engine.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  51849. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  51850. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  51851. }
  51852. else {
  51853. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51854. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51855. _this._generateMipMaps = false;
  51856. }
  51857. if (urls) {
  51858. _this.video.addEventListener("canplay", function () {
  51859. if (_this._texture === undefined) {
  51860. _this._createTexture();
  51861. }
  51862. });
  51863. urls.forEach(function (url) {
  51864. var source = document.createElement("source");
  51865. source.src = url;
  51866. _this.video.appendChild(source);
  51867. });
  51868. }
  51869. else {
  51870. _this._createTexture();
  51871. }
  51872. _this._lastUpdate = BABYLON.Tools.Now;
  51873. return _this;
  51874. }
  51875. VideoTexture.prototype.__setTextureReady = function () {
  51876. if (this._texture) {
  51877. this._texture.isReady = true;
  51878. }
  51879. };
  51880. VideoTexture.prototype._createTexture = function () {
  51881. this._texture = this._engine.createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  51882. if (this._autoLaunch) {
  51883. this._autoLaunch = false;
  51884. this.video.play();
  51885. }
  51886. this._setTextureReady = this.__setTextureReady.bind(this);
  51887. this.video.addEventListener("playing", this._setTextureReady);
  51888. };
  51889. VideoTexture.prototype._rebuild = function () {
  51890. this.update();
  51891. };
  51892. VideoTexture.prototype.update = function () {
  51893. var now = BABYLON.Tools.Now;
  51894. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  51895. return false;
  51896. }
  51897. this._lastUpdate = now;
  51898. this._engine.updateVideoTexture(this._texture, this.video, this._invertY);
  51899. return true;
  51900. };
  51901. VideoTexture.prototype.dispose = function () {
  51902. _super.prototype.dispose.call(this);
  51903. this.video.removeEventListener("playing", this._setTextureReady);
  51904. };
  51905. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  51906. var video = document.createElement("video");
  51907. var constraintsDeviceId;
  51908. if (constraints && constraints.deviceId) {
  51909. constraintsDeviceId = {
  51910. exact: constraints.deviceId
  51911. };
  51912. }
  51913. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  51914. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  51915. if (navigator.getUserMedia) {
  51916. navigator.getUserMedia({
  51917. video: {
  51918. deviceId: constraintsDeviceId,
  51919. width: {
  51920. min: (constraints && constraints.minWidth) || 256,
  51921. max: (constraints && constraints.maxWidth) || 640
  51922. },
  51923. height: {
  51924. min: (constraints && constraints.minHeight) || 256,
  51925. max: (constraints && constraints.maxHeight) || 480
  51926. }
  51927. }
  51928. }, function (stream) {
  51929. if (video.mozSrcObject !== undefined) {
  51930. video.mozSrcObject = stream;
  51931. }
  51932. else {
  51933. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  51934. }
  51935. video.play();
  51936. if (onReady) {
  51937. onReady(new VideoTexture("video", video, scene, true, true));
  51938. }
  51939. }, function (e) {
  51940. BABYLON.Tools.Error(e.name);
  51941. });
  51942. }
  51943. };
  51944. return VideoTexture;
  51945. }(BABYLON.Texture));
  51946. BABYLON.VideoTexture = VideoTexture;
  51947. })(BABYLON || (BABYLON = {}));
  51948. //# sourceMappingURL=babylon.videoTexture.js.map
  51949. var BABYLON;
  51950. (function (BABYLON) {
  51951. var RawTexture = /** @class */ (function (_super) {
  51952. __extends(RawTexture, _super);
  51953. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  51954. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51955. if (invertY === void 0) { invertY = false; }
  51956. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51957. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51958. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  51959. _this.format = format;
  51960. _this._engine = scene.getEngine();
  51961. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  51962. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51963. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51964. return _this;
  51965. }
  51966. RawTexture.prototype.update = function (data) {
  51967. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  51968. };
  51969. // Statics
  51970. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51971. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51972. if (invertY === void 0) { invertY = false; }
  51973. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51974. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  51975. };
  51976. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51977. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51978. if (invertY === void 0) { invertY = false; }
  51979. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51980. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  51981. };
  51982. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51983. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51984. if (invertY === void 0) { invertY = false; }
  51985. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51986. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  51987. };
  51988. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  51989. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51990. if (invertY === void 0) { invertY = false; }
  51991. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51992. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51993. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  51994. };
  51995. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  51996. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51997. if (invertY === void 0) { invertY = false; }
  51998. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51999. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52000. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  52001. };
  52002. return RawTexture;
  52003. }(BABYLON.Texture));
  52004. BABYLON.RawTexture = RawTexture;
  52005. })(BABYLON || (BABYLON = {}));
  52006. //# sourceMappingURL=babylon.rawTexture.js.map
  52007. var BABYLON;
  52008. (function (BABYLON) {
  52009. var PostProcess = /** @class */ (function () {
  52010. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  52011. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  52012. if (defines === void 0) { defines = null; }
  52013. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52014. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  52015. if (blockCompilation === void 0) { blockCompilation = false; }
  52016. this.name = name;
  52017. this.width = -1;
  52018. this.height = -1;
  52019. this.autoClear = true;
  52020. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  52021. this.animations = new Array();
  52022. /*
  52023. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  52024. Can only be used on a single postprocess or on the last one of a chain.
  52025. */
  52026. this.enablePixelPerfectMode = false;
  52027. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  52028. this.alwaysForcePOT = false;
  52029. this.samples = 1;
  52030. this.adaptScaleToCurrentViewport = false;
  52031. this._reusable = false;
  52032. this._textures = new BABYLON.SmartArray(2);
  52033. this._currentRenderTextureInd = 0;
  52034. this._scaleRatio = new BABYLON.Vector2(1, 1);
  52035. this._texelSize = BABYLON.Vector2.Zero();
  52036. // Events
  52037. /**
  52038. * An event triggered when the postprocess is activated.
  52039. * @type {BABYLON.Observable}
  52040. */
  52041. this.onActivateObservable = new BABYLON.Observable();
  52042. /**
  52043. * An event triggered when the postprocess changes its size.
  52044. * @type {BABYLON.Observable}
  52045. */
  52046. this.onSizeChangedObservable = new BABYLON.Observable();
  52047. /**
  52048. * An event triggered when the postprocess applies its effect.
  52049. * @type {BABYLON.Observable}
  52050. */
  52051. this.onApplyObservable = new BABYLON.Observable();
  52052. /**
  52053. * An event triggered before rendering the postprocess
  52054. * @type {BABYLON.Observable}
  52055. */
  52056. this.onBeforeRenderObservable = new BABYLON.Observable();
  52057. /**
  52058. * An event triggered after rendering the postprocess
  52059. * @type {BABYLON.Observable}
  52060. */
  52061. this.onAfterRenderObservable = new BABYLON.Observable();
  52062. if (camera != null) {
  52063. this._camera = camera;
  52064. this._scene = camera.getScene();
  52065. camera.attachPostProcess(this);
  52066. this._engine = this._scene.getEngine();
  52067. this._scene.postProcesses.push(this);
  52068. }
  52069. else if (engine) {
  52070. this._engine = engine;
  52071. this._engine.postProcesses.push(this);
  52072. }
  52073. this._options = options;
  52074. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  52075. this._reusable = reusable || false;
  52076. this._textureType = textureType;
  52077. this._samplers = samplers || [];
  52078. this._samplers.push("textureSampler");
  52079. this._fragmentUrl = fragmentUrl;
  52080. this._vertexUrl = vertexUrl;
  52081. this._parameters = parameters || [];
  52082. this._parameters.push("scale");
  52083. this._indexParameters = indexParameters;
  52084. if (!blockCompilation) {
  52085. this.updateEffect(defines);
  52086. }
  52087. }
  52088. Object.defineProperty(PostProcess.prototype, "onActivate", {
  52089. set: function (callback) {
  52090. if (this._onActivateObserver) {
  52091. this.onActivateObservable.remove(this._onActivateObserver);
  52092. }
  52093. if (callback) {
  52094. this._onActivateObserver = this.onActivateObservable.add(callback);
  52095. }
  52096. },
  52097. enumerable: true,
  52098. configurable: true
  52099. });
  52100. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  52101. set: function (callback) {
  52102. if (this._onSizeChangedObserver) {
  52103. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  52104. }
  52105. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  52106. },
  52107. enumerable: true,
  52108. configurable: true
  52109. });
  52110. Object.defineProperty(PostProcess.prototype, "onApply", {
  52111. set: function (callback) {
  52112. if (this._onApplyObserver) {
  52113. this.onApplyObservable.remove(this._onApplyObserver);
  52114. }
  52115. this._onApplyObserver = this.onApplyObservable.add(callback);
  52116. },
  52117. enumerable: true,
  52118. configurable: true
  52119. });
  52120. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  52121. set: function (callback) {
  52122. if (this._onBeforeRenderObserver) {
  52123. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  52124. }
  52125. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  52126. },
  52127. enumerable: true,
  52128. configurable: true
  52129. });
  52130. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  52131. set: function (callback) {
  52132. if (this._onAfterRenderObserver) {
  52133. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  52134. }
  52135. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  52136. },
  52137. enumerable: true,
  52138. configurable: true
  52139. });
  52140. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  52141. get: function () {
  52142. return this._textures.data[this._currentRenderTextureInd];
  52143. },
  52144. set: function (value) {
  52145. this._forcedOutputTexture = value;
  52146. },
  52147. enumerable: true,
  52148. configurable: true
  52149. });
  52150. PostProcess.prototype.getCamera = function () {
  52151. return this._camera;
  52152. };
  52153. Object.defineProperty(PostProcess.prototype, "texelSize", {
  52154. get: function () {
  52155. if (this._shareOutputWithPostProcess) {
  52156. return this._shareOutputWithPostProcess.texelSize;
  52157. }
  52158. if (this._forcedOutputTexture) {
  52159. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  52160. }
  52161. return this._texelSize;
  52162. },
  52163. enumerable: true,
  52164. configurable: true
  52165. });
  52166. PostProcess.prototype.getEngine = function () {
  52167. return this._engine;
  52168. };
  52169. PostProcess.prototype.getEffect = function () {
  52170. return this._effect;
  52171. };
  52172. PostProcess.prototype.shareOutputWith = function (postProcess) {
  52173. this._disposeTextures();
  52174. this._shareOutputWithPostProcess = postProcess;
  52175. return this;
  52176. };
  52177. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  52178. if (defines === void 0) { defines = null; }
  52179. if (uniforms === void 0) { uniforms = null; }
  52180. if (samplers === void 0) { samplers = null; }
  52181. 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);
  52182. };
  52183. PostProcess.prototype.isReusable = function () {
  52184. return this._reusable;
  52185. };
  52186. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  52187. PostProcess.prototype.markTextureDirty = function () {
  52188. this.width = -1;
  52189. };
  52190. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  52191. var _this = this;
  52192. if (sourceTexture === void 0) { sourceTexture = null; }
  52193. camera = camera || this._camera;
  52194. var scene = camera.getScene();
  52195. var engine = scene.getEngine();
  52196. var maxSize = engine.getCaps().maxTextureSize;
  52197. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  52198. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  52199. var desiredWidth = (this._options.width || requiredWidth);
  52200. var desiredHeight = this._options.height || requiredHeight;
  52201. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  52202. if (this.adaptScaleToCurrentViewport) {
  52203. var currentViewport = engine.currentViewport;
  52204. if (currentViewport) {
  52205. desiredWidth *= currentViewport.width;
  52206. desiredHeight *= currentViewport.height;
  52207. }
  52208. }
  52209. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  52210. if (!this._options.width) {
  52211. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  52212. }
  52213. if (!this._options.height) {
  52214. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  52215. }
  52216. }
  52217. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  52218. if (this._textures.length > 0) {
  52219. for (var i = 0; i < this._textures.length; i++) {
  52220. this._engine._releaseTexture(this._textures.data[i]);
  52221. }
  52222. this._textures.reset();
  52223. }
  52224. this.width = desiredWidth;
  52225. this.height = desiredHeight;
  52226. var textureSize = { width: this.width, height: this.height };
  52227. var textureOptions = {
  52228. generateMipMaps: false,
  52229. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  52230. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  52231. samplingMode: this.renderTargetSamplingMode,
  52232. type: this._textureType
  52233. };
  52234. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  52235. if (this._reusable) {
  52236. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  52237. }
  52238. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  52239. this.onSizeChangedObservable.notifyObservers(this);
  52240. }
  52241. this._textures.forEach(function (texture) {
  52242. if (texture.samples !== _this.samples) {
  52243. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  52244. }
  52245. });
  52246. }
  52247. var target;
  52248. if (this._shareOutputWithPostProcess) {
  52249. target = this._shareOutputWithPostProcess.outputTexture;
  52250. }
  52251. else if (this._forcedOutputTexture) {
  52252. target = this._forcedOutputTexture;
  52253. this.width = this._forcedOutputTexture.width;
  52254. this.height = this._forcedOutputTexture.height;
  52255. }
  52256. else {
  52257. target = this.outputTexture;
  52258. }
  52259. if (this.enablePixelPerfectMode) {
  52260. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  52261. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  52262. }
  52263. else {
  52264. this._scaleRatio.copyFromFloats(1, 1);
  52265. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  52266. }
  52267. this.onActivateObservable.notifyObservers(camera);
  52268. // Clear
  52269. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  52270. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  52271. }
  52272. if (this._reusable) {
  52273. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  52274. }
  52275. };
  52276. Object.defineProperty(PostProcess.prototype, "isSupported", {
  52277. get: function () {
  52278. return this._effect.isSupported;
  52279. },
  52280. enumerable: true,
  52281. configurable: true
  52282. });
  52283. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  52284. get: function () {
  52285. if (this._shareOutputWithPostProcess) {
  52286. return this._shareOutputWithPostProcess.aspectRatio;
  52287. }
  52288. if (this._forcedOutputTexture) {
  52289. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  52290. }
  52291. return this.width / this.height;
  52292. },
  52293. enumerable: true,
  52294. configurable: true
  52295. });
  52296. PostProcess.prototype.apply = function () {
  52297. // Check
  52298. if (!this._effect || !this._effect.isReady())
  52299. return null;
  52300. // States
  52301. this._engine.enableEffect(this._effect);
  52302. this._engine.setState(false);
  52303. this._engine.setDepthBuffer(false);
  52304. this._engine.setDepthWrite(false);
  52305. // Alpha
  52306. this._engine.setAlphaMode(this.alphaMode);
  52307. if (this.alphaConstants) {
  52308. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  52309. }
  52310. // Texture
  52311. var source;
  52312. if (this._shareOutputWithPostProcess) {
  52313. source = this._shareOutputWithPostProcess.outputTexture;
  52314. }
  52315. else if (this._forcedOutputTexture) {
  52316. source = this._forcedOutputTexture;
  52317. }
  52318. else {
  52319. source = this.outputTexture;
  52320. }
  52321. this._effect._bindTexture("textureSampler", source);
  52322. // Parameters
  52323. this._effect.setVector2("scale", this._scaleRatio);
  52324. this.onApplyObservable.notifyObservers(this._effect);
  52325. return this._effect;
  52326. };
  52327. PostProcess.prototype._disposeTextures = function () {
  52328. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  52329. return;
  52330. }
  52331. if (this._textures.length > 0) {
  52332. for (var i = 0; i < this._textures.length; i++) {
  52333. this._engine._releaseTexture(this._textures.data[i]);
  52334. }
  52335. }
  52336. this._textures.dispose();
  52337. };
  52338. PostProcess.prototype.dispose = function (camera) {
  52339. camera = camera || this._camera;
  52340. this._disposeTextures();
  52341. if (this._scene) {
  52342. var index_1 = this._scene.postProcesses.indexOf(this);
  52343. if (index_1 !== -1) {
  52344. this._scene.postProcesses.splice(index_1, 1);
  52345. }
  52346. }
  52347. else {
  52348. var index_2 = this._engine.postProcesses.indexOf(this);
  52349. if (index_2 !== -1) {
  52350. this._engine.postProcesses.splice(index_2, 1);
  52351. }
  52352. }
  52353. if (!camera) {
  52354. return;
  52355. }
  52356. camera.detachPostProcess(this);
  52357. var index = camera._postProcesses.indexOf(this);
  52358. if (index === 0 && camera._postProcesses.length > 0) {
  52359. this._camera._postProcesses[0].markTextureDirty();
  52360. }
  52361. this.onActivateObservable.clear();
  52362. this.onAfterRenderObservable.clear();
  52363. this.onApplyObservable.clear();
  52364. this.onBeforeRenderObservable.clear();
  52365. this.onSizeChangedObservable.clear();
  52366. };
  52367. return PostProcess;
  52368. }());
  52369. BABYLON.PostProcess = PostProcess;
  52370. })(BABYLON || (BABYLON = {}));
  52371. //# sourceMappingURL=babylon.postProcess.js.map
  52372. var BABYLON;
  52373. (function (BABYLON) {
  52374. var PassPostProcess = /** @class */ (function (_super) {
  52375. __extends(PassPostProcess, _super);
  52376. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  52377. if (camera === void 0) { camera = null; }
  52378. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52379. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  52380. }
  52381. return PassPostProcess;
  52382. }(BABYLON.PostProcess));
  52383. BABYLON.PassPostProcess = PassPostProcess;
  52384. })(BABYLON || (BABYLON = {}));
  52385. //# sourceMappingURL=babylon.passPostProcess.js.map
  52386. var __assign = (this && this.__assign) || Object.assign || function(t) {
  52387. for (var s, i = 1, n = arguments.length; i < n; i++) {
  52388. s = arguments[i];
  52389. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  52390. t[p] = s[p];
  52391. }
  52392. return t;
  52393. };
  52394. var BABYLON;
  52395. (function (BABYLON) {
  52396. var ShadowGenerator = /** @class */ (function () {
  52397. /**
  52398. * Creates a ShadowGenerator object.
  52399. * A ShadowGenerator is the required tool to use the shadows.
  52400. * Each light casting shadows needs to use its own ShadowGenerator.
  52401. * Required parameters :
  52402. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  52403. * - `light`: the light object generating the shadows.
  52404. * - `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.
  52405. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  52406. */
  52407. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  52408. // Members
  52409. this._bias = 0.00005;
  52410. this._blurBoxOffset = 1;
  52411. this._blurScale = 2;
  52412. this._blurKernel = 1;
  52413. this._useKernelBlur = false;
  52414. this._filter = ShadowGenerator.FILTER_NONE;
  52415. this._darkness = 0;
  52416. this._transparencyShadow = false;
  52417. /**
  52418. * Controls the extent to which the shadows fade out at the edge of the frustum
  52419. * Used only by directionals and spots
  52420. */
  52421. this.frustumEdgeFalloff = 0;
  52422. this.forceBackFacesOnly = false;
  52423. this._lightDirection = BABYLON.Vector3.Zero();
  52424. this._viewMatrix = BABYLON.Matrix.Zero();
  52425. this._projectionMatrix = BABYLON.Matrix.Zero();
  52426. this._transformMatrix = BABYLON.Matrix.Zero();
  52427. this._currentFaceIndex = 0;
  52428. this._currentFaceIndexCache = 0;
  52429. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  52430. this._mapSize = mapSize;
  52431. this._light = light;
  52432. this._scene = light.getScene();
  52433. light._shadowGenerator = this;
  52434. // Texture type fallback from float to int if not supported.
  52435. var caps = this._scene.getEngine().getCaps();
  52436. if (!useFullFloatFirst) {
  52437. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  52438. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  52439. }
  52440. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  52441. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  52442. }
  52443. else {
  52444. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  52445. }
  52446. }
  52447. else {
  52448. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  52449. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  52450. }
  52451. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  52452. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  52453. }
  52454. else {
  52455. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  52456. }
  52457. }
  52458. this._initializeGenerator();
  52459. }
  52460. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  52461. // Static
  52462. get: function () {
  52463. return ShadowGenerator._FILTER_NONE;
  52464. },
  52465. enumerable: true,
  52466. configurable: true
  52467. });
  52468. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  52469. get: function () {
  52470. return ShadowGenerator._FILTER_POISSONSAMPLING;
  52471. },
  52472. enumerable: true,
  52473. configurable: true
  52474. });
  52475. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  52476. get: function () {
  52477. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  52478. },
  52479. enumerable: true,
  52480. configurable: true
  52481. });
  52482. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  52483. get: function () {
  52484. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  52485. },
  52486. enumerable: true,
  52487. configurable: true
  52488. });
  52489. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  52490. get: function () {
  52491. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  52492. },
  52493. enumerable: true,
  52494. configurable: true
  52495. });
  52496. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  52497. get: function () {
  52498. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  52499. },
  52500. enumerable: true,
  52501. configurable: true
  52502. });
  52503. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  52504. get: function () {
  52505. return this._bias;
  52506. },
  52507. set: function (bias) {
  52508. this._bias = bias;
  52509. },
  52510. enumerable: true,
  52511. configurable: true
  52512. });
  52513. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  52514. get: function () {
  52515. return this._blurBoxOffset;
  52516. },
  52517. set: function (value) {
  52518. if (this._blurBoxOffset === value) {
  52519. return;
  52520. }
  52521. this._blurBoxOffset = value;
  52522. this._disposeBlurPostProcesses();
  52523. },
  52524. enumerable: true,
  52525. configurable: true
  52526. });
  52527. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  52528. get: function () {
  52529. return this._blurScale;
  52530. },
  52531. set: function (value) {
  52532. if (this._blurScale === value) {
  52533. return;
  52534. }
  52535. this._blurScale = value;
  52536. this._disposeBlurPostProcesses();
  52537. },
  52538. enumerable: true,
  52539. configurable: true
  52540. });
  52541. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  52542. get: function () {
  52543. return this._blurKernel;
  52544. },
  52545. set: function (value) {
  52546. if (this._blurKernel === value) {
  52547. return;
  52548. }
  52549. this._blurKernel = value;
  52550. this._disposeBlurPostProcesses();
  52551. },
  52552. enumerable: true,
  52553. configurable: true
  52554. });
  52555. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  52556. get: function () {
  52557. return this._useKernelBlur;
  52558. },
  52559. set: function (value) {
  52560. if (this._useKernelBlur === value) {
  52561. return;
  52562. }
  52563. this._useKernelBlur = value;
  52564. this._disposeBlurPostProcesses();
  52565. },
  52566. enumerable: true,
  52567. configurable: true
  52568. });
  52569. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  52570. get: function () {
  52571. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  52572. },
  52573. set: function (value) {
  52574. this._depthScale = value;
  52575. },
  52576. enumerable: true,
  52577. configurable: true
  52578. });
  52579. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  52580. get: function () {
  52581. return this._filter;
  52582. },
  52583. set: function (value) {
  52584. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  52585. if (this._light.needCube()) {
  52586. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  52587. this.useExponentialShadowMap = true;
  52588. return;
  52589. }
  52590. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  52591. this.useCloseExponentialShadowMap = true;
  52592. return;
  52593. }
  52594. }
  52595. if (this._filter === value) {
  52596. return;
  52597. }
  52598. this._filter = value;
  52599. this._disposeBlurPostProcesses();
  52600. this._applyFilterValues();
  52601. this._light._markMeshesAsLightDirty();
  52602. },
  52603. enumerable: true,
  52604. configurable: true
  52605. });
  52606. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  52607. get: function () {
  52608. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  52609. },
  52610. set: function (value) {
  52611. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  52612. return;
  52613. }
  52614. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  52615. },
  52616. enumerable: true,
  52617. configurable: true
  52618. });
  52619. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  52620. get: function () {
  52621. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  52622. return this.useExponentialShadowMap;
  52623. },
  52624. set: function (value) {
  52625. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  52626. this.useExponentialShadowMap = value;
  52627. },
  52628. enumerable: true,
  52629. configurable: true
  52630. });
  52631. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  52632. get: function () {
  52633. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  52634. return this.useBlurExponentialShadowMap;
  52635. },
  52636. set: function (value) {
  52637. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  52638. this.useBlurExponentialShadowMap = value;
  52639. },
  52640. enumerable: true,
  52641. configurable: true
  52642. });
  52643. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  52644. get: function () {
  52645. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  52646. },
  52647. set: function (value) {
  52648. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  52649. return;
  52650. }
  52651. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  52652. },
  52653. enumerable: true,
  52654. configurable: true
  52655. });
  52656. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  52657. get: function () {
  52658. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  52659. },
  52660. set: function (value) {
  52661. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  52662. return;
  52663. }
  52664. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  52665. },
  52666. enumerable: true,
  52667. configurable: true
  52668. });
  52669. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  52670. get: function () {
  52671. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  52672. },
  52673. set: function (value) {
  52674. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  52675. return;
  52676. }
  52677. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  52678. },
  52679. enumerable: true,
  52680. configurable: true
  52681. });
  52682. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  52683. get: function () {
  52684. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  52685. },
  52686. set: function (value) {
  52687. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  52688. return;
  52689. }
  52690. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  52691. },
  52692. enumerable: true,
  52693. configurable: true
  52694. });
  52695. /**
  52696. * Returns the darkness value (float).
  52697. */
  52698. ShadowGenerator.prototype.getDarkness = function () {
  52699. return this._darkness;
  52700. };
  52701. /**
  52702. * Sets the ShadowGenerator darkness value (float <= 1.0).
  52703. * Returns the ShadowGenerator.
  52704. */
  52705. ShadowGenerator.prototype.setDarkness = function (darkness) {
  52706. if (darkness >= 1.0)
  52707. this._darkness = 1.0;
  52708. else if (darkness <= 0.0)
  52709. this._darkness = 0.0;
  52710. else
  52711. this._darkness = darkness;
  52712. return this;
  52713. };
  52714. /**
  52715. * Sets the ability to have transparent shadow (boolean).
  52716. * Returns the ShadowGenerator.
  52717. */
  52718. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  52719. this._transparencyShadow = hasShadow;
  52720. return this;
  52721. };
  52722. /**
  52723. * Returns a RenderTargetTexture object : the shadow map texture.
  52724. */
  52725. ShadowGenerator.prototype.getShadowMap = function () {
  52726. return this._shadowMap;
  52727. };
  52728. /**
  52729. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  52730. */
  52731. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  52732. if (this._shadowMap2) {
  52733. return this._shadowMap2;
  52734. }
  52735. return this._shadowMap;
  52736. };
  52737. /**
  52738. * Helper function to add a mesh and its descendants to the list of shadow casters
  52739. * @param mesh Mesh to add
  52740. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  52741. */
  52742. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  52743. if (includeDescendants === void 0) { includeDescendants = true; }
  52744. if (!this._shadowMap) {
  52745. return this;
  52746. }
  52747. if (!this._shadowMap.renderList) {
  52748. this._shadowMap.renderList = [];
  52749. }
  52750. this._shadowMap.renderList.push(mesh);
  52751. if (includeDescendants) {
  52752. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  52753. }
  52754. return this;
  52755. var _a;
  52756. };
  52757. /**
  52758. * Helper function to remove a mesh and its descendants from the list of shadow casters
  52759. * @param mesh Mesh to remove
  52760. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  52761. */
  52762. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  52763. if (includeDescendants === void 0) { includeDescendants = true; }
  52764. if (!this._shadowMap || !this._shadowMap.renderList) {
  52765. return this;
  52766. }
  52767. var index = this._shadowMap.renderList.indexOf(mesh);
  52768. if (index !== -1) {
  52769. this._shadowMap.renderList.splice(index, 1);
  52770. }
  52771. if (includeDescendants) {
  52772. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  52773. var child = _a[_i];
  52774. this.removeShadowCaster(child);
  52775. }
  52776. }
  52777. return this;
  52778. };
  52779. /**
  52780. * Returns the associated light object.
  52781. */
  52782. ShadowGenerator.prototype.getLight = function () {
  52783. return this._light;
  52784. };
  52785. ShadowGenerator.prototype._initializeGenerator = function () {
  52786. this._light._markMeshesAsLightDirty();
  52787. this._initializeShadowMap();
  52788. };
  52789. ShadowGenerator.prototype._initializeShadowMap = function () {
  52790. var _this = this;
  52791. // Render target
  52792. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  52793. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52794. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52795. this._shadowMap.anisotropicFilteringLevel = 1;
  52796. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52797. this._shadowMap.renderParticles = false;
  52798. this._shadowMap.ignoreCameraViewport = true;
  52799. // Record Face Index before render.
  52800. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  52801. _this._currentFaceIndex = faceIndex;
  52802. });
  52803. // Custom render function.
  52804. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  52805. // Blur if required afer render.
  52806. this._shadowMap.onAfterUnbindObservable.add(function () {
  52807. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  52808. return;
  52809. }
  52810. if (!_this._blurPostProcesses || !_this._blurPostProcesses.length) {
  52811. _this._initializeBlurRTTAndPostProcesses();
  52812. }
  52813. var shadowMap = _this.getShadowMapForRendering();
  52814. if (shadowMap) {
  52815. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  52816. }
  52817. });
  52818. // Clear according to the chosen filter.
  52819. this._shadowMap.onClearObservable.add(function (engine) {
  52820. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  52821. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  52822. }
  52823. else {
  52824. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  52825. }
  52826. });
  52827. };
  52828. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  52829. var _this = this;
  52830. var engine = this._scene.getEngine();
  52831. var targetSize = this._mapSize / this.blurScale;
  52832. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  52833. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  52834. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52835. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52836. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52837. }
  52838. if (this.useKernelBlur) {
  52839. 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);
  52840. this._kernelBlurXPostprocess.width = targetSize;
  52841. this._kernelBlurXPostprocess.height = targetSize;
  52842. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  52843. effect.setTexture("textureSampler", _this._shadowMap);
  52844. });
  52845. 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);
  52846. this._kernelBlurXPostprocess.autoClear = false;
  52847. this._kernelBlurYPostprocess.autoClear = false;
  52848. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  52849. this._kernelBlurXPostprocess.packedFloat = true;
  52850. this._kernelBlurYPostprocess.packedFloat = true;
  52851. }
  52852. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  52853. }
  52854. else {
  52855. 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);
  52856. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  52857. effect.setFloat2("screenSize", targetSize, targetSize);
  52858. effect.setTexture("textureSampler", _this._shadowMap);
  52859. });
  52860. this._boxBlurPostprocess.autoClear = false;
  52861. this._blurPostProcesses = [this._boxBlurPostprocess];
  52862. }
  52863. };
  52864. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  52865. var index;
  52866. var engine = this._scene.getEngine();
  52867. if (depthOnlySubMeshes.length) {
  52868. engine.setColorWrite(false);
  52869. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  52870. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  52871. }
  52872. engine.setColorWrite(true);
  52873. }
  52874. for (index = 0; index < opaqueSubMeshes.length; index++) {
  52875. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  52876. }
  52877. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  52878. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  52879. }
  52880. if (this._transparencyShadow) {
  52881. for (index = 0; index < transparentSubMeshes.length; index++) {
  52882. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  52883. }
  52884. }
  52885. };
  52886. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  52887. var _this = this;
  52888. var mesh = subMesh.getRenderingMesh();
  52889. var scene = this._scene;
  52890. var engine = scene.getEngine();
  52891. var material = subMesh.getMaterial();
  52892. if (!material) {
  52893. return;
  52894. }
  52895. // Culling
  52896. engine.setState(material.backFaceCulling);
  52897. // Managing instances
  52898. var batch = mesh._getInstancesRenderList(subMesh._id);
  52899. if (batch.mustReturn) {
  52900. return;
  52901. }
  52902. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  52903. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  52904. engine.enableEffect(this._effect);
  52905. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  52906. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  52907. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  52908. this._effect.setVector3("lightPosition", this.getLight().position);
  52909. if (scene.activeCamera) {
  52910. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  52911. }
  52912. // Alpha test
  52913. if (material && material.needAlphaTesting()) {
  52914. var alphaTexture = material.getAlphaTestTexture();
  52915. if (alphaTexture) {
  52916. this._effect.setTexture("diffuseSampler", alphaTexture);
  52917. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  52918. }
  52919. }
  52920. // Bones
  52921. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52922. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  52923. }
  52924. if (this.forceBackFacesOnly) {
  52925. engine.setState(true, 0, false, true);
  52926. }
  52927. // Draw
  52928. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  52929. if (this.forceBackFacesOnly) {
  52930. engine.setState(true, 0, false, false);
  52931. }
  52932. }
  52933. else {
  52934. // Need to reset refresh rate of the shadowMap
  52935. if (this._shadowMap) {
  52936. this._shadowMap.resetRefreshCounter();
  52937. }
  52938. }
  52939. };
  52940. ShadowGenerator.prototype._applyFilterValues = function () {
  52941. if (!this._shadowMap) {
  52942. return;
  52943. }
  52944. if (this.filter === ShadowGenerator.FILTER_NONE) {
  52945. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  52946. }
  52947. else {
  52948. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52949. }
  52950. };
  52951. /**
  52952. * Force shader compilation including textures ready check
  52953. */
  52954. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  52955. var _this = this;
  52956. var localOptions = __assign({ useInstances: false }, options);
  52957. var shadowMap = this.getShadowMap();
  52958. if (!shadowMap) {
  52959. if (onCompiled) {
  52960. onCompiled(this);
  52961. }
  52962. return;
  52963. }
  52964. var renderList = shadowMap.renderList;
  52965. if (!renderList) {
  52966. if (onCompiled) {
  52967. onCompiled(this);
  52968. }
  52969. return;
  52970. }
  52971. var subMeshes = new Array();
  52972. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  52973. var mesh = renderList_1[_i];
  52974. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  52975. }
  52976. if (subMeshes.length === 0) {
  52977. if (onCompiled) {
  52978. onCompiled(this);
  52979. }
  52980. return;
  52981. }
  52982. var currentIndex = 0;
  52983. var checkReady = function () {
  52984. if (!_this._scene || !_this._scene.getEngine()) {
  52985. return;
  52986. }
  52987. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  52988. currentIndex++;
  52989. if (currentIndex >= subMeshes.length) {
  52990. if (onCompiled) {
  52991. onCompiled(_this);
  52992. }
  52993. return;
  52994. }
  52995. }
  52996. setTimeout(checkReady, 16);
  52997. };
  52998. checkReady();
  52999. };
  53000. /**
  53001. * Boolean : true when the ShadowGenerator is finally computed.
  53002. */
  53003. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  53004. var defines = [];
  53005. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  53006. defines.push("#define FLOAT");
  53007. }
  53008. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  53009. defines.push("#define ESM");
  53010. }
  53011. var attribs = [BABYLON.VertexBuffer.PositionKind];
  53012. var mesh = subMesh.getMesh();
  53013. var material = subMesh.getMaterial();
  53014. // Alpha test
  53015. if (material && material.needAlphaTesting()) {
  53016. var alphaTexture = material.getAlphaTestTexture();
  53017. if (alphaTexture) {
  53018. defines.push("#define ALPHATEST");
  53019. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53020. attribs.push(BABYLON.VertexBuffer.UVKind);
  53021. defines.push("#define UV1");
  53022. }
  53023. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53024. if (alphaTexture.coordinatesIndex === 1) {
  53025. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53026. defines.push("#define UV2");
  53027. }
  53028. }
  53029. }
  53030. }
  53031. // Bones
  53032. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53033. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53034. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53035. if (mesh.numBoneInfluencers > 4) {
  53036. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53037. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53038. }
  53039. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53040. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53041. }
  53042. else {
  53043. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53044. }
  53045. // Instances
  53046. if (useInstances) {
  53047. defines.push("#define INSTANCES");
  53048. attribs.push("world0");
  53049. attribs.push("world1");
  53050. attribs.push("world2");
  53051. attribs.push("world3");
  53052. }
  53053. // Get correct effect
  53054. var join = defines.join("\n");
  53055. if (this._cachedDefines !== join) {
  53056. this._cachedDefines = join;
  53057. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  53058. }
  53059. return this._effect.isReady();
  53060. };
  53061. /**
  53062. * This creates the defines related to the standard BJS materials.
  53063. */
  53064. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  53065. var scene = this._scene;
  53066. var light = this._light;
  53067. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  53068. return;
  53069. }
  53070. defines["SHADOW" + lightIndex] = true;
  53071. if (this.usePoissonSampling) {
  53072. defines["SHADOWPCF" + lightIndex] = true;
  53073. }
  53074. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  53075. defines["SHADOWESM" + lightIndex] = true;
  53076. }
  53077. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  53078. defines["SHADOWCLOSEESM" + lightIndex] = true;
  53079. }
  53080. if (light.needCube()) {
  53081. defines["SHADOWCUBE" + lightIndex] = true;
  53082. }
  53083. };
  53084. /**
  53085. * This binds shadow lights related to the standard BJS materials.
  53086. * It implies the unifroms available on the materials are the standard BJS ones.
  53087. */
  53088. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  53089. var light = this._light;
  53090. var scene = this._scene;
  53091. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  53092. return;
  53093. }
  53094. var camera = scene.activeCamera;
  53095. if (!camera) {
  53096. return;
  53097. }
  53098. var shadowMap = this.getShadowMap();
  53099. if (!shadowMap) {
  53100. return;
  53101. }
  53102. if (!light.needCube()) {
  53103. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  53104. }
  53105. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  53106. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  53107. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  53108. };
  53109. // Methods
  53110. /**
  53111. * Returns a Matrix object : the updated transformation matrix.
  53112. */
  53113. ShadowGenerator.prototype.getTransformMatrix = function () {
  53114. var scene = this._scene;
  53115. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  53116. return this._transformMatrix;
  53117. }
  53118. this._currentRenderID = scene.getRenderId();
  53119. this._currentFaceIndexCache = this._currentFaceIndex;
  53120. var lightPosition = this._light.position;
  53121. if (this._light.computeTransformedInformation()) {
  53122. lightPosition = this._light.transformedPosition;
  53123. }
  53124. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  53125. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  53126. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  53127. }
  53128. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  53129. this._cachedPosition = lightPosition.clone();
  53130. this._cachedDirection = this._lightDirection.clone();
  53131. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  53132. var shadowMap = this.getShadowMap();
  53133. if (shadowMap) {
  53134. var renderList = shadowMap.renderList;
  53135. if (renderList) {
  53136. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  53137. }
  53138. }
  53139. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  53140. }
  53141. return this._transformMatrix;
  53142. };
  53143. ShadowGenerator.prototype.recreateShadowMap = function () {
  53144. var shadowMap = this._shadowMap;
  53145. if (!shadowMap) {
  53146. return;
  53147. }
  53148. // Track render list.
  53149. var renderList = shadowMap.renderList;
  53150. // Clean up existing data.
  53151. this._disposeRTTandPostProcesses();
  53152. // Reinitializes.
  53153. this._initializeGenerator();
  53154. // Reaffect the filter to ensure a correct fallback if necessary.
  53155. this.filter = this.filter;
  53156. // Reaffect the filter.
  53157. this._applyFilterValues();
  53158. // Reaffect Render List.
  53159. this._shadowMap.renderList = renderList;
  53160. };
  53161. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  53162. if (this._shadowMap2) {
  53163. this._shadowMap2.dispose();
  53164. this._shadowMap2 = null;
  53165. }
  53166. if (this._downSamplePostprocess) {
  53167. this._downSamplePostprocess.dispose();
  53168. this._downSamplePostprocess = null;
  53169. }
  53170. if (this._boxBlurPostprocess) {
  53171. this._boxBlurPostprocess.dispose();
  53172. this._boxBlurPostprocess = null;
  53173. }
  53174. if (this._kernelBlurXPostprocess) {
  53175. this._kernelBlurXPostprocess.dispose();
  53176. this._kernelBlurXPostprocess = null;
  53177. }
  53178. if (this._kernelBlurYPostprocess) {
  53179. this._kernelBlurYPostprocess.dispose();
  53180. this._kernelBlurYPostprocess = null;
  53181. }
  53182. this._blurPostProcesses = [];
  53183. };
  53184. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  53185. if (this._shadowMap) {
  53186. this._shadowMap.dispose();
  53187. this._shadowMap = null;
  53188. }
  53189. this._disposeBlurPostProcesses();
  53190. };
  53191. /**
  53192. * Disposes the ShadowGenerator.
  53193. * Returns nothing.
  53194. */
  53195. ShadowGenerator.prototype.dispose = function () {
  53196. this._disposeRTTandPostProcesses();
  53197. if (this._light) {
  53198. this._light._shadowGenerator = null;
  53199. this._light._markMeshesAsLightDirty();
  53200. }
  53201. };
  53202. /**
  53203. * Serializes the ShadowGenerator and returns a serializationObject.
  53204. */
  53205. ShadowGenerator.prototype.serialize = function () {
  53206. var serializationObject = {};
  53207. var shadowMap = this.getShadowMap();
  53208. if (!shadowMap) {
  53209. return serializationObject;
  53210. }
  53211. serializationObject.lightId = this._light.id;
  53212. serializationObject.mapSize = shadowMap.getRenderSize();
  53213. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  53214. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  53215. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  53216. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  53217. serializationObject.usePoissonSampling = this.usePoissonSampling;
  53218. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  53219. serializationObject.depthScale = this.depthScale;
  53220. serializationObject.darkness = this.getDarkness();
  53221. serializationObject.blurBoxOffset = this.blurBoxOffset;
  53222. serializationObject.blurKernel = this.blurKernel;
  53223. serializationObject.blurScale = this.blurScale;
  53224. serializationObject.useKernelBlur = this.useKernelBlur;
  53225. serializationObject.transparencyShadow = this._transparencyShadow;
  53226. serializationObject.renderList = [];
  53227. if (shadowMap.renderList) {
  53228. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  53229. var mesh = shadowMap.renderList[meshIndex];
  53230. serializationObject.renderList.push(mesh.id);
  53231. }
  53232. }
  53233. return serializationObject;
  53234. };
  53235. /**
  53236. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  53237. */
  53238. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  53239. //casting to point light, as light is missing the position attr and typescript complains.
  53240. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  53241. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  53242. var shadowMap = shadowGenerator.getShadowMap();
  53243. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  53244. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  53245. meshes.forEach(function (mesh) {
  53246. if (!shadowMap) {
  53247. return;
  53248. }
  53249. if (!shadowMap.renderList) {
  53250. shadowMap.renderList = [];
  53251. }
  53252. shadowMap.renderList.push(mesh);
  53253. });
  53254. }
  53255. if (parsedShadowGenerator.usePoissonSampling) {
  53256. shadowGenerator.usePoissonSampling = true;
  53257. }
  53258. else if (parsedShadowGenerator.useExponentialShadowMap) {
  53259. shadowGenerator.useExponentialShadowMap = true;
  53260. }
  53261. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  53262. shadowGenerator.useBlurExponentialShadowMap = true;
  53263. }
  53264. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  53265. shadowGenerator.useCloseExponentialShadowMap = true;
  53266. }
  53267. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  53268. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  53269. }
  53270. else if (parsedShadowGenerator.useVarianceShadowMap) {
  53271. shadowGenerator.useExponentialShadowMap = true;
  53272. }
  53273. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  53274. shadowGenerator.useBlurExponentialShadowMap = true;
  53275. }
  53276. if (parsedShadowGenerator.depthScale) {
  53277. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  53278. }
  53279. if (parsedShadowGenerator.blurScale) {
  53280. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  53281. }
  53282. if (parsedShadowGenerator.blurBoxOffset) {
  53283. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  53284. }
  53285. if (parsedShadowGenerator.useKernelBlur) {
  53286. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  53287. }
  53288. if (parsedShadowGenerator.blurKernel) {
  53289. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  53290. }
  53291. if (parsedShadowGenerator.bias !== undefined) {
  53292. shadowGenerator.bias = parsedShadowGenerator.bias;
  53293. }
  53294. if (parsedShadowGenerator.darkness) {
  53295. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  53296. }
  53297. if (parsedShadowGenerator.transparencyShadow) {
  53298. shadowGenerator.setTransparencyShadow(true);
  53299. }
  53300. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  53301. return shadowGenerator;
  53302. };
  53303. ShadowGenerator._FILTER_NONE = 0;
  53304. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  53305. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  53306. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  53307. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  53308. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  53309. return ShadowGenerator;
  53310. }());
  53311. BABYLON.ShadowGenerator = ShadowGenerator;
  53312. })(BABYLON || (BABYLON = {}));
  53313. //# sourceMappingURL=babylon.shadowGenerator.js.map
  53314. var BABYLON;
  53315. (function (BABYLON) {
  53316. var DefaultLoadingScreen = /** @class */ (function () {
  53317. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  53318. if (_loadingText === void 0) { _loadingText = ""; }
  53319. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  53320. var _this = this;
  53321. this._renderingCanvas = _renderingCanvas;
  53322. this._loadingText = _loadingText;
  53323. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  53324. // Resize
  53325. this._resizeLoadingUI = function () {
  53326. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  53327. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  53328. if (!_this._loadingDiv) {
  53329. return;
  53330. }
  53331. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  53332. _this._loadingDiv.style.left = canvasRect.left + "px";
  53333. _this._loadingDiv.style.top = canvasRect.top + "px";
  53334. _this._loadingDiv.style.width = canvasRect.width + "px";
  53335. _this._loadingDiv.style.height = canvasRect.height + "px";
  53336. };
  53337. }
  53338. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  53339. if (this._loadingDiv) {
  53340. // Do not add a loading screen if there is already one
  53341. return;
  53342. }
  53343. this._loadingDiv = document.createElement("div");
  53344. this._loadingDiv.id = "babylonjsLoadingDiv";
  53345. this._loadingDiv.style.opacity = "0";
  53346. this._loadingDiv.style.transition = "opacity 1.5s ease";
  53347. this._loadingDiv.style.pointerEvents = "none";
  53348. // Loading text
  53349. this._loadingTextDiv = document.createElement("div");
  53350. this._loadingTextDiv.style.position = "absolute";
  53351. this._loadingTextDiv.style.left = "0";
  53352. this._loadingTextDiv.style.top = "50%";
  53353. this._loadingTextDiv.style.marginTop = "80px";
  53354. this._loadingTextDiv.style.width = "100%";
  53355. this._loadingTextDiv.style.height = "20px";
  53356. this._loadingTextDiv.style.fontFamily = "Arial";
  53357. this._loadingTextDiv.style.fontSize = "14px";
  53358. this._loadingTextDiv.style.color = "white";
  53359. this._loadingTextDiv.style.textAlign = "center";
  53360. this._loadingTextDiv.innerHTML = "Loading";
  53361. this._loadingDiv.appendChild(this._loadingTextDiv);
  53362. //set the predefined text
  53363. this._loadingTextDiv.innerHTML = this._loadingText;
  53364. // Generating keyframes
  53365. var style = document.createElement('style');
  53366. style.type = 'text/css';
  53367. 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 }";
  53368. style.innerHTML = keyFrames;
  53369. document.getElementsByTagName('head')[0].appendChild(style);
  53370. // Loading img
  53371. var imgBack = new Image();
  53372. 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";
  53373. imgBack.style.position = "absolute";
  53374. imgBack.style.left = "50%";
  53375. imgBack.style.top = "50%";
  53376. imgBack.style.marginLeft = "-60px";
  53377. imgBack.style.marginTop = "-60px";
  53378. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  53379. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  53380. imgBack.style.transformOrigin = "50% 50%";
  53381. imgBack.style.webkitTransformOrigin = "50% 50%";
  53382. this._loadingDiv.appendChild(imgBack);
  53383. this._resizeLoadingUI();
  53384. window.addEventListener("resize", this._resizeLoadingUI);
  53385. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  53386. document.body.appendChild(this._loadingDiv);
  53387. this._loadingDiv.style.opacity = "1";
  53388. };
  53389. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  53390. var _this = this;
  53391. if (!this._loadingDiv) {
  53392. return;
  53393. }
  53394. var onTransitionEnd = function () {
  53395. if (!_this._loadingDiv) {
  53396. return;
  53397. }
  53398. document.body.removeChild(_this._loadingDiv);
  53399. window.removeEventListener("resize", _this._resizeLoadingUI);
  53400. _this._loadingDiv = null;
  53401. };
  53402. this._loadingDiv.style.opacity = "0";
  53403. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  53404. };
  53405. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  53406. set: function (text) {
  53407. this._loadingText = text;
  53408. if (this._loadingTextDiv) {
  53409. this._loadingTextDiv.innerHTML = this._loadingText;
  53410. }
  53411. },
  53412. enumerable: true,
  53413. configurable: true
  53414. });
  53415. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  53416. get: function () {
  53417. return this._loadingDivBackgroundColor;
  53418. },
  53419. set: function (color) {
  53420. this._loadingDivBackgroundColor = color;
  53421. if (!this._loadingDiv) {
  53422. return;
  53423. }
  53424. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  53425. },
  53426. enumerable: true,
  53427. configurable: true
  53428. });
  53429. return DefaultLoadingScreen;
  53430. }());
  53431. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  53432. })(BABYLON || (BABYLON = {}));
  53433. //# sourceMappingURL=babylon.loadingScreen.js.map
  53434. var BABYLON;
  53435. (function (BABYLON) {
  53436. var SceneLoaderProgressEvent = /** @class */ (function () {
  53437. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  53438. this.lengthComputable = lengthComputable;
  53439. this.loaded = loaded;
  53440. this.total = total;
  53441. }
  53442. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  53443. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  53444. };
  53445. return SceneLoaderProgressEvent;
  53446. }());
  53447. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  53448. var SceneLoader = /** @class */ (function () {
  53449. function SceneLoader() {
  53450. }
  53451. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  53452. get: function () {
  53453. return 0;
  53454. },
  53455. enumerable: true,
  53456. configurable: true
  53457. });
  53458. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  53459. get: function () {
  53460. return 1;
  53461. },
  53462. enumerable: true,
  53463. configurable: true
  53464. });
  53465. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  53466. get: function () {
  53467. return 2;
  53468. },
  53469. enumerable: true,
  53470. configurable: true
  53471. });
  53472. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  53473. get: function () {
  53474. return 3;
  53475. },
  53476. enumerable: true,
  53477. configurable: true
  53478. });
  53479. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  53480. get: function () {
  53481. return SceneLoader._ForceFullSceneLoadingForIncremental;
  53482. },
  53483. set: function (value) {
  53484. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  53485. },
  53486. enumerable: true,
  53487. configurable: true
  53488. });
  53489. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  53490. get: function () {
  53491. return SceneLoader._ShowLoadingScreen;
  53492. },
  53493. set: function (value) {
  53494. SceneLoader._ShowLoadingScreen = value;
  53495. },
  53496. enumerable: true,
  53497. configurable: true
  53498. });
  53499. Object.defineProperty(SceneLoader, "loggingLevel", {
  53500. get: function () {
  53501. return SceneLoader._loggingLevel;
  53502. },
  53503. set: function (value) {
  53504. SceneLoader._loggingLevel = value;
  53505. },
  53506. enumerable: true,
  53507. configurable: true
  53508. });
  53509. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  53510. get: function () {
  53511. return SceneLoader._CleanBoneMatrixWeights;
  53512. },
  53513. set: function (value) {
  53514. SceneLoader._CleanBoneMatrixWeights = value;
  53515. },
  53516. enumerable: true,
  53517. configurable: true
  53518. });
  53519. SceneLoader._getDefaultPlugin = function () {
  53520. return SceneLoader._registeredPlugins[".babylon"];
  53521. };
  53522. SceneLoader._getPluginForExtension = function (extension) {
  53523. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  53524. if (registeredPlugin) {
  53525. return registeredPlugin;
  53526. }
  53527. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  53528. return SceneLoader._getDefaultPlugin();
  53529. };
  53530. SceneLoader._getPluginForDirectLoad = function (data) {
  53531. for (var extension in SceneLoader._registeredPlugins) {
  53532. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  53533. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  53534. return SceneLoader._registeredPlugins[extension];
  53535. }
  53536. }
  53537. return SceneLoader._getDefaultPlugin();
  53538. };
  53539. SceneLoader._getPluginForFilename = function (sceneFilename) {
  53540. if (sceneFilename.name) {
  53541. sceneFilename = sceneFilename.name;
  53542. }
  53543. var queryStringPosition = sceneFilename.indexOf("?");
  53544. if (queryStringPosition !== -1) {
  53545. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  53546. }
  53547. var dotPosition = sceneFilename.lastIndexOf(".");
  53548. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  53549. return SceneLoader._getPluginForExtension(extension);
  53550. };
  53551. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  53552. SceneLoader._getDirectLoad = function (sceneFilename) {
  53553. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  53554. return sceneFilename.substr(5);
  53555. }
  53556. return null;
  53557. };
  53558. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  53559. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  53560. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  53561. var plugin;
  53562. if (registeredPlugin.plugin.createPlugin) {
  53563. plugin = registeredPlugin.plugin.createPlugin();
  53564. }
  53565. else {
  53566. plugin = registeredPlugin.plugin;
  53567. }
  53568. var useArrayBuffer = registeredPlugin.isBinary;
  53569. var database;
  53570. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  53571. var dataCallback = function (data, responseURL) {
  53572. if (scene.isDisposed) {
  53573. onError("Scene has been disposed");
  53574. return;
  53575. }
  53576. scene.database = database;
  53577. onSuccess(plugin, data, responseURL);
  53578. };
  53579. var manifestChecked = function (success) {
  53580. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress ? function (event) {
  53581. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  53582. } : undefined, database, useArrayBuffer, function (request, exception) {
  53583. if (request) {
  53584. onError(request.status + " " + request.statusText, exception);
  53585. }
  53586. });
  53587. };
  53588. if (directLoad) {
  53589. dataCallback(directLoad);
  53590. return plugin;
  53591. }
  53592. if (rootUrl.indexOf("file:") === -1) {
  53593. if (scene.getEngine().enableOfflineSupport) {
  53594. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  53595. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  53596. }
  53597. else {
  53598. manifestChecked(true);
  53599. }
  53600. }
  53601. else {
  53602. var fileOrString = sceneFilename;
  53603. if (fileOrString.name) {
  53604. BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  53605. }
  53606. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  53607. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  53608. }
  53609. else {
  53610. onError("Unable to find file named " + sceneFilename);
  53611. }
  53612. }
  53613. return plugin;
  53614. };
  53615. // Public functions
  53616. SceneLoader.GetPluginForExtension = function (extension) {
  53617. return SceneLoader._getPluginForExtension(extension).plugin;
  53618. };
  53619. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  53620. return !!SceneLoader._registeredPlugins[extension];
  53621. };
  53622. SceneLoader.RegisterPlugin = function (plugin) {
  53623. if (typeof plugin.extensions === "string") {
  53624. var extension = plugin.extensions;
  53625. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  53626. plugin: plugin,
  53627. isBinary: false
  53628. };
  53629. }
  53630. else {
  53631. var extensions = plugin.extensions;
  53632. Object.keys(extensions).forEach(function (extension) {
  53633. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  53634. plugin: plugin,
  53635. isBinary: extensions[extension].isBinary
  53636. };
  53637. });
  53638. }
  53639. };
  53640. /**
  53641. * Import meshes into a scene
  53642. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  53643. * @param rootUrl a string that defines the root url for scene and resources
  53644. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  53645. * @param scene the instance of BABYLON.Scene to append to
  53646. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  53647. * @param onProgress a callback with a progress event for each file being loaded
  53648. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  53649. */
  53650. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  53651. if (onSuccess === void 0) { onSuccess = null; }
  53652. if (onProgress === void 0) { onProgress = null; }
  53653. if (onError === void 0) { onError = null; }
  53654. if (pluginExtension === void 0) { pluginExtension = null; }
  53655. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  53656. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  53657. return null;
  53658. }
  53659. var loadingToken = {};
  53660. scene._addPendingData(loadingToken);
  53661. var errorHandler = function (message, exception) {
  53662. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  53663. if (onError) {
  53664. onError(scene, errorMessage, exception);
  53665. }
  53666. else {
  53667. BABYLON.Tools.Error(errorMessage);
  53668. // should the exception be thrown?
  53669. }
  53670. scene._removePendingData(loadingToken);
  53671. };
  53672. var progressHandler = onProgress ? function (event) {
  53673. try {
  53674. onProgress(event);
  53675. }
  53676. catch (e) {
  53677. errorHandler("Error in onProgress callback", e);
  53678. }
  53679. } : undefined;
  53680. var successHandler = function (meshes, particleSystems, skeletons) {
  53681. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  53682. if (onSuccess) {
  53683. try {
  53684. onSuccess(meshes, particleSystems, skeletons);
  53685. }
  53686. catch (e) {
  53687. errorHandler("Error in onSuccess callback", e);
  53688. }
  53689. }
  53690. scene._removePendingData(loadingToken);
  53691. };
  53692. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  53693. if (plugin.rewriteRootURL) {
  53694. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  53695. }
  53696. if (plugin.importMesh) {
  53697. var syncedPlugin = plugin;
  53698. var meshes = new Array();
  53699. var particleSystems = new Array();
  53700. var skeletons = new Array();
  53701. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  53702. return;
  53703. }
  53704. scene.loadingPluginName = plugin.name;
  53705. successHandler(meshes, particleSystems, skeletons);
  53706. }
  53707. else {
  53708. var asyncedPlugin = plugin;
  53709. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  53710. scene.loadingPluginName = plugin.name;
  53711. successHandler(meshes, particleSystems, skeletons);
  53712. }, progressHandler, errorHandler);
  53713. }
  53714. }, progressHandler, errorHandler, pluginExtension);
  53715. };
  53716. /**
  53717. * Load a scene
  53718. * @param rootUrl a string that defines the root url for scene and resources
  53719. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  53720. * @param engine is the instance of BABYLON.Engine to use to create the scene
  53721. * @param onSuccess a callback with the scene when import succeeds
  53722. * @param onProgress a callback with a progress event for each file being loaded
  53723. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  53724. */
  53725. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  53726. if (onSuccess === void 0) { onSuccess = null; }
  53727. if (onProgress === void 0) { onProgress = null; }
  53728. if (onError === void 0) { onError = null; }
  53729. if (pluginExtension === void 0) { pluginExtension = null; }
  53730. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  53731. };
  53732. /**
  53733. * Append a scene
  53734. * @param rootUrl a string that defines the root url for scene and resources
  53735. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  53736. * @param scene is the instance of BABYLON.Scene to append to
  53737. * @param onSuccess a callback with the scene when import succeeds
  53738. * @param onProgress a callback with a progress event for each file being loaded
  53739. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  53740. */
  53741. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  53742. if (onSuccess === void 0) { onSuccess = null; }
  53743. if (onProgress === void 0) { onProgress = null; }
  53744. if (onError === void 0) { onError = null; }
  53745. if (pluginExtension === void 0) { pluginExtension = null; }
  53746. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  53747. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  53748. return null;
  53749. }
  53750. if (SceneLoader.ShowLoadingScreen) {
  53751. scene.getEngine().displayLoadingUI();
  53752. }
  53753. var loadingToken = {};
  53754. scene._addPendingData(loadingToken);
  53755. var errorHandler = function (message, exception) {
  53756. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  53757. if (onError) {
  53758. onError(scene, errorMessage, exception);
  53759. }
  53760. else {
  53761. BABYLON.Tools.Error(errorMessage);
  53762. // should the exception be thrown?
  53763. }
  53764. scene._removePendingData(loadingToken);
  53765. scene.getEngine().hideLoadingUI();
  53766. };
  53767. var progressHandler = onProgress ? function (event) {
  53768. try {
  53769. onProgress(event);
  53770. }
  53771. catch (e) {
  53772. errorHandler("Error in onProgress callback", e);
  53773. }
  53774. } : undefined;
  53775. var successHandler = function () {
  53776. if (onSuccess) {
  53777. try {
  53778. onSuccess(scene);
  53779. }
  53780. catch (e) {
  53781. errorHandler("Error in onSuccess callback", e);
  53782. }
  53783. }
  53784. scene._removePendingData(loadingToken);
  53785. };
  53786. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  53787. if (plugin.load) {
  53788. var syncedPlugin = plugin;
  53789. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  53790. return;
  53791. }
  53792. scene.loadingPluginName = plugin.name;
  53793. successHandler();
  53794. }
  53795. else {
  53796. var asyncedPlugin = plugin;
  53797. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  53798. scene.loadingPluginName = plugin.name;
  53799. successHandler();
  53800. }, progressHandler, errorHandler);
  53801. }
  53802. if (SceneLoader.ShowLoadingScreen) {
  53803. scene.executeWhenReady(function () {
  53804. scene.getEngine().hideLoadingUI();
  53805. });
  53806. }
  53807. }, progressHandler, errorHandler, pluginExtension);
  53808. };
  53809. // Flags
  53810. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  53811. SceneLoader._ShowLoadingScreen = true;
  53812. SceneLoader._CleanBoneMatrixWeights = false;
  53813. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  53814. // Members
  53815. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  53816. SceneLoader._registeredPlugins = {};
  53817. return SceneLoader;
  53818. }());
  53819. BABYLON.SceneLoader = SceneLoader;
  53820. ;
  53821. })(BABYLON || (BABYLON = {}));
  53822. //# sourceMappingURL=babylon.sceneLoader.js.map
  53823. var BABYLON;
  53824. (function (BABYLON) {
  53825. var Internals;
  53826. (function (Internals) {
  53827. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  53828. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  53829. var parsedMaterial = parsedData.materials[index];
  53830. if (parsedMaterial.id === id) {
  53831. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  53832. }
  53833. }
  53834. return null;
  53835. };
  53836. var isDescendantOf = function (mesh, names, hierarchyIds) {
  53837. for (var i in names) {
  53838. if (mesh.name === names[i]) {
  53839. hierarchyIds.push(mesh.id);
  53840. return true;
  53841. }
  53842. }
  53843. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  53844. hierarchyIds.push(mesh.id);
  53845. return true;
  53846. }
  53847. return false;
  53848. };
  53849. var logOperation = function (operation, producer) {
  53850. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  53851. };
  53852. BABYLON.SceneLoader.RegisterPlugin({
  53853. name: "babylon.js",
  53854. extensions: ".babylon",
  53855. canDirectLoad: function (data) {
  53856. if (data.indexOf("babylon") !== -1) {
  53857. return true;
  53858. }
  53859. return false;
  53860. },
  53861. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  53862. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  53863. // when SceneLoader.debugLogging = true (default), or exception encountered.
  53864. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  53865. // and avoid problems with multiple concurrent .babylon loads.
  53866. var log = "importMesh has failed JSON parse";
  53867. try {
  53868. var parsedData = JSON.parse(data);
  53869. log = "";
  53870. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  53871. if (!meshesNames) {
  53872. meshesNames = null;
  53873. }
  53874. else if (!Array.isArray(meshesNames)) {
  53875. meshesNames = [meshesNames];
  53876. }
  53877. var hierarchyIds = new Array();
  53878. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  53879. var loadedSkeletonsIds = [];
  53880. var loadedMaterialsIds = [];
  53881. var index;
  53882. var cache;
  53883. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  53884. var parsedMesh = parsedData.meshes[index];
  53885. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  53886. if (meshesNames !== null) {
  53887. // Remove found mesh name from list.
  53888. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  53889. }
  53890. //Geometry?
  53891. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  53892. //does the file contain geometries?
  53893. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  53894. //find the correct geometry and add it to the scene
  53895. var found = false;
  53896. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  53897. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  53898. return;
  53899. }
  53900. else {
  53901. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  53902. if (parsedGeometryData.id === parsedMesh.geometryId) {
  53903. switch (geometryType) {
  53904. case "boxes":
  53905. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  53906. break;
  53907. case "spheres":
  53908. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  53909. break;
  53910. case "cylinders":
  53911. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  53912. break;
  53913. case "toruses":
  53914. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  53915. break;
  53916. case "grounds":
  53917. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  53918. break;
  53919. case "planes":
  53920. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  53921. break;
  53922. case "torusKnots":
  53923. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  53924. break;
  53925. case "vertexData":
  53926. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  53927. break;
  53928. }
  53929. found = true;
  53930. }
  53931. });
  53932. }
  53933. });
  53934. if (found === false) {
  53935. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  53936. }
  53937. }
  53938. }
  53939. // Material ?
  53940. if (parsedMesh.materialId) {
  53941. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  53942. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  53943. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  53944. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  53945. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  53946. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  53947. var subMatId = parsedMultiMaterial.materials[matIndex];
  53948. loadedMaterialsIds.push(subMatId);
  53949. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  53950. log += "\n\tMaterial " + mat.toString(fullDetails);
  53951. }
  53952. loadedMaterialsIds.push(parsedMultiMaterial.id);
  53953. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  53954. materialFound = true;
  53955. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  53956. break;
  53957. }
  53958. }
  53959. }
  53960. if (materialFound === false) {
  53961. loadedMaterialsIds.push(parsedMesh.materialId);
  53962. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  53963. if (!mat) {
  53964. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  53965. }
  53966. else {
  53967. log += "\n\tMaterial " + mat.toString(fullDetails);
  53968. }
  53969. }
  53970. }
  53971. // Skeleton ?
  53972. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  53973. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  53974. if (skeletonAlreadyLoaded === false) {
  53975. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  53976. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  53977. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  53978. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  53979. skeletons.push(skeleton);
  53980. loadedSkeletonsIds.push(parsedSkeleton.id);
  53981. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  53982. }
  53983. }
  53984. }
  53985. }
  53986. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  53987. meshes.push(mesh);
  53988. log += "\n\tMesh " + mesh.toString(fullDetails);
  53989. }
  53990. }
  53991. // Connecting parents
  53992. var currentMesh;
  53993. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  53994. currentMesh = scene.meshes[index];
  53995. if (currentMesh._waitingParentId) {
  53996. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  53997. currentMesh._waitingParentId = null;
  53998. }
  53999. }
  54000. // freeze and compute world matrix application
  54001. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  54002. currentMesh = scene.meshes[index];
  54003. if (currentMesh._waitingFreezeWorldMatrix) {
  54004. currentMesh.freezeWorldMatrix();
  54005. currentMesh._waitingFreezeWorldMatrix = null;
  54006. }
  54007. else {
  54008. currentMesh.computeWorldMatrix(true);
  54009. }
  54010. }
  54011. }
  54012. // Particles
  54013. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  54014. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  54015. var parsedParticleSystem = parsedData.particleSystems[index];
  54016. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  54017. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  54018. }
  54019. }
  54020. }
  54021. return true;
  54022. }
  54023. catch (err) {
  54024. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  54025. if (onError) {
  54026. onError(msg, err);
  54027. }
  54028. else {
  54029. BABYLON.Tools.Log(msg);
  54030. throw err;
  54031. }
  54032. }
  54033. finally {
  54034. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  54035. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  54036. }
  54037. }
  54038. return false;
  54039. },
  54040. load: function (scene, data, rootUrl, onError) {
  54041. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  54042. // when SceneLoader.debugLogging = true (default), or exception encountered.
  54043. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  54044. // and avoid problems with multiple concurrent .babylon loads.
  54045. var log = "importScene has failed JSON parse";
  54046. try {
  54047. var parsedData = JSON.parse(data);
  54048. log = "";
  54049. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  54050. // Scene
  54051. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  54052. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  54053. }
  54054. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  54055. scene.autoClear = parsedData.autoClear;
  54056. }
  54057. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  54058. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  54059. }
  54060. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  54061. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  54062. }
  54063. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  54064. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  54065. }
  54066. // Fog
  54067. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  54068. scene.fogMode = parsedData.fogMode;
  54069. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  54070. scene.fogStart = parsedData.fogStart;
  54071. scene.fogEnd = parsedData.fogEnd;
  54072. scene.fogDensity = parsedData.fogDensity;
  54073. log += "\tFog mode for scene: ";
  54074. switch (scene.fogMode) {
  54075. // getters not compiling, so using hardcoded
  54076. case 1:
  54077. log += "exp\n";
  54078. break;
  54079. case 2:
  54080. log += "exp2\n";
  54081. break;
  54082. case 3:
  54083. log += "linear\n";
  54084. break;
  54085. }
  54086. }
  54087. //Physics
  54088. if (parsedData.physicsEnabled) {
  54089. var physicsPlugin;
  54090. if (parsedData.physicsEngine === "cannon") {
  54091. physicsPlugin = new BABYLON.CannonJSPlugin();
  54092. }
  54093. else if (parsedData.physicsEngine === "oimo") {
  54094. physicsPlugin = new BABYLON.OimoJSPlugin();
  54095. }
  54096. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  54097. //else - default engine, which is currently oimo
  54098. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  54099. scene.enablePhysics(physicsGravity, physicsPlugin);
  54100. }
  54101. // Metadata
  54102. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  54103. scene.metadata = parsedData.metadata;
  54104. }
  54105. //collisions, if defined. otherwise, default is true
  54106. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  54107. scene.collisionsEnabled = parsedData.collisionsEnabled;
  54108. }
  54109. scene.workerCollisions = !!parsedData.workerCollisions;
  54110. var index;
  54111. var cache;
  54112. // Lights
  54113. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  54114. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  54115. var parsedLight = parsedData.lights[index];
  54116. var light = BABYLON.Light.Parse(parsedLight, scene);
  54117. if (light) {
  54118. log += (index === 0 ? "\n\tLights:" : "");
  54119. log += "\n\t\t" + light.toString(fullDetails);
  54120. }
  54121. }
  54122. }
  54123. // Animations
  54124. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  54125. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  54126. var parsedAnimation = parsedData.animations[index];
  54127. var animation = BABYLON.Animation.Parse(parsedAnimation);
  54128. scene.animations.push(animation);
  54129. log += (index === 0 ? "\n\tAnimations:" : "");
  54130. log += "\n\t\t" + animation.toString(fullDetails);
  54131. }
  54132. }
  54133. if (parsedData.autoAnimate) {
  54134. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  54135. }
  54136. // Materials
  54137. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  54138. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  54139. var parsedMaterial = parsedData.materials[index];
  54140. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  54141. log += (index === 0 ? "\n\tMaterials:" : "");
  54142. log += "\n\t\t" + mat.toString(fullDetails);
  54143. }
  54144. }
  54145. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  54146. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  54147. var parsedMultiMaterial = parsedData.multiMaterials[index];
  54148. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  54149. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  54150. log += "\n\t\t" + mmat.toString(fullDetails);
  54151. }
  54152. }
  54153. // Morph targets
  54154. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  54155. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  54156. var managerData = _a[_i];
  54157. BABYLON.MorphTargetManager.Parse(managerData, scene);
  54158. }
  54159. }
  54160. // Skeletons
  54161. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  54162. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  54163. var parsedSkeleton = parsedData.skeletons[index];
  54164. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  54165. log += (index === 0 ? "\n\tSkeletons:" : "");
  54166. log += "\n\t\t" + skeleton.toString(fullDetails);
  54167. }
  54168. }
  54169. // Geometries
  54170. var geometries = parsedData.geometries;
  54171. if (geometries !== undefined && geometries !== null) {
  54172. // Boxes
  54173. var boxes = geometries.boxes;
  54174. if (boxes !== undefined && boxes !== null) {
  54175. for (index = 0, cache = boxes.length; index < cache; index++) {
  54176. var parsedBox = boxes[index];
  54177. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  54178. }
  54179. }
  54180. // Spheres
  54181. var spheres = geometries.spheres;
  54182. if (spheres !== undefined && spheres !== null) {
  54183. for (index = 0, cache = spheres.length; index < cache; index++) {
  54184. var parsedSphere = spheres[index];
  54185. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  54186. }
  54187. }
  54188. // Cylinders
  54189. var cylinders = geometries.cylinders;
  54190. if (cylinders !== undefined && cylinders !== null) {
  54191. for (index = 0, cache = cylinders.length; index < cache; index++) {
  54192. var parsedCylinder = cylinders[index];
  54193. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  54194. }
  54195. }
  54196. // Toruses
  54197. var toruses = geometries.toruses;
  54198. if (toruses !== undefined && toruses !== null) {
  54199. for (index = 0, cache = toruses.length; index < cache; index++) {
  54200. var parsedTorus = toruses[index];
  54201. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  54202. }
  54203. }
  54204. // Grounds
  54205. var grounds = geometries.grounds;
  54206. if (grounds !== undefined && grounds !== null) {
  54207. for (index = 0, cache = grounds.length; index < cache; index++) {
  54208. var parsedGround = grounds[index];
  54209. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  54210. }
  54211. }
  54212. // Planes
  54213. var planes = geometries.planes;
  54214. if (planes !== undefined && planes !== null) {
  54215. for (index = 0, cache = planes.length; index < cache; index++) {
  54216. var parsedPlane = planes[index];
  54217. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  54218. }
  54219. }
  54220. // TorusKnots
  54221. var torusKnots = geometries.torusKnots;
  54222. if (torusKnots !== undefined && torusKnots !== null) {
  54223. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  54224. var parsedTorusKnot = torusKnots[index];
  54225. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  54226. }
  54227. }
  54228. // VertexData
  54229. var vertexData = geometries.vertexData;
  54230. if (vertexData !== undefined && vertexData !== null) {
  54231. for (index = 0, cache = vertexData.length; index < cache; index++) {
  54232. var parsedVertexData = vertexData[index];
  54233. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  54234. }
  54235. }
  54236. }
  54237. // Transform nodes
  54238. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  54239. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  54240. var parsedTransformNode = parsedData.transformNodes[index];
  54241. BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  54242. }
  54243. }
  54244. // Meshes
  54245. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  54246. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  54247. var parsedMesh = parsedData.meshes[index];
  54248. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  54249. log += (index === 0 ? "\n\tMeshes:" : "");
  54250. log += "\n\t\t" + mesh.toString(fullDetails);
  54251. }
  54252. }
  54253. // Cameras
  54254. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  54255. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  54256. var parsedCamera = parsedData.cameras[index];
  54257. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  54258. log += (index === 0 ? "\n\tCameras:" : "");
  54259. log += "\n\t\t" + camera.toString(fullDetails);
  54260. }
  54261. }
  54262. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  54263. scene.setActiveCameraByID(parsedData.activeCameraID);
  54264. }
  54265. // Browsing all the graph to connect the dots
  54266. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  54267. var camera = scene.cameras[index];
  54268. if (camera._waitingParentId) {
  54269. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  54270. camera._waitingParentId = null;
  54271. }
  54272. }
  54273. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  54274. var light_1 = scene.lights[index];
  54275. if (light_1 && light_1._waitingParentId) {
  54276. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  54277. light_1._waitingParentId = null;
  54278. }
  54279. }
  54280. // Sounds
  54281. var loadedSounds = [];
  54282. var loadedSound;
  54283. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  54284. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  54285. var parsedSound = parsedData.sounds[index];
  54286. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  54287. if (!parsedSound.url)
  54288. parsedSound.url = parsedSound.name;
  54289. if (!loadedSounds[parsedSound.url]) {
  54290. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  54291. loadedSounds[parsedSound.url] = loadedSound;
  54292. }
  54293. else {
  54294. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  54295. }
  54296. }
  54297. else {
  54298. new BABYLON.Sound(parsedSound.name, null, scene);
  54299. }
  54300. }
  54301. }
  54302. loadedSounds = [];
  54303. // Connect parents & children and parse actions
  54304. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  54305. var transformNode = scene.transformNodes[index];
  54306. if (transformNode._waitingParentId) {
  54307. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  54308. transformNode._waitingParentId = null;
  54309. }
  54310. }
  54311. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  54312. var mesh = scene.meshes[index];
  54313. if (mesh._waitingParentId) {
  54314. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  54315. mesh._waitingParentId = null;
  54316. }
  54317. if (mesh._waitingActions) {
  54318. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  54319. mesh._waitingActions = null;
  54320. }
  54321. }
  54322. // freeze world matrix application
  54323. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  54324. var currentMesh = scene.meshes[index];
  54325. if (currentMesh._waitingFreezeWorldMatrix) {
  54326. currentMesh.freezeWorldMatrix();
  54327. currentMesh._waitingFreezeWorldMatrix = null;
  54328. }
  54329. else {
  54330. currentMesh.computeWorldMatrix(true);
  54331. }
  54332. }
  54333. // Particles Systems
  54334. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  54335. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  54336. var parsedParticleSystem = parsedData.particleSystems[index];
  54337. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  54338. }
  54339. }
  54340. // Environment texture
  54341. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  54342. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  54343. if (parsedData.createDefaultSkybox === true) {
  54344. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  54345. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  54346. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  54347. }
  54348. }
  54349. // Lens flares
  54350. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  54351. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  54352. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  54353. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  54354. }
  54355. }
  54356. // Shadows
  54357. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  54358. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  54359. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  54360. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  54361. }
  54362. }
  54363. // Lights exclusions / inclusions
  54364. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  54365. var light_2 = scene.lights[index];
  54366. // Excluded check
  54367. if (light_2._excludedMeshesIds.length > 0) {
  54368. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  54369. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  54370. if (excludedMesh) {
  54371. light_2.excludedMeshes.push(excludedMesh);
  54372. }
  54373. }
  54374. light_2._excludedMeshesIds = [];
  54375. }
  54376. // Included check
  54377. if (light_2._includedOnlyMeshesIds.length > 0) {
  54378. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  54379. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  54380. if (includedOnlyMesh) {
  54381. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  54382. }
  54383. }
  54384. light_2._includedOnlyMeshesIds = [];
  54385. }
  54386. }
  54387. // Actions (scene)
  54388. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  54389. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  54390. }
  54391. // Finish
  54392. return true;
  54393. }
  54394. catch (err) {
  54395. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  54396. if (onError) {
  54397. onError(msg, err);
  54398. }
  54399. else {
  54400. BABYLON.Tools.Log(msg);
  54401. throw err;
  54402. }
  54403. }
  54404. finally {
  54405. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  54406. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  54407. }
  54408. }
  54409. return false;
  54410. }
  54411. });
  54412. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  54413. })(BABYLON || (BABYLON = {}));
  54414. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  54415. var BABYLON;
  54416. (function (BABYLON) {
  54417. var FilesInput = /** @class */ (function () {
  54418. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  54419. this.onProcessFileCallback = function () { return true; };
  54420. this._engine = engine;
  54421. this._currentScene = scene;
  54422. this._sceneLoadedCallback = sceneLoadedCallback;
  54423. this._progressCallback = progressCallback;
  54424. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  54425. this._textureLoadingCallback = textureLoadingCallback;
  54426. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  54427. this._onReloadCallback = onReloadCallback;
  54428. this._errorCallback = errorCallback;
  54429. }
  54430. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  54431. var _this = this;
  54432. if (elementToMonitor) {
  54433. this._elementToMonitor = elementToMonitor;
  54434. this._dragEnterHandler = function (e) { _this.drag(e); };
  54435. this._dragOverHandler = function (e) { _this.drag(e); };
  54436. this._dropHandler = function (e) { _this.drop(e); };
  54437. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  54438. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  54439. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  54440. }
  54441. };
  54442. FilesInput.prototype.dispose = function () {
  54443. if (!this._elementToMonitor) {
  54444. return;
  54445. }
  54446. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  54447. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  54448. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  54449. };
  54450. FilesInput.prototype.renderFunction = function () {
  54451. if (this._additionalRenderLoopLogicCallback) {
  54452. this._additionalRenderLoopLogicCallback();
  54453. }
  54454. if (this._currentScene) {
  54455. if (this._textureLoadingCallback) {
  54456. var remaining = this._currentScene.getWaitingItemsCount();
  54457. if (remaining > 0) {
  54458. this._textureLoadingCallback(remaining);
  54459. }
  54460. }
  54461. this._currentScene.render();
  54462. }
  54463. };
  54464. FilesInput.prototype.drag = function (e) {
  54465. e.stopPropagation();
  54466. e.preventDefault();
  54467. };
  54468. FilesInput.prototype.drop = function (eventDrop) {
  54469. eventDrop.stopPropagation();
  54470. eventDrop.preventDefault();
  54471. this.loadFiles(eventDrop);
  54472. };
  54473. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  54474. var _this = this;
  54475. var reader = folder.createReader();
  54476. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  54477. reader.readEntries(function (entries) {
  54478. remaining.count += entries.length;
  54479. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  54480. var entry = entries_1[_i];
  54481. if (entry.isFile) {
  54482. entry.file(function (file) {
  54483. file.correctName = relativePath + file.name;
  54484. files.push(file);
  54485. if (--remaining.count === 0) {
  54486. callback();
  54487. }
  54488. });
  54489. }
  54490. else if (entry.isDirectory) {
  54491. _this._traverseFolder(entry, files, remaining, callback);
  54492. }
  54493. }
  54494. if (--remaining.count) {
  54495. callback();
  54496. }
  54497. });
  54498. };
  54499. FilesInput.prototype._processFiles = function (files) {
  54500. for (var i = 0; i < files.length; i++) {
  54501. var name = files[i].correctName.toLowerCase();
  54502. var extension = name.split('.').pop();
  54503. if (!this.onProcessFileCallback(files[i], name, extension)) {
  54504. continue;
  54505. }
  54506. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  54507. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  54508. this._sceneFileToLoad = files[i];
  54509. }
  54510. else {
  54511. FilesInput.FilesToLoad[name] = files[i];
  54512. }
  54513. }
  54514. };
  54515. FilesInput.prototype.loadFiles = function (event) {
  54516. var _this = this;
  54517. if (this._startingProcessingFilesCallback)
  54518. this._startingProcessingFilesCallback();
  54519. // Handling data transfer via drag'n'drop
  54520. if (event && event.dataTransfer && event.dataTransfer.files) {
  54521. this._filesToLoad = event.dataTransfer.files;
  54522. }
  54523. // Handling files from input files
  54524. if (event && event.target && event.target.files) {
  54525. this._filesToLoad = event.target.files;
  54526. }
  54527. if (this._filesToLoad && this._filesToLoad.length > 0) {
  54528. var files_1 = new Array();
  54529. var folders = [];
  54530. var items = event.dataTransfer ? event.dataTransfer.items : null;
  54531. for (var i = 0; i < this._filesToLoad.length; i++) {
  54532. var fileToLoad = this._filesToLoad[i];
  54533. var name_1 = fileToLoad.name.toLowerCase();
  54534. var entry = void 0;
  54535. fileToLoad.correctName = name_1;
  54536. if (items) {
  54537. var item = items[i];
  54538. if (item.getAsEntry) {
  54539. entry = item.getAsEntry();
  54540. }
  54541. else if (item.webkitGetAsEntry) {
  54542. entry = item.webkitGetAsEntry();
  54543. }
  54544. }
  54545. if (!entry) {
  54546. files_1.push(fileToLoad);
  54547. }
  54548. else {
  54549. if (entry.isDirectory) {
  54550. folders.push(entry);
  54551. }
  54552. else {
  54553. files_1.push(fileToLoad);
  54554. }
  54555. }
  54556. }
  54557. if (folders.length === 0) {
  54558. this._processFiles(files_1);
  54559. this._processReload();
  54560. }
  54561. else {
  54562. var remaining = { count: folders.length };
  54563. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  54564. var folder = folders_1[_i];
  54565. this._traverseFolder(folder, files_1, remaining, function () {
  54566. _this._processFiles(files_1);
  54567. if (remaining.count === 0) {
  54568. _this._processReload();
  54569. }
  54570. });
  54571. }
  54572. }
  54573. }
  54574. };
  54575. FilesInput.prototype._processReload = function () {
  54576. if (this._onReloadCallback) {
  54577. this._onReloadCallback(this._sceneFileToLoad);
  54578. }
  54579. else {
  54580. this.reload();
  54581. }
  54582. };
  54583. FilesInput.prototype.reload = function () {
  54584. var _this = this;
  54585. // If a scene file has been provided
  54586. if (this._sceneFileToLoad) {
  54587. if (this._currentScene) {
  54588. if (BABYLON.Tools.errorsCount > 0) {
  54589. BABYLON.Tools.ClearLogCache();
  54590. }
  54591. this._engine.stopRenderLoop();
  54592. this._currentScene.dispose();
  54593. }
  54594. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  54595. _this._currentScene = newScene;
  54596. if (_this._sceneLoadedCallback) {
  54597. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  54598. }
  54599. // Wait for textures and shaders to be ready
  54600. _this._currentScene.executeWhenReady(function () {
  54601. _this._engine.runRenderLoop(function () {
  54602. _this.renderFunction();
  54603. });
  54604. });
  54605. }, function (progress) {
  54606. if (_this._progressCallback) {
  54607. _this._progressCallback(progress);
  54608. }
  54609. }, function (scene, message) {
  54610. _this._currentScene = scene;
  54611. if (_this._errorCallback) {
  54612. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  54613. }
  54614. });
  54615. }
  54616. else {
  54617. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  54618. }
  54619. };
  54620. FilesInput.FilesToLoad = {};
  54621. return FilesInput;
  54622. }());
  54623. BABYLON.FilesInput = FilesInput;
  54624. })(BABYLON || (BABYLON = {}));
  54625. //# sourceMappingURL=babylon.filesInput.js.map
  54626. var BABYLON;
  54627. (function (BABYLON) {
  54628. /**
  54629. * This class implement a typical dictionary using a string as key and the generic type T as value.
  54630. * The underlying implementation relies on an associative array to ensure the best performances.
  54631. * The value can be anything including 'null' but except 'undefined'
  54632. */
  54633. var StringDictionary = /** @class */ (function () {
  54634. function StringDictionary() {
  54635. this._count = 0;
  54636. this._data = {};
  54637. }
  54638. /**
  54639. * This will clear this dictionary and copy the content from the 'source' one.
  54640. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  54641. * @param source the dictionary to take the content from and copy to this dictionary
  54642. */
  54643. StringDictionary.prototype.copyFrom = function (source) {
  54644. var _this = this;
  54645. this.clear();
  54646. source.forEach(function (t, v) { return _this.add(t, v); });
  54647. };
  54648. /**
  54649. * Get a value based from its key
  54650. * @param key the given key to get the matching value from
  54651. * @return the value if found, otherwise undefined is returned
  54652. */
  54653. StringDictionary.prototype.get = function (key) {
  54654. var val = this._data[key];
  54655. if (val !== undefined) {
  54656. return val;
  54657. }
  54658. return undefined;
  54659. };
  54660. /**
  54661. * Get a value from its key or add it if it doesn't exist.
  54662. * This method will ensure you that a given key/data will be present in the dictionary.
  54663. * @param key the given key to get the matching value from
  54664. * @param factory the factory that will create the value if the key is not present in the dictionary.
  54665. * The factory will only be invoked if there's no data for the given key.
  54666. * @return the value corresponding to the key.
  54667. */
  54668. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  54669. var val = this.get(key);
  54670. if (val !== undefined) {
  54671. return val;
  54672. }
  54673. val = factory(key);
  54674. if (val) {
  54675. this.add(key, val);
  54676. }
  54677. return val;
  54678. };
  54679. /**
  54680. * Get a value from its key if present in the dictionary otherwise add it
  54681. * @param key the key to get the value from
  54682. * @param val if there's no such key/value pair in the dictionary add it with this value
  54683. * @return the value corresponding to the key
  54684. */
  54685. StringDictionary.prototype.getOrAdd = function (key, val) {
  54686. var curVal = this.get(key);
  54687. if (curVal !== undefined) {
  54688. return curVal;
  54689. }
  54690. this.add(key, val);
  54691. return val;
  54692. };
  54693. /**
  54694. * Check if there's a given key in the dictionary
  54695. * @param key the key to check for
  54696. * @return true if the key is present, false otherwise
  54697. */
  54698. StringDictionary.prototype.contains = function (key) {
  54699. return this._data[key] !== undefined;
  54700. };
  54701. /**
  54702. * Add a new key and its corresponding value
  54703. * @param key the key to add
  54704. * @param value the value corresponding to the key
  54705. * @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
  54706. */
  54707. StringDictionary.prototype.add = function (key, value) {
  54708. if (this._data[key] !== undefined) {
  54709. return false;
  54710. }
  54711. this._data[key] = value;
  54712. ++this._count;
  54713. return true;
  54714. };
  54715. StringDictionary.prototype.set = function (key, value) {
  54716. if (this._data[key] === undefined) {
  54717. return false;
  54718. }
  54719. this._data[key] = value;
  54720. return true;
  54721. };
  54722. /**
  54723. * Get the element of the given key and remove it from the dictionary
  54724. * @param key
  54725. */
  54726. StringDictionary.prototype.getAndRemove = function (key) {
  54727. var val = this.get(key);
  54728. if (val !== undefined) {
  54729. delete this._data[key];
  54730. --this._count;
  54731. return val;
  54732. }
  54733. return null;
  54734. };
  54735. /**
  54736. * Remove a key/value from the dictionary.
  54737. * @param key the key to remove
  54738. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  54739. */
  54740. StringDictionary.prototype.remove = function (key) {
  54741. if (this.contains(key)) {
  54742. delete this._data[key];
  54743. --this._count;
  54744. return true;
  54745. }
  54746. return false;
  54747. };
  54748. /**
  54749. * Clear the whole content of the dictionary
  54750. */
  54751. StringDictionary.prototype.clear = function () {
  54752. this._data = {};
  54753. this._count = 0;
  54754. };
  54755. Object.defineProperty(StringDictionary.prototype, "count", {
  54756. get: function () {
  54757. return this._count;
  54758. },
  54759. enumerable: true,
  54760. configurable: true
  54761. });
  54762. /**
  54763. * Execute a callback on each key/val of the dictionary.
  54764. * Note that you can remove any element in this dictionary in the callback implementation
  54765. * @param callback the callback to execute on a given key/value pair
  54766. */
  54767. StringDictionary.prototype.forEach = function (callback) {
  54768. for (var cur in this._data) {
  54769. var val = this._data[cur];
  54770. callback(cur, val);
  54771. }
  54772. };
  54773. /**
  54774. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  54775. * If the callback returns null or undefined the method will iterate to the next key/value pair
  54776. * Note that you can remove any element in this dictionary in the callback implementation
  54777. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  54778. */
  54779. StringDictionary.prototype.first = function (callback) {
  54780. for (var cur in this._data) {
  54781. var val = this._data[cur];
  54782. var res = callback(cur, val);
  54783. if (res) {
  54784. return res;
  54785. }
  54786. }
  54787. return null;
  54788. };
  54789. return StringDictionary;
  54790. }());
  54791. BABYLON.StringDictionary = StringDictionary;
  54792. })(BABYLON || (BABYLON = {}));
  54793. //# sourceMappingURL=babylon.stringDictionary.js.map
  54794. var BABYLON;
  54795. (function (BABYLON) {
  54796. var Tags = /** @class */ (function () {
  54797. function Tags() {
  54798. }
  54799. Tags.EnableFor = function (obj) {
  54800. obj._tags = obj._tags || {};
  54801. obj.hasTags = function () {
  54802. return Tags.HasTags(obj);
  54803. };
  54804. obj.addTags = function (tagsString) {
  54805. return Tags.AddTagsTo(obj, tagsString);
  54806. };
  54807. obj.removeTags = function (tagsString) {
  54808. return Tags.RemoveTagsFrom(obj, tagsString);
  54809. };
  54810. obj.matchesTagsQuery = function (tagsQuery) {
  54811. return Tags.MatchesQuery(obj, tagsQuery);
  54812. };
  54813. };
  54814. Tags.DisableFor = function (obj) {
  54815. delete obj._tags;
  54816. delete obj.hasTags;
  54817. delete obj.addTags;
  54818. delete obj.removeTags;
  54819. delete obj.matchesTagsQuery;
  54820. };
  54821. Tags.HasTags = function (obj) {
  54822. if (!obj._tags) {
  54823. return false;
  54824. }
  54825. return !BABYLON.Tools.IsEmpty(obj._tags);
  54826. };
  54827. Tags.GetTags = function (obj, asString) {
  54828. if (asString === void 0) { asString = true; }
  54829. if (!obj._tags) {
  54830. return null;
  54831. }
  54832. if (asString) {
  54833. var tagsArray = [];
  54834. for (var tag in obj._tags) {
  54835. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  54836. tagsArray.push(tag);
  54837. }
  54838. }
  54839. return tagsArray.join(" ");
  54840. }
  54841. else {
  54842. return obj._tags;
  54843. }
  54844. };
  54845. // the tags 'true' and 'false' are reserved and cannot be used as tags
  54846. // a tag cannot start with '||', '&&', and '!'
  54847. // it cannot contain whitespaces
  54848. Tags.AddTagsTo = function (obj, tagsString) {
  54849. if (!tagsString) {
  54850. return;
  54851. }
  54852. if (typeof tagsString !== "string") {
  54853. return;
  54854. }
  54855. var tags = tagsString.split(" ");
  54856. tags.forEach(function (tag, index, array) {
  54857. Tags._AddTagTo(obj, tag);
  54858. });
  54859. };
  54860. Tags._AddTagTo = function (obj, tag) {
  54861. tag = tag.trim();
  54862. if (tag === "" || tag === "true" || tag === "false") {
  54863. return;
  54864. }
  54865. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  54866. return;
  54867. }
  54868. Tags.EnableFor(obj);
  54869. obj._tags[tag] = true;
  54870. };
  54871. Tags.RemoveTagsFrom = function (obj, tagsString) {
  54872. if (!Tags.HasTags(obj)) {
  54873. return;
  54874. }
  54875. var tags = tagsString.split(" ");
  54876. for (var t in tags) {
  54877. Tags._RemoveTagFrom(obj, tags[t]);
  54878. }
  54879. };
  54880. Tags._RemoveTagFrom = function (obj, tag) {
  54881. delete obj._tags[tag];
  54882. };
  54883. Tags.MatchesQuery = function (obj, tagsQuery) {
  54884. if (tagsQuery === undefined) {
  54885. return true;
  54886. }
  54887. if (tagsQuery === "") {
  54888. return Tags.HasTags(obj);
  54889. }
  54890. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  54891. };
  54892. return Tags;
  54893. }());
  54894. BABYLON.Tags = Tags;
  54895. })(BABYLON || (BABYLON = {}));
  54896. //# sourceMappingURL=babylon.tags.js.map
  54897. var BABYLON;
  54898. (function (BABYLON) {
  54899. var Internals;
  54900. (function (Internals) {
  54901. var AndOrNotEvaluator = /** @class */ (function () {
  54902. function AndOrNotEvaluator() {
  54903. }
  54904. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  54905. if (!query.match(/\([^\(\)]*\)/g)) {
  54906. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  54907. }
  54908. else {
  54909. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  54910. // remove parenthesis
  54911. r = r.slice(1, r.length - 1);
  54912. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  54913. });
  54914. }
  54915. if (query === "true") {
  54916. return true;
  54917. }
  54918. if (query === "false") {
  54919. return false;
  54920. }
  54921. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  54922. };
  54923. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  54924. evaluateCallback = evaluateCallback || (function (r) {
  54925. return r === "true" ? true : false;
  54926. });
  54927. var result;
  54928. var or = parenthesisContent.split("||");
  54929. for (var i in or) {
  54930. if (or.hasOwnProperty(i)) {
  54931. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  54932. var and = ori.split("&&");
  54933. if (and.length > 1) {
  54934. for (var j = 0; j < and.length; ++j) {
  54935. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  54936. if (andj !== "true" && andj !== "false") {
  54937. if (andj[0] === "!") {
  54938. result = !evaluateCallback(andj.substring(1));
  54939. }
  54940. else {
  54941. result = evaluateCallback(andj);
  54942. }
  54943. }
  54944. else {
  54945. result = andj === "true" ? true : false;
  54946. }
  54947. if (!result) {
  54948. ori = "false";
  54949. break;
  54950. }
  54951. }
  54952. }
  54953. if (result || ori === "true") {
  54954. result = true;
  54955. break;
  54956. }
  54957. // result equals false (or undefined)
  54958. if (ori !== "true" && ori !== "false") {
  54959. if (ori[0] === "!") {
  54960. result = !evaluateCallback(ori.substring(1));
  54961. }
  54962. else {
  54963. result = evaluateCallback(ori);
  54964. }
  54965. }
  54966. else {
  54967. result = ori === "true" ? true : false;
  54968. }
  54969. }
  54970. }
  54971. // the whole parenthesis scope is replaced by 'true' or 'false'
  54972. return result ? "true" : "false";
  54973. };
  54974. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  54975. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  54976. // remove whitespaces
  54977. r = r.replace(/[\s]/g, function () { return ""; });
  54978. return r.length % 2 ? "!" : "";
  54979. });
  54980. booleanString = booleanString.trim();
  54981. if (booleanString === "!true") {
  54982. booleanString = "false";
  54983. }
  54984. else if (booleanString === "!false") {
  54985. booleanString = "true";
  54986. }
  54987. return booleanString;
  54988. };
  54989. return AndOrNotEvaluator;
  54990. }());
  54991. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  54992. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  54993. })(BABYLON || (BABYLON = {}));
  54994. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  54995. var BABYLON;
  54996. (function (BABYLON) {
  54997. var Database = /** @class */ (function () {
  54998. function Database(urlToScene, callbackManifestChecked) {
  54999. // Handling various flavors of prefixed version of IndexedDB
  55000. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  55001. this.callbackManifestChecked = callbackManifestChecked;
  55002. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  55003. this.db = null;
  55004. this._enableSceneOffline = false;
  55005. this._enableTexturesOffline = false;
  55006. this.manifestVersionFound = 0;
  55007. this.mustUpdateRessources = false;
  55008. this.hasReachedQuota = false;
  55009. if (!Database.IDBStorageEnabled) {
  55010. this.callbackManifestChecked(true);
  55011. }
  55012. else {
  55013. this.checkManifestFile();
  55014. }
  55015. }
  55016. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  55017. get: function () {
  55018. return this._enableSceneOffline;
  55019. },
  55020. enumerable: true,
  55021. configurable: true
  55022. });
  55023. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  55024. get: function () {
  55025. return this._enableTexturesOffline;
  55026. },
  55027. enumerable: true,
  55028. configurable: true
  55029. });
  55030. Database.prototype.checkManifestFile = function () {
  55031. var _this = this;
  55032. var noManifestFile = function () {
  55033. _this._enableSceneOffline = false;
  55034. _this._enableTexturesOffline = false;
  55035. _this.callbackManifestChecked(false);
  55036. };
  55037. var timeStampUsed = false;
  55038. var manifestURL = this.currentSceneUrl + ".manifest";
  55039. var xhr = new XMLHttpRequest();
  55040. if (navigator.onLine) {
  55041. // Adding a timestamp to by-pass browsers' cache
  55042. timeStampUsed = true;
  55043. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  55044. }
  55045. xhr.open("GET", manifestURL, true);
  55046. xhr.addEventListener("load", function () {
  55047. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  55048. try {
  55049. var manifestFile = JSON.parse(xhr.response);
  55050. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  55051. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  55052. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  55053. _this.manifestVersionFound = manifestFile.version;
  55054. }
  55055. if (_this.callbackManifestChecked) {
  55056. _this.callbackManifestChecked(true);
  55057. }
  55058. }
  55059. catch (ex) {
  55060. noManifestFile();
  55061. }
  55062. }
  55063. else {
  55064. noManifestFile();
  55065. }
  55066. }, false);
  55067. xhr.addEventListener("error", function (event) {
  55068. if (timeStampUsed) {
  55069. timeStampUsed = false;
  55070. // Let's retry without the timeStamp
  55071. // It could fail when coupled with HTML5 Offline API
  55072. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  55073. xhr.open("GET", retryManifestURL, true);
  55074. xhr.send();
  55075. }
  55076. else {
  55077. noManifestFile();
  55078. }
  55079. }, false);
  55080. try {
  55081. xhr.send();
  55082. }
  55083. catch (ex) {
  55084. BABYLON.Tools.Error("Error on XHR send request.");
  55085. this.callbackManifestChecked(false);
  55086. }
  55087. };
  55088. Database.prototype.openAsync = function (successCallback, errorCallback) {
  55089. var _this = this;
  55090. var handleError = function () {
  55091. _this.isSupported = false;
  55092. if (errorCallback)
  55093. errorCallback();
  55094. };
  55095. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  55096. // Your browser doesn't support IndexedDB
  55097. this.isSupported = false;
  55098. if (errorCallback)
  55099. errorCallback();
  55100. }
  55101. else {
  55102. // If the DB hasn't been opened or created yet
  55103. if (!this.db) {
  55104. this.hasReachedQuota = false;
  55105. this.isSupported = true;
  55106. var request = this.idbFactory.open("babylonjs", 1);
  55107. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  55108. request.onerror = function (event) {
  55109. handleError();
  55110. };
  55111. // executes when a version change transaction cannot complete due to other active transactions
  55112. request.onblocked = function (event) {
  55113. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  55114. handleError();
  55115. };
  55116. // DB has been opened successfully
  55117. request.onsuccess = function (event) {
  55118. _this.db = request.result;
  55119. successCallback();
  55120. };
  55121. // Initialization of the DB. Creating Scenes & Textures stores
  55122. request.onupgradeneeded = function (event) {
  55123. _this.db = (event.target).result;
  55124. if (_this.db) {
  55125. try {
  55126. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  55127. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  55128. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  55129. }
  55130. catch (ex) {
  55131. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  55132. handleError();
  55133. }
  55134. }
  55135. };
  55136. }
  55137. else {
  55138. if (successCallback)
  55139. successCallback();
  55140. }
  55141. }
  55142. };
  55143. Database.prototype.loadImageFromDB = function (url, image) {
  55144. var _this = this;
  55145. var completeURL = Database.ReturnFullUrlLocation(url);
  55146. var saveAndLoadImage = function () {
  55147. if (!_this.hasReachedQuota && _this.db !== null) {
  55148. // the texture is not yet in the DB, let's try to save it
  55149. _this._saveImageIntoDBAsync(completeURL, image);
  55150. }
  55151. else {
  55152. image.src = url;
  55153. }
  55154. };
  55155. if (!this.mustUpdateRessources) {
  55156. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  55157. }
  55158. else {
  55159. saveAndLoadImage();
  55160. }
  55161. };
  55162. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  55163. if (this.isSupported && this.db !== null) {
  55164. var texture;
  55165. var transaction = this.db.transaction(["textures"]);
  55166. transaction.onabort = function (event) {
  55167. image.src = url;
  55168. };
  55169. transaction.oncomplete = function (event) {
  55170. var blobTextureURL;
  55171. if (texture) {
  55172. var URL = window.URL || window.webkitURL;
  55173. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  55174. image.onerror = function () {
  55175. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  55176. image.src = url;
  55177. };
  55178. image.src = blobTextureURL;
  55179. }
  55180. else {
  55181. notInDBCallback();
  55182. }
  55183. };
  55184. var getRequest = transaction.objectStore("textures").get(url);
  55185. getRequest.onsuccess = function (event) {
  55186. texture = (event.target).result;
  55187. };
  55188. getRequest.onerror = function (event) {
  55189. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  55190. image.src = url;
  55191. };
  55192. }
  55193. else {
  55194. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  55195. image.src = url;
  55196. }
  55197. };
  55198. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  55199. var _this = this;
  55200. if (this.isSupported) {
  55201. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  55202. var generateBlobUrl = function () {
  55203. var blobTextureURL;
  55204. if (blob) {
  55205. var URL = window.URL || window.webkitURL;
  55206. try {
  55207. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  55208. }
  55209. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  55210. catch (ex) {
  55211. blobTextureURL = URL.createObjectURL(blob);
  55212. }
  55213. }
  55214. if (blobTextureURL) {
  55215. image.src = blobTextureURL;
  55216. }
  55217. };
  55218. if (Database.IsUASupportingBlobStorage) {
  55219. var xhr = new XMLHttpRequest(), blob;
  55220. xhr.open("GET", url, true);
  55221. xhr.responseType = "blob";
  55222. xhr.addEventListener("load", function () {
  55223. if (xhr.status === 200 && _this.db) {
  55224. // Blob as response (XHR2)
  55225. blob = xhr.response;
  55226. var transaction = _this.db.transaction(["textures"], "readwrite");
  55227. // the transaction could abort because of a QuotaExceededError error
  55228. transaction.onabort = function (event) {
  55229. try {
  55230. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  55231. var srcElement = (event.srcElement || event.target);
  55232. var error = srcElement.error;
  55233. if (error && error.name === "QuotaExceededError") {
  55234. _this.hasReachedQuota = true;
  55235. }
  55236. }
  55237. catch (ex) { }
  55238. generateBlobUrl();
  55239. };
  55240. transaction.oncomplete = function (event) {
  55241. generateBlobUrl();
  55242. };
  55243. var newTexture = { textureUrl: url, data: blob };
  55244. try {
  55245. // Put the blob into the dabase
  55246. var addRequest = transaction.objectStore("textures").put(newTexture);
  55247. addRequest.onsuccess = function (event) {
  55248. };
  55249. addRequest.onerror = function (event) {
  55250. generateBlobUrl();
  55251. };
  55252. }
  55253. catch (ex) {
  55254. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  55255. if (ex.code === 25) {
  55256. Database.IsUASupportingBlobStorage = false;
  55257. }
  55258. image.src = url;
  55259. }
  55260. }
  55261. else {
  55262. image.src = url;
  55263. }
  55264. }, false);
  55265. xhr.addEventListener("error", function (event) {
  55266. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  55267. image.src = url;
  55268. }, false);
  55269. xhr.send();
  55270. }
  55271. else {
  55272. image.src = url;
  55273. }
  55274. }
  55275. else {
  55276. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  55277. image.src = url;
  55278. }
  55279. };
  55280. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  55281. var _this = this;
  55282. var updateVersion = function () {
  55283. // the version is not yet in the DB or we need to update it
  55284. _this._saveVersionIntoDBAsync(url, versionLoaded);
  55285. };
  55286. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  55287. };
  55288. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  55289. var _this = this;
  55290. if (this.isSupported && this.db) {
  55291. var version;
  55292. try {
  55293. var transaction = this.db.transaction(["versions"]);
  55294. transaction.oncomplete = function (event) {
  55295. if (version) {
  55296. // If the version in the JSON file is > than the version in DB
  55297. if (_this.manifestVersionFound > version.data) {
  55298. _this.mustUpdateRessources = true;
  55299. updateInDBCallback();
  55300. }
  55301. else {
  55302. callback(version.data);
  55303. }
  55304. }
  55305. else {
  55306. _this.mustUpdateRessources = true;
  55307. updateInDBCallback();
  55308. }
  55309. };
  55310. transaction.onabort = function (event) {
  55311. callback(-1);
  55312. };
  55313. var getRequest = transaction.objectStore("versions").get(url);
  55314. getRequest.onsuccess = function (event) {
  55315. version = (event.target).result;
  55316. };
  55317. getRequest.onerror = function (event) {
  55318. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  55319. callback(-1);
  55320. };
  55321. }
  55322. catch (ex) {
  55323. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  55324. callback(-1);
  55325. }
  55326. }
  55327. else {
  55328. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  55329. callback(-1);
  55330. }
  55331. };
  55332. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  55333. var _this = this;
  55334. if (this.isSupported && !this.hasReachedQuota && this.db) {
  55335. try {
  55336. // Open a transaction to the database
  55337. var transaction = this.db.transaction(["versions"], "readwrite");
  55338. // the transaction could abort because of a QuotaExceededError error
  55339. transaction.onabort = function (event) {
  55340. try {
  55341. var error = event.srcElement['error'];
  55342. if (error && error.name === "QuotaExceededError") {
  55343. _this.hasReachedQuota = true;
  55344. }
  55345. }
  55346. catch (ex) { }
  55347. callback(-1);
  55348. };
  55349. transaction.oncomplete = function (event) {
  55350. callback(_this.manifestVersionFound);
  55351. };
  55352. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  55353. // Put the scene into the database
  55354. var addRequest = transaction.objectStore("versions").put(newVersion);
  55355. addRequest.onsuccess = function (event) {
  55356. };
  55357. addRequest.onerror = function (event) {
  55358. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  55359. };
  55360. }
  55361. catch (ex) {
  55362. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  55363. callback(-1);
  55364. }
  55365. }
  55366. else {
  55367. callback(-1);
  55368. }
  55369. };
  55370. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  55371. var _this = this;
  55372. var completeUrl = Database.ReturnFullUrlLocation(url);
  55373. var saveAndLoadFile = function () {
  55374. // the scene is not yet in the DB, let's try to save it
  55375. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  55376. };
  55377. this._checkVersionFromDB(completeUrl, function (version) {
  55378. if (version !== -1) {
  55379. if (!_this.mustUpdateRessources) {
  55380. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  55381. }
  55382. else {
  55383. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  55384. }
  55385. }
  55386. else {
  55387. if (errorCallback) {
  55388. errorCallback();
  55389. }
  55390. }
  55391. });
  55392. };
  55393. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  55394. if (this.isSupported && this.db) {
  55395. var targetStore;
  55396. if (url.indexOf(".babylon") !== -1) {
  55397. targetStore = "scenes";
  55398. }
  55399. else {
  55400. targetStore = "textures";
  55401. }
  55402. var file;
  55403. var transaction = this.db.transaction([targetStore]);
  55404. transaction.oncomplete = function (event) {
  55405. if (file) {
  55406. callback(file.data);
  55407. }
  55408. else {
  55409. notInDBCallback();
  55410. }
  55411. };
  55412. transaction.onabort = function (event) {
  55413. notInDBCallback();
  55414. };
  55415. var getRequest = transaction.objectStore(targetStore).get(url);
  55416. getRequest.onsuccess = function (event) {
  55417. file = (event.target).result;
  55418. };
  55419. getRequest.onerror = function (event) {
  55420. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  55421. notInDBCallback();
  55422. };
  55423. }
  55424. else {
  55425. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  55426. callback();
  55427. }
  55428. };
  55429. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  55430. var _this = this;
  55431. if (this.isSupported) {
  55432. var targetStore;
  55433. if (url.indexOf(".babylon") !== -1) {
  55434. targetStore = "scenes";
  55435. }
  55436. else {
  55437. targetStore = "textures";
  55438. }
  55439. // Create XHR
  55440. var xhr = new XMLHttpRequest();
  55441. var fileData;
  55442. xhr.open("GET", url, true);
  55443. if (useArrayBuffer) {
  55444. xhr.responseType = "arraybuffer";
  55445. }
  55446. if (progressCallback) {
  55447. xhr.onprogress = progressCallback;
  55448. }
  55449. xhr.addEventListener("load", function () {
  55450. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  55451. // Blob as response (XHR2)
  55452. //fileData = xhr.responseText;
  55453. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  55454. if (!_this.hasReachedQuota && _this.db) {
  55455. // Open a transaction to the database
  55456. var transaction = _this.db.transaction([targetStore], "readwrite");
  55457. // the transaction could abort because of a QuotaExceededError error
  55458. transaction.onabort = function (event) {
  55459. try {
  55460. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  55461. var error = event.srcElement['error'];
  55462. if (error && error.name === "QuotaExceededError") {
  55463. _this.hasReachedQuota = true;
  55464. }
  55465. }
  55466. catch (ex) { }
  55467. callback(fileData);
  55468. };
  55469. transaction.oncomplete = function (event) {
  55470. callback(fileData);
  55471. };
  55472. var newFile;
  55473. if (targetStore === "scenes") {
  55474. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  55475. }
  55476. else {
  55477. newFile = { textureUrl: url, data: fileData };
  55478. }
  55479. try {
  55480. // Put the scene into the database
  55481. var addRequest = transaction.objectStore(targetStore).put(newFile);
  55482. addRequest.onsuccess = function (event) {
  55483. };
  55484. addRequest.onerror = function (event) {
  55485. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  55486. };
  55487. }
  55488. catch (ex) {
  55489. callback(fileData);
  55490. }
  55491. }
  55492. else {
  55493. callback(fileData);
  55494. }
  55495. }
  55496. else {
  55497. callback();
  55498. }
  55499. }, false);
  55500. xhr.addEventListener("error", function (event) {
  55501. BABYLON.Tools.Error("error on XHR request.");
  55502. callback();
  55503. }, false);
  55504. xhr.send();
  55505. }
  55506. else {
  55507. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  55508. callback();
  55509. }
  55510. };
  55511. Database.IsUASupportingBlobStorage = true;
  55512. Database.IDBStorageEnabled = true;
  55513. Database.parseURL = function (url) {
  55514. var a = document.createElement('a');
  55515. a.href = url;
  55516. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  55517. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  55518. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  55519. return absLocation;
  55520. };
  55521. Database.ReturnFullUrlLocation = function (url) {
  55522. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  55523. return (Database.parseURL(window.location.href) + url);
  55524. }
  55525. else {
  55526. return url;
  55527. }
  55528. };
  55529. return Database;
  55530. }());
  55531. BABYLON.Database = Database;
  55532. })(BABYLON || (BABYLON = {}));
  55533. //# sourceMappingURL=babylon.database.js.map
  55534. var BABYLON;
  55535. (function (BABYLON) {
  55536. var FresnelParameters = /** @class */ (function () {
  55537. function FresnelParameters() {
  55538. this._isEnabled = true;
  55539. this.leftColor = BABYLON.Color3.White();
  55540. this.rightColor = BABYLON.Color3.Black();
  55541. this.bias = 0;
  55542. this.power = 1;
  55543. }
  55544. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  55545. get: function () {
  55546. return this._isEnabled;
  55547. },
  55548. set: function (value) {
  55549. if (this._isEnabled === value) {
  55550. return;
  55551. }
  55552. this._isEnabled = value;
  55553. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  55554. },
  55555. enumerable: true,
  55556. configurable: true
  55557. });
  55558. FresnelParameters.prototype.clone = function () {
  55559. var newFresnelParameters = new FresnelParameters();
  55560. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  55561. return newFresnelParameters;
  55562. };
  55563. FresnelParameters.prototype.serialize = function () {
  55564. var serializationObject = {};
  55565. serializationObject.isEnabled = this.isEnabled;
  55566. serializationObject.leftColor = this.leftColor;
  55567. serializationObject.rightColor = this.rightColor;
  55568. serializationObject.bias = this.bias;
  55569. serializationObject.power = this.power;
  55570. return serializationObject;
  55571. };
  55572. FresnelParameters.Parse = function (parsedFresnelParameters) {
  55573. var fresnelParameters = new FresnelParameters();
  55574. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  55575. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  55576. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  55577. fresnelParameters.bias = parsedFresnelParameters.bias;
  55578. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  55579. return fresnelParameters;
  55580. };
  55581. return FresnelParameters;
  55582. }());
  55583. BABYLON.FresnelParameters = FresnelParameters;
  55584. })(BABYLON || (BABYLON = {}));
  55585. //# sourceMappingURL=babylon.fresnelParameters.js.map
  55586. var BABYLON;
  55587. (function (BABYLON) {
  55588. var MultiMaterial = /** @class */ (function (_super) {
  55589. __extends(MultiMaterial, _super);
  55590. function MultiMaterial(name, scene) {
  55591. var _this = _super.call(this, name, scene, true) || this;
  55592. scene.multiMaterials.push(_this);
  55593. _this.subMaterials = new Array();
  55594. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  55595. return _this;
  55596. }
  55597. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  55598. get: function () {
  55599. return this._subMaterials;
  55600. },
  55601. set: function (value) {
  55602. this._subMaterials = value;
  55603. this._hookArray(value);
  55604. },
  55605. enumerable: true,
  55606. configurable: true
  55607. });
  55608. MultiMaterial.prototype._hookArray = function (array) {
  55609. var _this = this;
  55610. var oldPush = array.push;
  55611. array.push = function () {
  55612. var items = [];
  55613. for (var _i = 0; _i < arguments.length; _i++) {
  55614. items[_i] = arguments[_i];
  55615. }
  55616. var result = oldPush.apply(array, items);
  55617. _this._markAllSubMeshesAsTexturesDirty();
  55618. return result;
  55619. };
  55620. var oldSplice = array.splice;
  55621. array.splice = function (index, deleteCount) {
  55622. var deleted = oldSplice.apply(array, [index, deleteCount]);
  55623. _this._markAllSubMeshesAsTexturesDirty();
  55624. return deleted;
  55625. };
  55626. };
  55627. // Properties
  55628. MultiMaterial.prototype.getSubMaterial = function (index) {
  55629. if (index < 0 || index >= this.subMaterials.length) {
  55630. return this.getScene().defaultMaterial;
  55631. }
  55632. return this.subMaterials[index];
  55633. };
  55634. MultiMaterial.prototype.getActiveTextures = function () {
  55635. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  55636. if (subMaterial) {
  55637. return subMaterial.getActiveTextures();
  55638. }
  55639. else {
  55640. return [];
  55641. }
  55642. }));
  55643. var _a;
  55644. };
  55645. // Methods
  55646. MultiMaterial.prototype.getClassName = function () {
  55647. return "MultiMaterial";
  55648. };
  55649. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  55650. for (var index = 0; index < this.subMaterials.length; index++) {
  55651. var subMaterial = this.subMaterials[index];
  55652. if (subMaterial) {
  55653. if (subMaterial.storeEffectOnSubMeshes) {
  55654. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  55655. return false;
  55656. }
  55657. continue;
  55658. }
  55659. if (!subMaterial.isReady(mesh)) {
  55660. return false;
  55661. }
  55662. }
  55663. }
  55664. return true;
  55665. };
  55666. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  55667. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  55668. for (var index = 0; index < this.subMaterials.length; index++) {
  55669. var subMaterial = null;
  55670. var current = this.subMaterials[index];
  55671. if (cloneChildren && current) {
  55672. subMaterial = current.clone(name + "-" + current.name);
  55673. }
  55674. else {
  55675. subMaterial = this.subMaterials[index];
  55676. }
  55677. newMultiMaterial.subMaterials.push(subMaterial);
  55678. }
  55679. return newMultiMaterial;
  55680. };
  55681. MultiMaterial.prototype.serialize = function () {
  55682. var serializationObject = {};
  55683. serializationObject.name = this.name;
  55684. serializationObject.id = this.id;
  55685. if (BABYLON.Tags) {
  55686. serializationObject.tags = BABYLON.Tags.GetTags(this);
  55687. }
  55688. serializationObject.materials = [];
  55689. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  55690. var subMat = this.subMaterials[matIndex];
  55691. if (subMat) {
  55692. serializationObject.materials.push(subMat.id);
  55693. }
  55694. else {
  55695. serializationObject.materials.push(null);
  55696. }
  55697. }
  55698. return serializationObject;
  55699. };
  55700. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  55701. var scene = this.getScene();
  55702. if (!scene) {
  55703. return;
  55704. }
  55705. var index = scene.multiMaterials.indexOf(this);
  55706. if (index >= 0) {
  55707. scene.multiMaterials.splice(index, 1);
  55708. }
  55709. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  55710. };
  55711. return MultiMaterial;
  55712. }(BABYLON.Material));
  55713. BABYLON.MultiMaterial = MultiMaterial;
  55714. })(BABYLON || (BABYLON = {}));
  55715. //# sourceMappingURL=babylon.multiMaterial.js.map
  55716. var BABYLON;
  55717. (function (BABYLON) {
  55718. var FreeCameraTouchInput = /** @class */ (function () {
  55719. function FreeCameraTouchInput() {
  55720. this._offsetX = null;
  55721. this._offsetY = null;
  55722. this._pointerPressed = new Array();
  55723. this.touchAngularSensibility = 200000.0;
  55724. this.touchMoveSensibility = 250.0;
  55725. }
  55726. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  55727. var _this = this;
  55728. var previousPosition = null;
  55729. if (this._pointerInput === undefined) {
  55730. this._onLostFocus = function (evt) {
  55731. _this._offsetX = null;
  55732. _this._offsetY = null;
  55733. };
  55734. this._pointerInput = function (p, s) {
  55735. var evt = p.event;
  55736. if (evt.pointerType === "mouse") {
  55737. return;
  55738. }
  55739. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  55740. if (!noPreventDefault) {
  55741. evt.preventDefault();
  55742. }
  55743. _this._pointerPressed.push(evt.pointerId);
  55744. if (_this._pointerPressed.length !== 1) {
  55745. return;
  55746. }
  55747. previousPosition = {
  55748. x: evt.clientX,
  55749. y: evt.clientY
  55750. };
  55751. }
  55752. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  55753. if (!noPreventDefault) {
  55754. evt.preventDefault();
  55755. }
  55756. var index = _this._pointerPressed.indexOf(evt.pointerId);
  55757. if (index === -1) {
  55758. return;
  55759. }
  55760. _this._pointerPressed.splice(index, 1);
  55761. if (index != 0) {
  55762. return;
  55763. }
  55764. previousPosition = null;
  55765. _this._offsetX = null;
  55766. _this._offsetY = null;
  55767. }
  55768. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  55769. if (!noPreventDefault) {
  55770. evt.preventDefault();
  55771. }
  55772. if (!previousPosition) {
  55773. return;
  55774. }
  55775. var index = _this._pointerPressed.indexOf(evt.pointerId);
  55776. if (index != 0) {
  55777. return;
  55778. }
  55779. _this._offsetX = evt.clientX - previousPosition.x;
  55780. _this._offsetY = -(evt.clientY - previousPosition.y);
  55781. }
  55782. };
  55783. }
  55784. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  55785. if (this._onLostFocus) {
  55786. element.addEventListener("blur", this._onLostFocus);
  55787. }
  55788. };
  55789. FreeCameraTouchInput.prototype.detachControl = function (element) {
  55790. if (this._pointerInput && element) {
  55791. if (this._observer) {
  55792. this.camera.getScene().onPointerObservable.remove(this._observer);
  55793. this._observer = null;
  55794. }
  55795. if (this._onLostFocus) {
  55796. element.removeEventListener("blur", this._onLostFocus);
  55797. this._onLostFocus = null;
  55798. }
  55799. this._pointerPressed = [];
  55800. this._offsetX = null;
  55801. this._offsetY = null;
  55802. }
  55803. };
  55804. FreeCameraTouchInput.prototype.checkInputs = function () {
  55805. if (this._offsetX && this._offsetY) {
  55806. var camera = this.camera;
  55807. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  55808. if (this._pointerPressed.length > 1) {
  55809. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  55810. }
  55811. else {
  55812. var speed = camera._computeLocalCameraSpeed();
  55813. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  55814. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  55815. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  55816. }
  55817. }
  55818. };
  55819. FreeCameraTouchInput.prototype.getClassName = function () {
  55820. return "FreeCameraTouchInput";
  55821. };
  55822. FreeCameraTouchInput.prototype.getSimpleName = function () {
  55823. return "touch";
  55824. };
  55825. __decorate([
  55826. BABYLON.serialize()
  55827. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  55828. __decorate([
  55829. BABYLON.serialize()
  55830. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  55831. return FreeCameraTouchInput;
  55832. }());
  55833. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  55834. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  55835. })(BABYLON || (BABYLON = {}));
  55836. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  55837. var BABYLON;
  55838. (function (BABYLON) {
  55839. // We're mainly based on the logic defined into the FreeCamera code
  55840. var TouchCamera = /** @class */ (function (_super) {
  55841. __extends(TouchCamera, _super);
  55842. //-- end properties for backward compatibility for inputs
  55843. function TouchCamera(name, position, scene) {
  55844. var _this = _super.call(this, name, position, scene) || this;
  55845. _this.inputs.addTouch();
  55846. _this._setupInputs();
  55847. return _this;
  55848. }
  55849. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  55850. //-- Begin properties for backward compatibility for inputs
  55851. get: function () {
  55852. var touch = this.inputs.attached["touch"];
  55853. if (touch)
  55854. return touch.touchAngularSensibility;
  55855. return 0;
  55856. },
  55857. set: function (value) {
  55858. var touch = this.inputs.attached["touch"];
  55859. if (touch)
  55860. touch.touchAngularSensibility = value;
  55861. },
  55862. enumerable: true,
  55863. configurable: true
  55864. });
  55865. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  55866. get: function () {
  55867. var touch = this.inputs.attached["touch"];
  55868. if (touch)
  55869. return touch.touchMoveSensibility;
  55870. return 0;
  55871. },
  55872. set: function (value) {
  55873. var touch = this.inputs.attached["touch"];
  55874. if (touch)
  55875. touch.touchMoveSensibility = value;
  55876. },
  55877. enumerable: true,
  55878. configurable: true
  55879. });
  55880. TouchCamera.prototype.getClassName = function () {
  55881. return "TouchCamera";
  55882. };
  55883. TouchCamera.prototype._setupInputs = function () {
  55884. var mouse = this.inputs.attached["mouse"];
  55885. if (mouse) {
  55886. mouse.touchEnabled = false;
  55887. }
  55888. };
  55889. return TouchCamera;
  55890. }(BABYLON.FreeCamera));
  55891. BABYLON.TouchCamera = TouchCamera;
  55892. })(BABYLON || (BABYLON = {}));
  55893. //# sourceMappingURL=babylon.touchCamera.js.map
  55894. var BABYLON;
  55895. (function (BABYLON) {
  55896. var ProceduralTexture = /** @class */ (function (_super) {
  55897. __extends(ProceduralTexture, _super);
  55898. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  55899. if (fallbackTexture === void 0) { fallbackTexture = null; }
  55900. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55901. if (isCube === void 0) { isCube = false; }
  55902. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  55903. _this.isCube = isCube;
  55904. _this.isEnabled = true;
  55905. _this._currentRefreshId = -1;
  55906. _this._refreshRate = 1;
  55907. _this._vertexBuffers = {};
  55908. _this._uniforms = new Array();
  55909. _this._samplers = new Array();
  55910. _this._textures = {};
  55911. _this._floats = {};
  55912. _this._floatsArrays = {};
  55913. _this._colors3 = {};
  55914. _this._colors4 = {};
  55915. _this._vectors2 = {};
  55916. _this._vectors3 = {};
  55917. _this._matrices = {};
  55918. _this._fallbackTextureUsed = false;
  55919. scene._proceduralTextures.push(_this);
  55920. _this._engine = scene.getEngine();
  55921. _this.name = name;
  55922. _this.isRenderTarget = true;
  55923. _this._size = size;
  55924. _this._generateMipMaps = generateMipMaps;
  55925. _this.setFragment(fragment);
  55926. _this._fallbackTexture = fallbackTexture;
  55927. if (isCube) {
  55928. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  55929. _this.setFloat("face", 0);
  55930. }
  55931. else {
  55932. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  55933. }
  55934. // VBO
  55935. var vertices = [];
  55936. vertices.push(1, 1);
  55937. vertices.push(-1, 1);
  55938. vertices.push(-1, -1);
  55939. vertices.push(1, -1);
  55940. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  55941. _this._createIndexBuffer();
  55942. return _this;
  55943. }
  55944. ProceduralTexture.prototype._createIndexBuffer = function () {
  55945. var engine = this._engine;
  55946. // Indices
  55947. var indices = [];
  55948. indices.push(0);
  55949. indices.push(1);
  55950. indices.push(2);
  55951. indices.push(0);
  55952. indices.push(2);
  55953. indices.push(3);
  55954. this._indexBuffer = engine.createIndexBuffer(indices);
  55955. };
  55956. ProceduralTexture.prototype._rebuild = function () {
  55957. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  55958. if (vb) {
  55959. vb._rebuild();
  55960. }
  55961. this._createIndexBuffer();
  55962. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  55963. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  55964. }
  55965. };
  55966. ProceduralTexture.prototype.reset = function () {
  55967. if (this._effect === undefined) {
  55968. return;
  55969. }
  55970. var engine = this._engine;
  55971. engine._releaseEffect(this._effect);
  55972. };
  55973. ProceduralTexture.prototype.isReady = function () {
  55974. var _this = this;
  55975. var engine = this._engine;
  55976. var shaders;
  55977. if (!this._fragment) {
  55978. return false;
  55979. }
  55980. if (this._fallbackTextureUsed) {
  55981. return true;
  55982. }
  55983. if (this._fragment.fragmentElement !== undefined) {
  55984. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  55985. }
  55986. else {
  55987. shaders = { vertex: "procedural", fragment: this._fragment };
  55988. }
  55989. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  55990. _this.releaseInternalTexture();
  55991. if (_this._fallbackTexture) {
  55992. _this._texture = _this._fallbackTexture._texture;
  55993. if (_this._texture) {
  55994. _this._texture.incrementReferences();
  55995. }
  55996. }
  55997. _this._fallbackTextureUsed = true;
  55998. });
  55999. return this._effect.isReady();
  56000. };
  56001. ProceduralTexture.prototype.resetRefreshCounter = function () {
  56002. this._currentRefreshId = -1;
  56003. };
  56004. ProceduralTexture.prototype.setFragment = function (fragment) {
  56005. this._fragment = fragment;
  56006. };
  56007. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  56008. get: function () {
  56009. return this._refreshRate;
  56010. },
  56011. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  56012. set: function (value) {
  56013. this._refreshRate = value;
  56014. this.resetRefreshCounter();
  56015. },
  56016. enumerable: true,
  56017. configurable: true
  56018. });
  56019. ProceduralTexture.prototype._shouldRender = function () {
  56020. if (!this.isEnabled || !this.isReady() || !this._texture) {
  56021. return false;
  56022. }
  56023. if (this._fallbackTextureUsed) {
  56024. return false;
  56025. }
  56026. if (this._currentRefreshId === -1) {
  56027. this._currentRefreshId = 1;
  56028. return true;
  56029. }
  56030. if (this.refreshRate === this._currentRefreshId) {
  56031. this._currentRefreshId = 1;
  56032. return true;
  56033. }
  56034. this._currentRefreshId++;
  56035. return false;
  56036. };
  56037. ProceduralTexture.prototype.getRenderSize = function () {
  56038. return this._size;
  56039. };
  56040. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  56041. if (this._fallbackTextureUsed) {
  56042. return;
  56043. }
  56044. this.releaseInternalTexture();
  56045. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  56046. };
  56047. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  56048. if (this._uniforms.indexOf(uniformName) === -1) {
  56049. this._uniforms.push(uniformName);
  56050. }
  56051. };
  56052. ProceduralTexture.prototype.setTexture = function (name, texture) {
  56053. if (this._samplers.indexOf(name) === -1) {
  56054. this._samplers.push(name);
  56055. }
  56056. this._textures[name] = texture;
  56057. return this;
  56058. };
  56059. ProceduralTexture.prototype.setFloat = function (name, value) {
  56060. this._checkUniform(name);
  56061. this._floats[name] = value;
  56062. return this;
  56063. };
  56064. ProceduralTexture.prototype.setFloats = function (name, value) {
  56065. this._checkUniform(name);
  56066. this._floatsArrays[name] = value;
  56067. return this;
  56068. };
  56069. ProceduralTexture.prototype.setColor3 = function (name, value) {
  56070. this._checkUniform(name);
  56071. this._colors3[name] = value;
  56072. return this;
  56073. };
  56074. ProceduralTexture.prototype.setColor4 = function (name, value) {
  56075. this._checkUniform(name);
  56076. this._colors4[name] = value;
  56077. return this;
  56078. };
  56079. ProceduralTexture.prototype.setVector2 = function (name, value) {
  56080. this._checkUniform(name);
  56081. this._vectors2[name] = value;
  56082. return this;
  56083. };
  56084. ProceduralTexture.prototype.setVector3 = function (name, value) {
  56085. this._checkUniform(name);
  56086. this._vectors3[name] = value;
  56087. return this;
  56088. };
  56089. ProceduralTexture.prototype.setMatrix = function (name, value) {
  56090. this._checkUniform(name);
  56091. this._matrices[name] = value;
  56092. return this;
  56093. };
  56094. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  56095. var scene = this.getScene();
  56096. if (!scene) {
  56097. return;
  56098. }
  56099. var engine = this._engine;
  56100. // Render
  56101. engine.enableEffect(this._effect);
  56102. engine.setState(false);
  56103. // Texture
  56104. for (var name in this._textures) {
  56105. this._effect.setTexture(name, this._textures[name]);
  56106. }
  56107. // Float
  56108. for (name in this._floats) {
  56109. this._effect.setFloat(name, this._floats[name]);
  56110. }
  56111. // Floats
  56112. for (name in this._floatsArrays) {
  56113. this._effect.setArray(name, this._floatsArrays[name]);
  56114. }
  56115. // Color3
  56116. for (name in this._colors3) {
  56117. this._effect.setColor3(name, this._colors3[name]);
  56118. }
  56119. // Color4
  56120. for (name in this._colors4) {
  56121. var color = this._colors4[name];
  56122. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  56123. }
  56124. // Vector2
  56125. for (name in this._vectors2) {
  56126. this._effect.setVector2(name, this._vectors2[name]);
  56127. }
  56128. // Vector3
  56129. for (name in this._vectors3) {
  56130. this._effect.setVector3(name, this._vectors3[name]);
  56131. }
  56132. // Matrix
  56133. for (name in this._matrices) {
  56134. this._effect.setMatrix(name, this._matrices[name]);
  56135. }
  56136. if (!this._texture) {
  56137. return;
  56138. }
  56139. if (this.isCube) {
  56140. for (var face = 0; face < 6; face++) {
  56141. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  56142. // VBOs
  56143. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  56144. this._effect.setFloat("face", face);
  56145. // Clear
  56146. engine.clear(scene.clearColor, true, true, true);
  56147. // Draw order
  56148. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  56149. // Mipmaps
  56150. if (face === 5) {
  56151. engine.generateMipMapsForCubemap(this._texture);
  56152. }
  56153. }
  56154. }
  56155. else {
  56156. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  56157. // VBOs
  56158. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  56159. // Clear
  56160. engine.clear(scene.clearColor, true, true, true);
  56161. // Draw order
  56162. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  56163. }
  56164. // Unbind
  56165. engine.unBindFramebuffer(this._texture, this.isCube);
  56166. if (this.onGenerated) {
  56167. this.onGenerated();
  56168. }
  56169. };
  56170. ProceduralTexture.prototype.clone = function () {
  56171. var textureSize = this.getSize();
  56172. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  56173. // Base texture
  56174. newTexture.hasAlpha = this.hasAlpha;
  56175. newTexture.level = this.level;
  56176. // RenderTarget Texture
  56177. newTexture.coordinatesMode = this.coordinatesMode;
  56178. return newTexture;
  56179. };
  56180. ProceduralTexture.prototype.dispose = function () {
  56181. var scene = this.getScene();
  56182. if (!scene) {
  56183. return;
  56184. }
  56185. var index = scene._proceduralTextures.indexOf(this);
  56186. if (index >= 0) {
  56187. scene._proceduralTextures.splice(index, 1);
  56188. }
  56189. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  56190. if (vertexBuffer) {
  56191. vertexBuffer.dispose();
  56192. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  56193. }
  56194. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  56195. this._indexBuffer = null;
  56196. }
  56197. _super.prototype.dispose.call(this);
  56198. };
  56199. return ProceduralTexture;
  56200. }(BABYLON.Texture));
  56201. BABYLON.ProceduralTexture = ProceduralTexture;
  56202. })(BABYLON || (BABYLON = {}));
  56203. //# sourceMappingURL=babylon.proceduralTexture.js.map
  56204. var BABYLON;
  56205. (function (BABYLON) {
  56206. var CustomProceduralTexture = /** @class */ (function (_super) {
  56207. __extends(CustomProceduralTexture, _super);
  56208. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  56209. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  56210. _this._animate = true;
  56211. _this._time = 0;
  56212. _this._texturePath = texturePath;
  56213. //Try to load json
  56214. _this.loadJson(texturePath);
  56215. _this.refreshRate = 1;
  56216. return _this;
  56217. }
  56218. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  56219. var _this = this;
  56220. var noConfigFile = function () {
  56221. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  56222. try {
  56223. _this.setFragment(_this._texturePath);
  56224. }
  56225. catch (ex) {
  56226. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  56227. }
  56228. };
  56229. var configFileUrl = jsonUrl + "/config.json";
  56230. var xhr = new XMLHttpRequest();
  56231. xhr.open("GET", configFileUrl, true);
  56232. xhr.addEventListener("load", function () {
  56233. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  56234. try {
  56235. _this._config = JSON.parse(xhr.response);
  56236. _this.updateShaderUniforms();
  56237. _this.updateTextures();
  56238. _this.setFragment(_this._texturePath + "/custom");
  56239. _this._animate = _this._config.animate;
  56240. _this.refreshRate = _this._config.refreshrate;
  56241. }
  56242. catch (ex) {
  56243. noConfigFile();
  56244. }
  56245. }
  56246. else {
  56247. noConfigFile();
  56248. }
  56249. }, false);
  56250. xhr.addEventListener("error", function () {
  56251. noConfigFile();
  56252. }, false);
  56253. try {
  56254. xhr.send();
  56255. }
  56256. catch (ex) {
  56257. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  56258. }
  56259. };
  56260. CustomProceduralTexture.prototype.isReady = function () {
  56261. if (!_super.prototype.isReady.call(this)) {
  56262. return false;
  56263. }
  56264. for (var name in this._textures) {
  56265. var texture = this._textures[name];
  56266. if (!texture.isReady()) {
  56267. return false;
  56268. }
  56269. }
  56270. return true;
  56271. };
  56272. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  56273. var scene = this.getScene();
  56274. if (this._animate && scene) {
  56275. this._time += scene.getAnimationRatio() * 0.03;
  56276. this.updateShaderUniforms();
  56277. }
  56278. _super.prototype.render.call(this, useCameraPostProcess);
  56279. };
  56280. CustomProceduralTexture.prototype.updateTextures = function () {
  56281. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  56282. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  56283. }
  56284. };
  56285. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  56286. if (this._config) {
  56287. for (var j = 0; j < this._config.uniforms.length; j++) {
  56288. var uniform = this._config.uniforms[j];
  56289. switch (uniform.type) {
  56290. case "float":
  56291. this.setFloat(uniform.name, uniform.value);
  56292. break;
  56293. case "color3":
  56294. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  56295. break;
  56296. case "color4":
  56297. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  56298. break;
  56299. case "vector2":
  56300. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  56301. break;
  56302. case "vector3":
  56303. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  56304. break;
  56305. }
  56306. }
  56307. }
  56308. this.setFloat("time", this._time);
  56309. };
  56310. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  56311. get: function () {
  56312. return this._animate;
  56313. },
  56314. set: function (value) {
  56315. this._animate = value;
  56316. },
  56317. enumerable: true,
  56318. configurable: true
  56319. });
  56320. return CustomProceduralTexture;
  56321. }(BABYLON.ProceduralTexture));
  56322. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  56323. })(BABYLON || (BABYLON = {}));
  56324. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  56325. var BABYLON;
  56326. (function (BABYLON) {
  56327. var FreeCameraGamepadInput = /** @class */ (function () {
  56328. function FreeCameraGamepadInput() {
  56329. this.gamepadAngularSensibility = 200;
  56330. this.gamepadMoveSensibility = 40;
  56331. // private members
  56332. this._cameraTransform = BABYLON.Matrix.Identity();
  56333. this._deltaTransform = BABYLON.Vector3.Zero();
  56334. this._vector3 = BABYLON.Vector3.Zero();
  56335. this._vector2 = BABYLON.Vector2.Zero();
  56336. }
  56337. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  56338. var _this = this;
  56339. var manager = this.camera.getScene().gamepadManager;
  56340. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  56341. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  56342. // prioritize XBOX gamepads.
  56343. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  56344. _this.gamepad = gamepad;
  56345. }
  56346. }
  56347. });
  56348. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  56349. if (_this.gamepad === gamepad) {
  56350. _this.gamepad = null;
  56351. }
  56352. });
  56353. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  56354. };
  56355. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  56356. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  56357. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  56358. this.gamepad = null;
  56359. };
  56360. FreeCameraGamepadInput.prototype.checkInputs = function () {
  56361. if (this.gamepad && this.gamepad.leftStick) {
  56362. var camera = this.camera;
  56363. var LSValues = this.gamepad.leftStick;
  56364. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  56365. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  56366. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  56367. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  56368. var RSValues = this.gamepad.rightStick;
  56369. if (RSValues) {
  56370. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  56371. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  56372. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  56373. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  56374. }
  56375. else {
  56376. RSValues = { x: 0, y: 0 };
  56377. }
  56378. if (!camera.rotationQuaternion) {
  56379. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  56380. }
  56381. else {
  56382. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  56383. }
  56384. var speed = camera._computeLocalCameraSpeed() * 50.0;
  56385. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  56386. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  56387. camera.cameraDirection.addInPlace(this._deltaTransform);
  56388. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  56389. camera.cameraRotation.addInPlace(this._vector2);
  56390. }
  56391. };
  56392. FreeCameraGamepadInput.prototype.getClassName = function () {
  56393. return "FreeCameraGamepadInput";
  56394. };
  56395. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  56396. return "gamepad";
  56397. };
  56398. __decorate([
  56399. BABYLON.serialize()
  56400. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  56401. __decorate([
  56402. BABYLON.serialize()
  56403. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  56404. return FreeCameraGamepadInput;
  56405. }());
  56406. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  56407. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  56408. })(BABYLON || (BABYLON = {}));
  56409. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  56410. var BABYLON;
  56411. (function (BABYLON) {
  56412. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  56413. function ArcRotateCameraGamepadInput() {
  56414. this.gamepadRotationSensibility = 80;
  56415. this.gamepadMoveSensibility = 40;
  56416. }
  56417. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  56418. var _this = this;
  56419. var manager = this.camera.getScene().gamepadManager;
  56420. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  56421. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  56422. // prioritize XBOX gamepads.
  56423. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  56424. _this.gamepad = gamepad;
  56425. }
  56426. }
  56427. });
  56428. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  56429. if (_this.gamepad === gamepad) {
  56430. _this.gamepad = null;
  56431. }
  56432. });
  56433. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  56434. };
  56435. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  56436. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  56437. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  56438. this.gamepad = null;
  56439. };
  56440. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  56441. if (this.gamepad) {
  56442. var camera = this.camera;
  56443. var RSValues = this.gamepad.rightStick;
  56444. if (RSValues) {
  56445. if (RSValues.x != 0) {
  56446. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  56447. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  56448. camera.inertialAlphaOffset += normalizedRX;
  56449. }
  56450. }
  56451. if (RSValues.y != 0) {
  56452. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  56453. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  56454. camera.inertialBetaOffset += normalizedRY;
  56455. }
  56456. }
  56457. }
  56458. var LSValues = this.gamepad.leftStick;
  56459. if (LSValues && LSValues.y != 0) {
  56460. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  56461. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  56462. this.camera.inertialRadiusOffset -= normalizedLY;
  56463. }
  56464. }
  56465. }
  56466. };
  56467. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  56468. return "ArcRotateCameraGamepadInput";
  56469. };
  56470. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  56471. return "gamepad";
  56472. };
  56473. __decorate([
  56474. BABYLON.serialize()
  56475. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  56476. __decorate([
  56477. BABYLON.serialize()
  56478. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  56479. return ArcRotateCameraGamepadInput;
  56480. }());
  56481. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  56482. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  56483. })(BABYLON || (BABYLON = {}));
  56484. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  56485. var BABYLON;
  56486. (function (BABYLON) {
  56487. var GamepadManager = /** @class */ (function () {
  56488. function GamepadManager(_scene) {
  56489. var _this = this;
  56490. this._scene = _scene;
  56491. this._babylonGamepads = [];
  56492. this._oneGamepadConnected = false;
  56493. this._isMonitoring = false;
  56494. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  56495. if (!BABYLON.Tools.IsWindowObjectExist()) {
  56496. this._gamepadEventSupported = false;
  56497. }
  56498. else {
  56499. this._gamepadEventSupported = 'GamepadEvent' in window;
  56500. this._gamepadSupport = (navigator.getGamepads ||
  56501. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  56502. }
  56503. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  56504. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  56505. for (var i in _this._babylonGamepads) {
  56506. var gamepad = _this._babylonGamepads[i];
  56507. if (gamepad && gamepad._isConnected) {
  56508. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  56509. }
  56510. }
  56511. });
  56512. this._onGamepadConnectedEvent = function (evt) {
  56513. var gamepad = evt.gamepad;
  56514. if (gamepad.index in _this._babylonGamepads) {
  56515. if (_this._babylonGamepads[gamepad.index].isConnected) {
  56516. return;
  56517. }
  56518. }
  56519. var newGamepad;
  56520. if (_this._babylonGamepads[gamepad.index]) {
  56521. newGamepad = _this._babylonGamepads[gamepad.index];
  56522. newGamepad.browserGamepad = gamepad;
  56523. newGamepad._isConnected = true;
  56524. }
  56525. else {
  56526. newGamepad = _this._addNewGamepad(gamepad);
  56527. }
  56528. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  56529. _this._startMonitoringGamepads();
  56530. };
  56531. this._onGamepadDisconnectedEvent = function (evt) {
  56532. var gamepad = evt.gamepad;
  56533. // Remove the gamepad from the list of gamepads to monitor.
  56534. for (var i in _this._babylonGamepads) {
  56535. if (_this._babylonGamepads[i].index === gamepad.index) {
  56536. var disconnectedGamepad = _this._babylonGamepads[i];
  56537. disconnectedGamepad._isConnected = false;
  56538. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  56539. break;
  56540. }
  56541. }
  56542. };
  56543. if (this._gamepadSupport) {
  56544. //first add already-connected gamepads
  56545. this._updateGamepadObjects();
  56546. if (this._babylonGamepads.length) {
  56547. this._startMonitoringGamepads();
  56548. }
  56549. // Checking if the gamepad connected event is supported (like in Firefox)
  56550. if (this._gamepadEventSupported) {
  56551. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  56552. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  56553. }
  56554. else {
  56555. this._startMonitoringGamepads();
  56556. }
  56557. }
  56558. }
  56559. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  56560. get: function () {
  56561. return this._babylonGamepads;
  56562. },
  56563. enumerable: true,
  56564. configurable: true
  56565. });
  56566. GamepadManager.prototype.getGamepadByType = function (type) {
  56567. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  56568. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  56569. var gamepad = _a[_i];
  56570. if (gamepad && gamepad.type === type) {
  56571. return gamepad;
  56572. }
  56573. }
  56574. return null;
  56575. };
  56576. GamepadManager.prototype.dispose = function () {
  56577. if (this._gamepadEventSupported) {
  56578. if (this._onGamepadConnectedEvent) {
  56579. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  56580. }
  56581. if (this._onGamepadDisconnectedEvent) {
  56582. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  56583. }
  56584. this._onGamepadConnectedEvent = null;
  56585. this._onGamepadDisconnectedEvent = null;
  56586. }
  56587. this._babylonGamepads.forEach(function (gamepad) {
  56588. gamepad.dispose();
  56589. });
  56590. this.onGamepadConnectedObservable.clear();
  56591. this.onGamepadDisconnectedObservable.clear();
  56592. this._oneGamepadConnected = false;
  56593. this._stopMonitoringGamepads();
  56594. this._babylonGamepads = [];
  56595. };
  56596. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  56597. if (!this._oneGamepadConnected) {
  56598. this._oneGamepadConnected = true;
  56599. }
  56600. var newGamepad;
  56601. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  56602. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  56603. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  56604. }
  56605. else if (gamepad.pose) {
  56606. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  56607. }
  56608. else {
  56609. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  56610. }
  56611. this._babylonGamepads[newGamepad.index] = newGamepad;
  56612. return newGamepad;
  56613. };
  56614. GamepadManager.prototype._startMonitoringGamepads = function () {
  56615. if (!this._isMonitoring) {
  56616. this._isMonitoring = true;
  56617. //back-comp
  56618. if (!this._scene) {
  56619. this._checkGamepadsStatus();
  56620. }
  56621. }
  56622. };
  56623. GamepadManager.prototype._stopMonitoringGamepads = function () {
  56624. this._isMonitoring = false;
  56625. };
  56626. GamepadManager.prototype._checkGamepadsStatus = function () {
  56627. var _this = this;
  56628. // Hack to be compatible Chrome
  56629. this._updateGamepadObjects();
  56630. for (var i in this._babylonGamepads) {
  56631. var gamepad = this._babylonGamepads[i];
  56632. if (!gamepad || !gamepad.isConnected) {
  56633. continue;
  56634. }
  56635. gamepad.update();
  56636. }
  56637. if (this._isMonitoring && !this._scene) {
  56638. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  56639. }
  56640. };
  56641. // This function is called only on Chrome, which does not properly support
  56642. // connection/disconnection events and forces you to recopy again the gamepad object
  56643. GamepadManager.prototype._updateGamepadObjects = function () {
  56644. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  56645. for (var i = 0; i < gamepads.length; i++) {
  56646. if (gamepads[i]) {
  56647. if (!this._babylonGamepads[gamepads[i].index]) {
  56648. var newGamepad = this._addNewGamepad(gamepads[i]);
  56649. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  56650. }
  56651. else {
  56652. // Forced to copy again this object for Chrome for unknown reason
  56653. this._babylonGamepads[i].browserGamepad = gamepads[i];
  56654. if (!this._babylonGamepads[i].isConnected) {
  56655. this._babylonGamepads[i]._isConnected = true;
  56656. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  56657. }
  56658. }
  56659. }
  56660. }
  56661. };
  56662. return GamepadManager;
  56663. }());
  56664. BABYLON.GamepadManager = GamepadManager;
  56665. })(BABYLON || (BABYLON = {}));
  56666. //# sourceMappingURL=babylon.gamepadManager.js.map
  56667. var BABYLON;
  56668. (function (BABYLON) {
  56669. var StickValues = /** @class */ (function () {
  56670. function StickValues(x, y) {
  56671. this.x = x;
  56672. this.y = y;
  56673. }
  56674. return StickValues;
  56675. }());
  56676. BABYLON.StickValues = StickValues;
  56677. var Gamepad = /** @class */ (function () {
  56678. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  56679. if (leftStickX === void 0) { leftStickX = 0; }
  56680. if (leftStickY === void 0) { leftStickY = 1; }
  56681. if (rightStickX === void 0) { rightStickX = 2; }
  56682. if (rightStickY === void 0) { rightStickY = 3; }
  56683. this.id = id;
  56684. this.index = index;
  56685. this.browserGamepad = browserGamepad;
  56686. this._isConnected = true;
  56687. this._invertLeftStickY = false;
  56688. this.type = Gamepad.GAMEPAD;
  56689. this._leftStickAxisX = leftStickX;
  56690. this._leftStickAxisY = leftStickY;
  56691. this._rightStickAxisX = rightStickX;
  56692. this._rightStickAxisY = rightStickY;
  56693. if (this.browserGamepad.axes.length >= 2) {
  56694. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  56695. }
  56696. if (this.browserGamepad.axes.length >= 4) {
  56697. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  56698. }
  56699. }
  56700. Object.defineProperty(Gamepad.prototype, "isConnected", {
  56701. get: function () {
  56702. return this._isConnected;
  56703. },
  56704. enumerable: true,
  56705. configurable: true
  56706. });
  56707. Gamepad.prototype.onleftstickchanged = function (callback) {
  56708. this._onleftstickchanged = callback;
  56709. };
  56710. Gamepad.prototype.onrightstickchanged = function (callback) {
  56711. this._onrightstickchanged = callback;
  56712. };
  56713. Object.defineProperty(Gamepad.prototype, "leftStick", {
  56714. get: function () {
  56715. return this._leftStick;
  56716. },
  56717. set: function (newValues) {
  56718. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  56719. this._onleftstickchanged(newValues);
  56720. }
  56721. this._leftStick = newValues;
  56722. },
  56723. enumerable: true,
  56724. configurable: true
  56725. });
  56726. Object.defineProperty(Gamepad.prototype, "rightStick", {
  56727. get: function () {
  56728. return this._rightStick;
  56729. },
  56730. set: function (newValues) {
  56731. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  56732. this._onrightstickchanged(newValues);
  56733. }
  56734. this._rightStick = newValues;
  56735. },
  56736. enumerable: true,
  56737. configurable: true
  56738. });
  56739. Gamepad.prototype.update = function () {
  56740. if (this._leftStick) {
  56741. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  56742. if (this._invertLeftStickY) {
  56743. this.leftStick.y *= -1;
  56744. }
  56745. }
  56746. if (this._rightStick) {
  56747. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  56748. }
  56749. };
  56750. Gamepad.prototype.dispose = function () {
  56751. };
  56752. Gamepad.GAMEPAD = 0;
  56753. Gamepad.GENERIC = 1;
  56754. Gamepad.XBOX = 2;
  56755. Gamepad.POSE_ENABLED = 3;
  56756. return Gamepad;
  56757. }());
  56758. BABYLON.Gamepad = Gamepad;
  56759. var GenericPad = /** @class */ (function (_super) {
  56760. __extends(GenericPad, _super);
  56761. function GenericPad(id, index, browserGamepad) {
  56762. var _this = _super.call(this, id, index, browserGamepad) || this;
  56763. _this.onButtonDownObservable = new BABYLON.Observable();
  56764. _this.onButtonUpObservable = new BABYLON.Observable();
  56765. _this.type = Gamepad.GENERIC;
  56766. _this._buttons = new Array(browserGamepad.buttons.length);
  56767. return _this;
  56768. }
  56769. GenericPad.prototype.onbuttondown = function (callback) {
  56770. this._onbuttondown = callback;
  56771. };
  56772. GenericPad.prototype.onbuttonup = function (callback) {
  56773. this._onbuttonup = callback;
  56774. };
  56775. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  56776. if (newValue !== currentValue) {
  56777. if (newValue === 1) {
  56778. if (this._onbuttondown) {
  56779. this._onbuttondown(buttonIndex);
  56780. }
  56781. this.onButtonDownObservable.notifyObservers(buttonIndex);
  56782. }
  56783. if (newValue === 0) {
  56784. if (this._onbuttonup) {
  56785. this._onbuttonup(buttonIndex);
  56786. }
  56787. this.onButtonUpObservable.notifyObservers(buttonIndex);
  56788. }
  56789. }
  56790. return newValue;
  56791. };
  56792. GenericPad.prototype.update = function () {
  56793. _super.prototype.update.call(this);
  56794. for (var index = 0; index < this._buttons.length; index++) {
  56795. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  56796. }
  56797. };
  56798. GenericPad.prototype.dispose = function () {
  56799. _super.prototype.dispose.call(this);
  56800. this.onButtonDownObservable.clear();
  56801. this.onButtonUpObservable.clear();
  56802. };
  56803. return GenericPad;
  56804. }(Gamepad));
  56805. BABYLON.GenericPad = GenericPad;
  56806. })(BABYLON || (BABYLON = {}));
  56807. //# sourceMappingURL=babylon.gamepad.js.map
  56808. var BABYLON;
  56809. (function (BABYLON) {
  56810. var Xbox360Button;
  56811. (function (Xbox360Button) {
  56812. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  56813. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  56814. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  56815. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  56816. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  56817. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  56818. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  56819. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  56820. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  56821. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  56822. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  56823. var Xbox360Dpad;
  56824. (function (Xbox360Dpad) {
  56825. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  56826. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  56827. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  56828. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  56829. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  56830. var Xbox360Pad = /** @class */ (function (_super) {
  56831. __extends(Xbox360Pad, _super);
  56832. function Xbox360Pad(id, index, gamepad, xboxOne) {
  56833. if (xboxOne === void 0) { xboxOne = false; }
  56834. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  56835. _this._leftTrigger = 0;
  56836. _this._rightTrigger = 0;
  56837. _this.onButtonDownObservable = new BABYLON.Observable();
  56838. _this.onButtonUpObservable = new BABYLON.Observable();
  56839. _this.onPadDownObservable = new BABYLON.Observable();
  56840. _this.onPadUpObservable = new BABYLON.Observable();
  56841. _this._buttonA = 0;
  56842. _this._buttonB = 0;
  56843. _this._buttonX = 0;
  56844. _this._buttonY = 0;
  56845. _this._buttonBack = 0;
  56846. _this._buttonStart = 0;
  56847. _this._buttonLB = 0;
  56848. _this._buttonRB = 0;
  56849. _this._buttonLeftStick = 0;
  56850. _this._buttonRightStick = 0;
  56851. _this._dPadUp = 0;
  56852. _this._dPadDown = 0;
  56853. _this._dPadLeft = 0;
  56854. _this._dPadRight = 0;
  56855. _this._isXboxOnePad = false;
  56856. _this.type = BABYLON.Gamepad.XBOX;
  56857. _this._isXboxOnePad = xboxOne;
  56858. return _this;
  56859. }
  56860. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  56861. this._onlefttriggerchanged = callback;
  56862. };
  56863. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  56864. this._onrighttriggerchanged = callback;
  56865. };
  56866. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  56867. get: function () {
  56868. return this._leftTrigger;
  56869. },
  56870. set: function (newValue) {
  56871. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  56872. this._onlefttriggerchanged(newValue);
  56873. }
  56874. this._leftTrigger = newValue;
  56875. },
  56876. enumerable: true,
  56877. configurable: true
  56878. });
  56879. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  56880. get: function () {
  56881. return this._rightTrigger;
  56882. },
  56883. set: function (newValue) {
  56884. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  56885. this._onrighttriggerchanged(newValue);
  56886. }
  56887. this._rightTrigger = newValue;
  56888. },
  56889. enumerable: true,
  56890. configurable: true
  56891. });
  56892. Xbox360Pad.prototype.onbuttondown = function (callback) {
  56893. this._onbuttondown = callback;
  56894. };
  56895. Xbox360Pad.prototype.onbuttonup = function (callback) {
  56896. this._onbuttonup = callback;
  56897. };
  56898. Xbox360Pad.prototype.ondpaddown = function (callback) {
  56899. this._ondpaddown = callback;
  56900. };
  56901. Xbox360Pad.prototype.ondpadup = function (callback) {
  56902. this._ondpadup = callback;
  56903. };
  56904. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  56905. if (newValue !== currentValue) {
  56906. if (newValue === 1) {
  56907. if (this._onbuttondown) {
  56908. this._onbuttondown(buttonType);
  56909. }
  56910. this.onButtonDownObservable.notifyObservers(buttonType);
  56911. }
  56912. if (newValue === 0) {
  56913. if (this._onbuttonup) {
  56914. this._onbuttonup(buttonType);
  56915. }
  56916. this.onButtonUpObservable.notifyObservers(buttonType);
  56917. }
  56918. }
  56919. return newValue;
  56920. };
  56921. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  56922. if (newValue !== currentValue) {
  56923. if (newValue === 1) {
  56924. if (this._ondpaddown) {
  56925. this._ondpaddown(buttonType);
  56926. }
  56927. this.onPadDownObservable.notifyObservers(buttonType);
  56928. }
  56929. if (newValue === 0) {
  56930. if (this._ondpadup) {
  56931. this._ondpadup(buttonType);
  56932. }
  56933. this.onPadUpObservable.notifyObservers(buttonType);
  56934. }
  56935. }
  56936. return newValue;
  56937. };
  56938. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  56939. get: function () {
  56940. return this._buttonA;
  56941. },
  56942. set: function (value) {
  56943. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  56944. },
  56945. enumerable: true,
  56946. configurable: true
  56947. });
  56948. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  56949. get: function () {
  56950. return this._buttonB;
  56951. },
  56952. set: function (value) {
  56953. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  56954. },
  56955. enumerable: true,
  56956. configurable: true
  56957. });
  56958. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  56959. get: function () {
  56960. return this._buttonX;
  56961. },
  56962. set: function (value) {
  56963. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  56964. },
  56965. enumerable: true,
  56966. configurable: true
  56967. });
  56968. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  56969. get: function () {
  56970. return this._buttonY;
  56971. },
  56972. set: function (value) {
  56973. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  56974. },
  56975. enumerable: true,
  56976. configurable: true
  56977. });
  56978. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  56979. get: function () {
  56980. return this._buttonStart;
  56981. },
  56982. set: function (value) {
  56983. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  56984. },
  56985. enumerable: true,
  56986. configurable: true
  56987. });
  56988. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  56989. get: function () {
  56990. return this._buttonBack;
  56991. },
  56992. set: function (value) {
  56993. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  56994. },
  56995. enumerable: true,
  56996. configurable: true
  56997. });
  56998. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  56999. get: function () {
  57000. return this._buttonLB;
  57001. },
  57002. set: function (value) {
  57003. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  57004. },
  57005. enumerable: true,
  57006. configurable: true
  57007. });
  57008. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  57009. get: function () {
  57010. return this._buttonRB;
  57011. },
  57012. set: function (value) {
  57013. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  57014. },
  57015. enumerable: true,
  57016. configurable: true
  57017. });
  57018. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  57019. get: function () {
  57020. return this._buttonLeftStick;
  57021. },
  57022. set: function (value) {
  57023. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  57024. },
  57025. enumerable: true,
  57026. configurable: true
  57027. });
  57028. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  57029. get: function () {
  57030. return this._buttonRightStick;
  57031. },
  57032. set: function (value) {
  57033. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  57034. },
  57035. enumerable: true,
  57036. configurable: true
  57037. });
  57038. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  57039. get: function () {
  57040. return this._dPadUp;
  57041. },
  57042. set: function (value) {
  57043. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  57044. },
  57045. enumerable: true,
  57046. configurable: true
  57047. });
  57048. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  57049. get: function () {
  57050. return this._dPadDown;
  57051. },
  57052. set: function (value) {
  57053. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  57054. },
  57055. enumerable: true,
  57056. configurable: true
  57057. });
  57058. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  57059. get: function () {
  57060. return this._dPadLeft;
  57061. },
  57062. set: function (value) {
  57063. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  57064. },
  57065. enumerable: true,
  57066. configurable: true
  57067. });
  57068. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  57069. get: function () {
  57070. return this._dPadRight;
  57071. },
  57072. set: function (value) {
  57073. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  57074. },
  57075. enumerable: true,
  57076. configurable: true
  57077. });
  57078. Xbox360Pad.prototype.update = function () {
  57079. _super.prototype.update.call(this);
  57080. if (this._isXboxOnePad) {
  57081. this.buttonA = this.browserGamepad.buttons[0].value;
  57082. this.buttonB = this.browserGamepad.buttons[1].value;
  57083. this.buttonX = this.browserGamepad.buttons[2].value;
  57084. this.buttonY = this.browserGamepad.buttons[3].value;
  57085. this.buttonLB = this.browserGamepad.buttons[4].value;
  57086. this.buttonRB = this.browserGamepad.buttons[5].value;
  57087. this.leftTrigger = this.browserGamepad.axes[2];
  57088. this.rightTrigger = this.browserGamepad.axes[5];
  57089. this.buttonBack = this.browserGamepad.buttons[9].value;
  57090. this.buttonStart = this.browserGamepad.buttons[8].value;
  57091. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  57092. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  57093. this.dPadUp = this.browserGamepad.buttons[11].value;
  57094. this.dPadDown = this.browserGamepad.buttons[12].value;
  57095. this.dPadLeft = this.browserGamepad.buttons[13].value;
  57096. this.dPadRight = this.browserGamepad.buttons[14].value;
  57097. }
  57098. else {
  57099. this.buttonA = this.browserGamepad.buttons[0].value;
  57100. this.buttonB = this.browserGamepad.buttons[1].value;
  57101. this.buttonX = this.browserGamepad.buttons[2].value;
  57102. this.buttonY = this.browserGamepad.buttons[3].value;
  57103. this.buttonLB = this.browserGamepad.buttons[4].value;
  57104. this.buttonRB = this.browserGamepad.buttons[5].value;
  57105. this.leftTrigger = this.browserGamepad.buttons[6].value;
  57106. this.rightTrigger = this.browserGamepad.buttons[7].value;
  57107. this.buttonBack = this.browserGamepad.buttons[8].value;
  57108. this.buttonStart = this.browserGamepad.buttons[9].value;
  57109. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  57110. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  57111. this.dPadUp = this.browserGamepad.buttons[12].value;
  57112. this.dPadDown = this.browserGamepad.buttons[13].value;
  57113. this.dPadLeft = this.browserGamepad.buttons[14].value;
  57114. this.dPadRight = this.browserGamepad.buttons[15].value;
  57115. }
  57116. };
  57117. Xbox360Pad.prototype.dispose = function () {
  57118. _super.prototype.dispose.call(this);
  57119. this.onButtonDownObservable.clear();
  57120. this.onButtonUpObservable.clear();
  57121. this.onPadDownObservable.clear();
  57122. this.onPadUpObservable.clear();
  57123. };
  57124. return Xbox360Pad;
  57125. }(BABYLON.Gamepad));
  57126. BABYLON.Xbox360Pad = Xbox360Pad;
  57127. })(BABYLON || (BABYLON = {}));
  57128. //# sourceMappingURL=babylon.xboxGamepad.js.map
  57129. var BABYLON;
  57130. (function (BABYLON) {
  57131. var PoseEnabledControllerType;
  57132. (function (PoseEnabledControllerType) {
  57133. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  57134. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  57135. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  57136. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 3] = "GENERIC";
  57137. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  57138. var PoseEnabledControllerHelper = /** @class */ (function () {
  57139. function PoseEnabledControllerHelper() {
  57140. }
  57141. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  57142. // Oculus Touch
  57143. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  57144. return new BABYLON.OculusTouchController(vrGamepad);
  57145. }
  57146. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  57147. return new BABYLON.WindowsMotionController(vrGamepad);
  57148. }
  57149. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  57150. return new BABYLON.ViveController(vrGamepad);
  57151. }
  57152. else {
  57153. return new BABYLON.GenericController(vrGamepad);
  57154. }
  57155. };
  57156. return PoseEnabledControllerHelper;
  57157. }());
  57158. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  57159. var PoseEnabledController = /** @class */ (function (_super) {
  57160. __extends(PoseEnabledController, _super);
  57161. function PoseEnabledController(browserGamepad) {
  57162. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  57163. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  57164. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  57165. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  57166. // Represents device position and rotation in babylon space
  57167. _this.devicePosition = BABYLON.Vector3.Zero();
  57168. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  57169. _this.deviceScaleFactor = 1;
  57170. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  57171. _this._deviceToWorld = BABYLON.Matrix.Identity();
  57172. _this._workingMatrix = BABYLON.Matrix.Identity();
  57173. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  57174. _this.controllerType = PoseEnabledControllerType.GENERIC;
  57175. _this.position = BABYLON.Vector3.Zero();
  57176. _this.rotationQuaternion = new BABYLON.Quaternion();
  57177. _this._calculatedPosition = BABYLON.Vector3.Zero();
  57178. _this._calculatedRotation = new BABYLON.Quaternion();
  57179. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  57180. return _this;
  57181. }
  57182. PoseEnabledController.prototype.update = function () {
  57183. _super.prototype.update.call(this);
  57184. var pose = this.browserGamepad.pose;
  57185. this.updateFromDevice(pose);
  57186. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  57187. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  57188. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  57189. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  57190. if (this._mesh) {
  57191. this._mesh.position.copyFrom(this.devicePosition);
  57192. if (this._mesh.rotationQuaternion) {
  57193. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  57194. }
  57195. }
  57196. };
  57197. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  57198. if (poseData) {
  57199. this.rawPose = poseData;
  57200. if (poseData.position) {
  57201. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  57202. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  57203. this._deviceRoomPosition.z *= -1;
  57204. }
  57205. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  57206. this._calculatedPosition.addInPlace(this.position);
  57207. }
  57208. var pose = this.rawPose;
  57209. if (poseData.orientation && pose.orientation) {
  57210. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  57211. if (this._mesh) {
  57212. if (this._mesh.getScene().useRightHandedSystem) {
  57213. this._deviceRoomRotationQuaternion.z *= -1;
  57214. this._deviceRoomRotationQuaternion.w *= -1;
  57215. }
  57216. else {
  57217. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  57218. }
  57219. }
  57220. // if the camera is set, rotate to the camera's rotation
  57221. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  57222. }
  57223. }
  57224. };
  57225. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  57226. if (this._mesh) {
  57227. this._mesh.parent = null;
  57228. }
  57229. this._mesh = mesh;
  57230. if (this._poseControlledCamera) {
  57231. this._mesh.parent = this._poseControlledCamera;
  57232. }
  57233. if (!this._mesh.rotationQuaternion) {
  57234. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  57235. }
  57236. };
  57237. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  57238. this._poseControlledCamera = camera;
  57239. if (this._mesh) {
  57240. this._mesh.parent = this._poseControlledCamera;
  57241. }
  57242. };
  57243. PoseEnabledController.prototype.dispose = function () {
  57244. if (this._mesh) {
  57245. this._mesh.dispose();
  57246. }
  57247. this._mesh = null;
  57248. _super.prototype.dispose.call(this);
  57249. };
  57250. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  57251. get: function () {
  57252. return this._mesh;
  57253. },
  57254. enumerable: true,
  57255. configurable: true
  57256. });
  57257. PoseEnabledController.prototype.getForwardRay = function (length) {
  57258. if (length === void 0) { length = 100; }
  57259. if (!this.mesh) {
  57260. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  57261. }
  57262. var m = this.mesh.getWorldMatrix();
  57263. var origin = m.getTranslation();
  57264. var forward = new BABYLON.Vector3(0, 0, -1);
  57265. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  57266. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  57267. return new BABYLON.Ray(origin, direction, length);
  57268. };
  57269. return PoseEnabledController;
  57270. }(BABYLON.Gamepad));
  57271. BABYLON.PoseEnabledController = PoseEnabledController;
  57272. })(BABYLON || (BABYLON = {}));
  57273. //# sourceMappingURL=babylon.poseEnabledController.js.map
  57274. var BABYLON;
  57275. (function (BABYLON) {
  57276. var WebVRController = /** @class */ (function (_super) {
  57277. __extends(WebVRController, _super);
  57278. function WebVRController(vrGamepad) {
  57279. var _this = _super.call(this, vrGamepad) || this;
  57280. // Observables
  57281. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  57282. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  57283. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  57284. _this.onPadStateChangedObservable = new BABYLON.Observable();
  57285. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  57286. _this.pad = { x: 0, y: 0 };
  57287. // avoid GC, store state in a tmp object
  57288. _this._changes = {
  57289. pressChanged: false,
  57290. touchChanged: false,
  57291. valueChanged: false,
  57292. changed: false
  57293. };
  57294. _this._buttons = new Array(vrGamepad.buttons.length);
  57295. _this.hand = vrGamepad.hand;
  57296. return _this;
  57297. }
  57298. WebVRController.prototype.onButtonStateChange = function (callback) {
  57299. this._onButtonStateChange = callback;
  57300. };
  57301. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  57302. get: function () {
  57303. return this._defaultModel;
  57304. },
  57305. enumerable: true,
  57306. configurable: true
  57307. });
  57308. WebVRController.prototype.update = function () {
  57309. _super.prototype.update.call(this);
  57310. for (var index = 0; index < this._buttons.length; index++) {
  57311. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  57312. }
  57313. ;
  57314. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  57315. this.pad.x = this.leftStick.x;
  57316. this.pad.y = this.leftStick.y;
  57317. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  57318. }
  57319. };
  57320. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  57321. if (!newState) {
  57322. newState = {
  57323. pressed: false,
  57324. touched: false,
  57325. value: 0
  57326. };
  57327. }
  57328. if (!currentState) {
  57329. this._buttons[buttonIndex] = {
  57330. pressed: newState.pressed,
  57331. touched: newState.touched,
  57332. value: newState.value
  57333. };
  57334. return;
  57335. }
  57336. this._checkChanges(newState, currentState);
  57337. if (this._changes.changed) {
  57338. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  57339. this.handleButtonChange(buttonIndex, newState, this._changes);
  57340. }
  57341. this._buttons[buttonIndex].pressed = newState.pressed;
  57342. this._buttons[buttonIndex].touched = newState.touched;
  57343. // oculus triggers are never 0, thou not touched.
  57344. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  57345. };
  57346. WebVRController.prototype._checkChanges = function (newState, currentState) {
  57347. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  57348. this._changes.touchChanged = newState.touched !== currentState.touched;
  57349. this._changes.valueChanged = newState.value !== currentState.value;
  57350. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  57351. return this._changes;
  57352. };
  57353. WebVRController.prototype.dispose = function () {
  57354. _super.prototype.dispose.call(this);
  57355. this.onTriggerStateChangedObservable.clear();
  57356. this.onMainButtonStateChangedObservable.clear();
  57357. this.onSecondaryButtonStateChangedObservable.clear();
  57358. this.onPadStateChangedObservable.clear();
  57359. this.onPadValuesChangedObservable.clear();
  57360. };
  57361. return WebVRController;
  57362. }(BABYLON.PoseEnabledController));
  57363. BABYLON.WebVRController = WebVRController;
  57364. })(BABYLON || (BABYLON = {}));
  57365. //# sourceMappingURL=babylon.webVRController.js.map
  57366. var BABYLON;
  57367. (function (BABYLON) {
  57368. var OculusTouchController = /** @class */ (function (_super) {
  57369. __extends(OculusTouchController, _super);
  57370. function OculusTouchController(vrGamepad) {
  57371. var _this = _super.call(this, vrGamepad) || this;
  57372. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  57373. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  57374. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  57375. return _this;
  57376. }
  57377. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  57378. var _this = this;
  57379. var meshName;
  57380. // Hand
  57381. if (this.hand === 'left') {
  57382. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  57383. }
  57384. else {
  57385. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  57386. }
  57387. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  57388. /*
  57389. Parent Mesh name: oculus_touch_left
  57390. - body
  57391. - trigger
  57392. - thumbstick
  57393. - grip
  57394. - button_y
  57395. - button_x
  57396. - button_enter
  57397. */
  57398. _this._defaultModel = newMeshes[1];
  57399. _this.attachToMesh(_this._defaultModel);
  57400. if (meshLoaded) {
  57401. meshLoaded(_this._defaultModel);
  57402. }
  57403. });
  57404. };
  57405. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  57406. // helper getters for left and right hand.
  57407. get: function () {
  57408. if (this.hand === 'right') {
  57409. return this.onMainButtonStateChangedObservable;
  57410. }
  57411. else {
  57412. throw new Error('No A button on left hand');
  57413. }
  57414. },
  57415. enumerable: true,
  57416. configurable: true
  57417. });
  57418. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  57419. get: function () {
  57420. if (this.hand === 'right') {
  57421. return this.onSecondaryButtonStateChangedObservable;
  57422. }
  57423. else {
  57424. throw new Error('No B button on left hand');
  57425. }
  57426. },
  57427. enumerable: true,
  57428. configurable: true
  57429. });
  57430. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  57431. get: function () {
  57432. if (this.hand === 'left') {
  57433. return this.onMainButtonStateChangedObservable;
  57434. }
  57435. else {
  57436. throw new Error('No X button on right hand');
  57437. }
  57438. },
  57439. enumerable: true,
  57440. configurable: true
  57441. });
  57442. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  57443. get: function () {
  57444. if (this.hand === 'left') {
  57445. return this.onSecondaryButtonStateChangedObservable;
  57446. }
  57447. else {
  57448. throw new Error('No Y button on right hand');
  57449. }
  57450. },
  57451. enumerable: true,
  57452. configurable: true
  57453. });
  57454. /*
  57455. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  57456. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  57457. 2) secondary trigger (same)
  57458. 3) A (right) X (left), touch, pressed = value
  57459. 4) B / Y
  57460. 5) thumb rest
  57461. */
  57462. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  57463. var notifyObject = state; //{ state: state, changes: changes };
  57464. var triggerDirection = this.hand === 'right' ? -1 : 1;
  57465. switch (buttonIdx) {
  57466. case 0:
  57467. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  57468. return;
  57469. case 1:// index trigger
  57470. if (this._defaultModel) {
  57471. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  57472. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  57473. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  57474. }
  57475. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  57476. return;
  57477. case 2:// secondary trigger
  57478. if (this._defaultModel) {
  57479. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  57480. }
  57481. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  57482. return;
  57483. case 3:
  57484. if (this._defaultModel) {
  57485. if (notifyObject.pressed) {
  57486. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  57487. }
  57488. else {
  57489. (this._defaultModel.getChildren()[1]).position.y = 0;
  57490. }
  57491. }
  57492. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  57493. return;
  57494. case 4:
  57495. if (this._defaultModel) {
  57496. if (notifyObject.pressed) {
  57497. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  57498. }
  57499. else {
  57500. (this._defaultModel.getChildren()[2]).position.y = 0;
  57501. }
  57502. }
  57503. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  57504. return;
  57505. case 5:
  57506. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  57507. return;
  57508. }
  57509. };
  57510. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  57511. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  57512. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  57513. return OculusTouchController;
  57514. }(BABYLON.WebVRController));
  57515. BABYLON.OculusTouchController = OculusTouchController;
  57516. })(BABYLON || (BABYLON = {}));
  57517. //# sourceMappingURL=babylon.oculusTouchController.js.map
  57518. var BABYLON;
  57519. (function (BABYLON) {
  57520. var ViveController = /** @class */ (function (_super) {
  57521. __extends(ViveController, _super);
  57522. function ViveController(vrGamepad) {
  57523. var _this = _super.call(this, vrGamepad) || this;
  57524. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  57525. _this._invertLeftStickY = true;
  57526. return _this;
  57527. }
  57528. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  57529. var _this = this;
  57530. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  57531. /*
  57532. Parent Mesh name: ViveWand
  57533. - body
  57534. - r_gripper
  57535. - l_gripper
  57536. - menu_button
  57537. - system_button
  57538. - trackpad
  57539. - trigger
  57540. - LED
  57541. */
  57542. _this._defaultModel = newMeshes[1];
  57543. _this.attachToMesh(_this._defaultModel);
  57544. if (meshLoaded) {
  57545. meshLoaded(_this._defaultModel);
  57546. }
  57547. });
  57548. };
  57549. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  57550. get: function () {
  57551. return this.onMainButtonStateChangedObservable;
  57552. },
  57553. enumerable: true,
  57554. configurable: true
  57555. });
  57556. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  57557. get: function () {
  57558. return this.onMainButtonStateChangedObservable;
  57559. },
  57560. enumerable: true,
  57561. configurable: true
  57562. });
  57563. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  57564. get: function () {
  57565. return this.onSecondaryButtonStateChangedObservable;
  57566. },
  57567. enumerable: true,
  57568. configurable: true
  57569. });
  57570. /**
  57571. * Vive mapping:
  57572. * 0: touchpad
  57573. * 1: trigger
  57574. * 2: left AND right buttons
  57575. * 3: menu button
  57576. */
  57577. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  57578. var notifyObject = state; //{ state: state, changes: changes };
  57579. switch (buttonIdx) {
  57580. case 0:
  57581. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  57582. return;
  57583. case 1:// index trigger
  57584. if (this._defaultModel) {
  57585. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  57586. }
  57587. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  57588. return;
  57589. case 2:// left AND right button
  57590. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  57591. return;
  57592. case 3:
  57593. if (this._defaultModel) {
  57594. if (notifyObject.pressed) {
  57595. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  57596. }
  57597. else {
  57598. (this._defaultModel.getChildren()[2]).position.y = 0;
  57599. }
  57600. }
  57601. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  57602. return;
  57603. }
  57604. };
  57605. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  57606. ViveController.MODEL_FILENAME = 'wand.babylon';
  57607. return ViveController;
  57608. }(BABYLON.WebVRController));
  57609. BABYLON.ViveController = ViveController;
  57610. })(BABYLON || (BABYLON = {}));
  57611. //# sourceMappingURL=babylon.viveController.js.map
  57612. var BABYLON;
  57613. (function (BABYLON) {
  57614. var GenericController = /** @class */ (function (_super) {
  57615. __extends(GenericController, _super);
  57616. function GenericController(vrGamepad) {
  57617. return _super.call(this, vrGamepad) || this;
  57618. }
  57619. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  57620. var _this = this;
  57621. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  57622. _this._defaultModel = newMeshes[1];
  57623. _this.attachToMesh(_this._defaultModel);
  57624. if (meshLoaded) {
  57625. meshLoaded(_this._defaultModel);
  57626. }
  57627. });
  57628. };
  57629. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  57630. console.log("Button id: " + buttonIdx + "state: ");
  57631. console.dir(state);
  57632. };
  57633. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  57634. GenericController.MODEL_FILENAME = 'generic.babylon';
  57635. return GenericController;
  57636. }(BABYLON.WebVRController));
  57637. BABYLON.GenericController = GenericController;
  57638. })(BABYLON || (BABYLON = {}));
  57639. //# sourceMappingURL=babylon.genericController.js.map
  57640. var BABYLON;
  57641. (function (BABYLON) {
  57642. var LoadedMeshInfo = /** @class */ (function () {
  57643. function LoadedMeshInfo() {
  57644. this.buttonMeshes = {};
  57645. this.axisMeshes = {};
  57646. }
  57647. return LoadedMeshInfo;
  57648. }());
  57649. var WindowsMotionController = /** @class */ (function (_super) {
  57650. __extends(WindowsMotionController, _super);
  57651. function WindowsMotionController(vrGamepad) {
  57652. var _this = _super.call(this, vrGamepad) || this;
  57653. _this._mapping = {
  57654. // Semantic button names
  57655. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  57656. // A mapping of the button name to glTF model node name
  57657. // that should be transformed by button value.
  57658. buttonMeshNames: {
  57659. 'trigger': 'SELECT',
  57660. 'menu': 'MENU',
  57661. 'grip': 'GRASP',
  57662. 'thumbstick': 'THUMBSTICK_PRESS',
  57663. 'trackpad': 'TOUCHPAD_PRESS'
  57664. },
  57665. // This mapping is used to translate from the Motion Controller to Babylon semantics
  57666. buttonObservableNames: {
  57667. 'trigger': 'onTriggerStateChangedObservable',
  57668. 'menu': 'onSecondaryButtonStateChangedObservable',
  57669. 'grip': 'onMainButtonStateChangedObservable',
  57670. 'thumbstick': 'onPadStateChangedObservable',
  57671. 'trackpad': 'onTrackpadChangedObservable'
  57672. },
  57673. // A mapping of the axis name to glTF model node name
  57674. // that should be transformed by axis value.
  57675. // This array mirrors the browserGamepad.axes array, such that
  57676. // the mesh corresponding to axis 0 is in this array index 0.
  57677. axisMeshNames: [
  57678. 'THUMBSTICK_X',
  57679. 'THUMBSTICK_Y',
  57680. 'TOUCHPAD_TOUCH_X',
  57681. 'TOUCHPAD_TOUCH_Y'
  57682. ],
  57683. pointingPoseMeshName: 'POINTING_POSE'
  57684. };
  57685. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  57686. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  57687. _this.trackpad = { x: 0, y: 0 };
  57688. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  57689. _this._loadedMeshInfo = null;
  57690. return _this;
  57691. }
  57692. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  57693. get: function () {
  57694. return this.onTriggerStateChangedObservable;
  57695. },
  57696. enumerable: true,
  57697. configurable: true
  57698. });
  57699. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  57700. get: function () {
  57701. return this.onSecondaryButtonStateChangedObservable;
  57702. },
  57703. enumerable: true,
  57704. configurable: true
  57705. });
  57706. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  57707. get: function () {
  57708. return this.onMainButtonStateChangedObservable;
  57709. },
  57710. enumerable: true,
  57711. configurable: true
  57712. });
  57713. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  57714. get: function () {
  57715. return this.onPadStateChangedObservable;
  57716. },
  57717. enumerable: true,
  57718. configurable: true
  57719. });
  57720. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  57721. get: function () {
  57722. return this.onTrackpadChangedObservable;
  57723. },
  57724. enumerable: true,
  57725. configurable: true
  57726. });
  57727. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  57728. get: function () {
  57729. return this.onTrackpadValuesChangedObservable;
  57730. },
  57731. enumerable: true,
  57732. configurable: true
  57733. });
  57734. /**
  57735. * Called once per frame by the engine.
  57736. */
  57737. WindowsMotionController.prototype.update = function () {
  57738. _super.prototype.update.call(this);
  57739. // Only need to animate axes if there is a loaded mesh
  57740. if (this._loadedMeshInfo) {
  57741. if (this.browserGamepad.axes) {
  57742. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  57743. this.trackpad.x = this.browserGamepad["axes"][2];
  57744. this.trackpad.y = this.browserGamepad["axes"][3];
  57745. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  57746. }
  57747. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  57748. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  57749. }
  57750. }
  57751. }
  57752. };
  57753. /**
  57754. * Called once for each button that changed state since the last frame
  57755. * @param buttonIdx Which button index changed
  57756. * @param state New state of the button
  57757. * @param changes Which properties on the state changed since last frame
  57758. */
  57759. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  57760. var buttonName = this._mapping.buttons[buttonIdx];
  57761. if (!buttonName) {
  57762. return;
  57763. }
  57764. // Only emit events for buttons that we know how to map from index to name
  57765. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  57766. if (observable) {
  57767. observable.notifyObservers(state);
  57768. }
  57769. this.lerpButtonTransform(buttonName, state.value);
  57770. };
  57771. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  57772. // If there is no loaded mesh, there is nothing to transform.
  57773. if (!this._loadedMeshInfo) {
  57774. return;
  57775. }
  57776. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  57777. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  57778. return;
  57779. }
  57780. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  57781. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  57782. };
  57783. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  57784. if (!this._loadedMeshInfo) {
  57785. return;
  57786. }
  57787. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  57788. if (!meshInfo) {
  57789. return;
  57790. }
  57791. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  57792. return;
  57793. }
  57794. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  57795. var lerpValue = axisValue * 0.5 + 0.5;
  57796. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  57797. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  57798. };
  57799. /**
  57800. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  57801. * @param scene scene in which to add meshes
  57802. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  57803. */
  57804. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  57805. var _this = this;
  57806. if (forceDefault === void 0) { forceDefault = false; }
  57807. var path;
  57808. var filename;
  57809. // Checking if GLB loader is present
  57810. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  57811. // Determine the device specific folder based on the ID suffix
  57812. var device = 'default';
  57813. if (this.id && !forceDefault) {
  57814. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  57815. device = ((match && match[0]) || device);
  57816. }
  57817. // Hand
  57818. if (this.hand === 'left') {
  57819. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  57820. }
  57821. else {
  57822. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  57823. }
  57824. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  57825. }
  57826. else {
  57827. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  57828. path = BABYLON.GenericController.MODEL_BASE_URL;
  57829. filename = BABYLON.GenericController.MODEL_FILENAME;
  57830. }
  57831. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  57832. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  57833. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  57834. if (!_this._loadedMeshInfo) {
  57835. return;
  57836. }
  57837. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  57838. _this.attachToMesh(_this._defaultModel);
  57839. if (meshLoaded) {
  57840. meshLoaded(_this._defaultModel);
  57841. }
  57842. }, null, function (scene, message) {
  57843. BABYLON.Tools.Log(message);
  57844. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  57845. if (!forceDefault) {
  57846. _this.initControllerMesh(scene, meshLoaded, true);
  57847. }
  57848. });
  57849. };
  57850. /**
  57851. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  57852. * can be transformed by button presses and axes values, based on this._mapping.
  57853. *
  57854. * @param scene scene in which the meshes exist
  57855. * @param meshes list of meshes that make up the controller model to process
  57856. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  57857. */
  57858. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  57859. var loadedMeshInfo = null;
  57860. // Create a new mesh to contain the glTF hierarchy
  57861. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  57862. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  57863. var childMesh = null;
  57864. for (var i = 0; i < meshes.length; i++) {
  57865. var mesh = meshes[i];
  57866. if (!mesh.parent) {
  57867. // Exclude controller meshes from picking results
  57868. mesh.isPickable = false;
  57869. // Handle root node, attach to the new parentMesh
  57870. childMesh = mesh;
  57871. break;
  57872. }
  57873. }
  57874. if (childMesh) {
  57875. childMesh.setParent(parentMesh);
  57876. // Create our mesh info. Note that this method will always return non-null.
  57877. loadedMeshInfo = this.createMeshInfo(parentMesh);
  57878. }
  57879. else {
  57880. BABYLON.Tools.Warn('Could not find root node in model file.');
  57881. }
  57882. return loadedMeshInfo;
  57883. };
  57884. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  57885. var loadedMeshInfo = new LoadedMeshInfo();
  57886. var i;
  57887. loadedMeshInfo.rootNode = rootNode;
  57888. // Reset the caches
  57889. loadedMeshInfo.buttonMeshes = {};
  57890. loadedMeshInfo.axisMeshes = {};
  57891. // Button Meshes
  57892. for (i = 0; i < this._mapping.buttons.length; i++) {
  57893. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  57894. if (!buttonMeshName) {
  57895. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  57896. continue;
  57897. }
  57898. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  57899. if (!buttonMesh) {
  57900. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  57901. continue;
  57902. }
  57903. var buttonMeshInfo = {
  57904. index: i,
  57905. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  57906. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  57907. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  57908. };
  57909. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  57910. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  57911. }
  57912. else {
  57913. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  57914. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  57915. '(VALUE: ' + !!buttonMeshInfo.value +
  57916. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  57917. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  57918. ')');
  57919. }
  57920. }
  57921. // Axis Meshes
  57922. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  57923. var axisMeshName = this._mapping.axisMeshNames[i];
  57924. if (!axisMeshName) {
  57925. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  57926. continue;
  57927. }
  57928. var axisMesh = getChildByName(rootNode, axisMeshName);
  57929. if (!axisMesh) {
  57930. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  57931. continue;
  57932. }
  57933. var axisMeshInfo = {
  57934. index: i,
  57935. value: getImmediateChildByName(axisMesh, 'VALUE'),
  57936. min: getImmediateChildByName(axisMesh, 'MIN'),
  57937. max: getImmediateChildByName(axisMesh, 'MAX')
  57938. };
  57939. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  57940. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  57941. }
  57942. else {
  57943. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  57944. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  57945. '(VALUE: ' + !!axisMeshInfo.value +
  57946. ', MIN: ' + !!axisMeshInfo.min +
  57947. ', MAX:' + !!axisMeshInfo.max +
  57948. ')');
  57949. }
  57950. }
  57951. // Pointing Ray
  57952. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  57953. if (!loadedMeshInfo.pointingPoseNode) {
  57954. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  57955. }
  57956. return loadedMeshInfo;
  57957. // Look through all children recursively. This will return null if no mesh exists with the given name.
  57958. function getChildByName(node, name) {
  57959. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  57960. }
  57961. // Look through only immediate children. This will return null if no mesh exists with the given name.
  57962. function getImmediateChildByName(node, name) {
  57963. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  57964. }
  57965. };
  57966. WindowsMotionController.prototype.getForwardRay = function (length) {
  57967. if (length === void 0) { length = 100; }
  57968. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  57969. return _super.prototype.getForwardRay.call(this, length);
  57970. }
  57971. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  57972. var origin = m.getTranslation();
  57973. var forward = new BABYLON.Vector3(0, 0, -1);
  57974. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  57975. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  57976. return new BABYLON.Ray(origin, direction, length);
  57977. };
  57978. WindowsMotionController.prototype.dispose = function () {
  57979. _super.prototype.dispose.call(this);
  57980. this.onTrackpadChangedObservable.clear();
  57981. };
  57982. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  57983. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  57984. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  57985. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  57986. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  57987. return WindowsMotionController;
  57988. }(BABYLON.WebVRController));
  57989. BABYLON.WindowsMotionController = WindowsMotionController;
  57990. })(BABYLON || (BABYLON = {}));
  57991. //# sourceMappingURL=babylon.windowsMotionController.js.map
  57992. var BABYLON;
  57993. (function (BABYLON) {
  57994. var FollowCamera = /** @class */ (function (_super) {
  57995. __extends(FollowCamera, _super);
  57996. function FollowCamera(name, position, scene, lockedTarget) {
  57997. if (lockedTarget === void 0) { lockedTarget = null; }
  57998. var _this = _super.call(this, name, position, scene) || this;
  57999. _this.radius = 12;
  58000. _this.rotationOffset = 0;
  58001. _this.heightOffset = 4;
  58002. _this.cameraAcceleration = 0.05;
  58003. _this.maxCameraSpeed = 20;
  58004. _this.lockedTarget = lockedTarget;
  58005. return _this;
  58006. }
  58007. FollowCamera.prototype.getRadians = function (degrees) {
  58008. return degrees * Math.PI / 180;
  58009. };
  58010. FollowCamera.prototype.follow = function (cameraTarget) {
  58011. if (!cameraTarget)
  58012. return;
  58013. var yRotation;
  58014. if (cameraTarget.rotationQuaternion) {
  58015. var rotMatrix = new BABYLON.Matrix();
  58016. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  58017. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  58018. }
  58019. else {
  58020. yRotation = cameraTarget.rotation.y;
  58021. }
  58022. var radians = this.getRadians(this.rotationOffset) + yRotation;
  58023. var targetPosition = cameraTarget.getAbsolutePosition();
  58024. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  58025. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  58026. var dx = targetX - this.position.x;
  58027. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  58028. var dz = (targetZ) - this.position.z;
  58029. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  58030. var vy = dy * this.cameraAcceleration;
  58031. var vz = dz * this.cameraAcceleration * 2;
  58032. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  58033. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  58034. }
  58035. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  58036. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  58037. }
  58038. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  58039. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  58040. }
  58041. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  58042. this.setTarget(targetPosition);
  58043. };
  58044. FollowCamera.prototype._checkInputs = function () {
  58045. _super.prototype._checkInputs.call(this);
  58046. if (this.lockedTarget) {
  58047. this.follow(this.lockedTarget);
  58048. }
  58049. };
  58050. FollowCamera.prototype.getClassName = function () {
  58051. return "FollowCamera";
  58052. };
  58053. __decorate([
  58054. BABYLON.serialize()
  58055. ], FollowCamera.prototype, "radius", void 0);
  58056. __decorate([
  58057. BABYLON.serialize()
  58058. ], FollowCamera.prototype, "rotationOffset", void 0);
  58059. __decorate([
  58060. BABYLON.serialize()
  58061. ], FollowCamera.prototype, "heightOffset", void 0);
  58062. __decorate([
  58063. BABYLON.serialize()
  58064. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  58065. __decorate([
  58066. BABYLON.serialize()
  58067. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  58068. __decorate([
  58069. BABYLON.serializeAsMeshReference("lockedTargetId")
  58070. ], FollowCamera.prototype, "lockedTarget", void 0);
  58071. return FollowCamera;
  58072. }(BABYLON.TargetCamera));
  58073. BABYLON.FollowCamera = FollowCamera;
  58074. var ArcFollowCamera = /** @class */ (function (_super) {
  58075. __extends(ArcFollowCamera, _super);
  58076. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  58077. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  58078. _this.alpha = alpha;
  58079. _this.beta = beta;
  58080. _this.radius = radius;
  58081. _this.target = target;
  58082. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  58083. _this.follow();
  58084. return _this;
  58085. }
  58086. ArcFollowCamera.prototype.follow = function () {
  58087. if (!this.target) {
  58088. return;
  58089. }
  58090. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  58091. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  58092. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  58093. var targetPosition = this.target.getAbsolutePosition();
  58094. this.position = targetPosition.add(this._cartesianCoordinates);
  58095. this.setTarget(targetPosition);
  58096. };
  58097. ArcFollowCamera.prototype._checkInputs = function () {
  58098. _super.prototype._checkInputs.call(this);
  58099. this.follow();
  58100. };
  58101. ArcFollowCamera.prototype.getClassName = function () {
  58102. return "ArcFollowCamera";
  58103. };
  58104. return ArcFollowCamera;
  58105. }(BABYLON.TargetCamera));
  58106. BABYLON.ArcFollowCamera = ArcFollowCamera;
  58107. })(BABYLON || (BABYLON = {}));
  58108. //# sourceMappingURL=babylon.followCamera.js.map
  58109. var BABYLON;
  58110. (function (BABYLON) {
  58111. // We're mainly based on the logic defined into the FreeCamera code
  58112. var UniversalCamera = /** @class */ (function (_super) {
  58113. __extends(UniversalCamera, _super);
  58114. //-- end properties for backward compatibility for inputs
  58115. function UniversalCamera(name, position, scene) {
  58116. var _this = _super.call(this, name, position, scene) || this;
  58117. _this.inputs.addGamepad();
  58118. return _this;
  58119. }
  58120. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  58121. //-- Begin properties for backward compatibility for inputs
  58122. get: function () {
  58123. var gamepad = this.inputs.attached["gamepad"];
  58124. if (gamepad)
  58125. return gamepad.gamepadAngularSensibility;
  58126. return 0;
  58127. },
  58128. set: function (value) {
  58129. var gamepad = this.inputs.attached["gamepad"];
  58130. if (gamepad)
  58131. gamepad.gamepadAngularSensibility = value;
  58132. },
  58133. enumerable: true,
  58134. configurable: true
  58135. });
  58136. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  58137. get: function () {
  58138. var gamepad = this.inputs.attached["gamepad"];
  58139. if (gamepad)
  58140. return gamepad.gamepadMoveSensibility;
  58141. return 0;
  58142. },
  58143. set: function (value) {
  58144. var gamepad = this.inputs.attached["gamepad"];
  58145. if (gamepad)
  58146. gamepad.gamepadMoveSensibility = value;
  58147. },
  58148. enumerable: true,
  58149. configurable: true
  58150. });
  58151. UniversalCamera.prototype.getClassName = function () {
  58152. return "UniversalCamera";
  58153. };
  58154. return UniversalCamera;
  58155. }(BABYLON.TouchCamera));
  58156. BABYLON.UniversalCamera = UniversalCamera;
  58157. })(BABYLON || (BABYLON = {}));
  58158. //# sourceMappingURL=babylon.universalCamera.js.map
  58159. var BABYLON;
  58160. (function (BABYLON) {
  58161. // We're mainly based on the logic defined into the FreeCamera code
  58162. var GamepadCamera = /** @class */ (function (_super) {
  58163. __extends(GamepadCamera, _super);
  58164. //-- end properties for backward compatibility for inputs
  58165. function GamepadCamera(name, position, scene) {
  58166. return _super.call(this, name, position, scene) || this;
  58167. }
  58168. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  58169. //-- Begin properties for backward compatibility for inputs
  58170. get: function () {
  58171. var gamepad = this.inputs.attached["gamepad"];
  58172. if (gamepad)
  58173. return gamepad.gamepadAngularSensibility;
  58174. return 0;
  58175. },
  58176. set: function (value) {
  58177. var gamepad = this.inputs.attached["gamepad"];
  58178. if (gamepad)
  58179. gamepad.gamepadAngularSensibility = value;
  58180. },
  58181. enumerable: true,
  58182. configurable: true
  58183. });
  58184. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  58185. get: function () {
  58186. var gamepad = this.inputs.attached["gamepad"];
  58187. if (gamepad)
  58188. return gamepad.gamepadMoveSensibility;
  58189. return 0;
  58190. },
  58191. set: function (value) {
  58192. var gamepad = this.inputs.attached["gamepad"];
  58193. if (gamepad)
  58194. gamepad.gamepadMoveSensibility = value;
  58195. },
  58196. enumerable: true,
  58197. configurable: true
  58198. });
  58199. GamepadCamera.prototype.getClassName = function () {
  58200. return "GamepadCamera";
  58201. };
  58202. return GamepadCamera;
  58203. }(BABYLON.UniversalCamera));
  58204. BABYLON.GamepadCamera = GamepadCamera;
  58205. })(BABYLON || (BABYLON = {}));
  58206. //# sourceMappingURL=babylon.gamepadCamera.js.map
  58207. var BABYLON;
  58208. (function (BABYLON) {
  58209. var PostProcessRenderPipelineManager = /** @class */ (function () {
  58210. function PostProcessRenderPipelineManager() {
  58211. this._renderPipelines = {};
  58212. }
  58213. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  58214. this._renderPipelines[renderPipeline._name] = renderPipeline;
  58215. };
  58216. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  58217. if (unique === void 0) { unique = false; }
  58218. var renderPipeline = this._renderPipelines[renderPipelineName];
  58219. if (!renderPipeline) {
  58220. return;
  58221. }
  58222. renderPipeline._attachCameras(cameras, unique);
  58223. };
  58224. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  58225. var renderPipeline = this._renderPipelines[renderPipelineName];
  58226. if (!renderPipeline) {
  58227. return;
  58228. }
  58229. renderPipeline._detachCameras(cameras);
  58230. };
  58231. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  58232. var renderPipeline = this._renderPipelines[renderPipelineName];
  58233. if (!renderPipeline) {
  58234. return;
  58235. }
  58236. renderPipeline._enableEffect(renderEffectName, cameras);
  58237. };
  58238. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  58239. var renderPipeline = this._renderPipelines[renderPipelineName];
  58240. if (!renderPipeline) {
  58241. return;
  58242. }
  58243. renderPipeline._disableEffect(renderEffectName, cameras);
  58244. };
  58245. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  58246. var renderPipeline = this._renderPipelines[renderPipelineName];
  58247. if (!renderPipeline) {
  58248. return;
  58249. }
  58250. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  58251. };
  58252. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  58253. var renderPipeline = this._renderPipelines[renderPipelineName];
  58254. if (!renderPipeline) {
  58255. return;
  58256. }
  58257. renderPipeline._disableDisplayOnlyPass(cameras);
  58258. };
  58259. PostProcessRenderPipelineManager.prototype.update = function () {
  58260. for (var renderPipelineName in this._renderPipelines) {
  58261. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  58262. var pipeline = this._renderPipelines[renderPipelineName];
  58263. if (!pipeline.isSupported) {
  58264. pipeline.dispose();
  58265. delete this._renderPipelines[renderPipelineName];
  58266. }
  58267. else {
  58268. pipeline._update();
  58269. }
  58270. }
  58271. }
  58272. };
  58273. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  58274. for (var renderPipelineName in this._renderPipelines) {
  58275. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  58276. var pipeline = this._renderPipelines[renderPipelineName];
  58277. pipeline._rebuild();
  58278. }
  58279. }
  58280. };
  58281. PostProcessRenderPipelineManager.prototype.dispose = function () {
  58282. for (var renderPipelineName in this._renderPipelines) {
  58283. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  58284. var pipeline = this._renderPipelines[renderPipelineName];
  58285. pipeline.dispose();
  58286. }
  58287. }
  58288. };
  58289. return PostProcessRenderPipelineManager;
  58290. }());
  58291. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  58292. })(BABYLON || (BABYLON = {}));
  58293. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  58294. var BABYLON;
  58295. (function (BABYLON) {
  58296. var PostProcessRenderPass = /** @class */ (function () {
  58297. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  58298. this._refCount = 0;
  58299. this._name = name;
  58300. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  58301. this.setRenderList(renderList);
  58302. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  58303. this._renderTexture.onAfterRenderObservable.add(afterRender);
  58304. this._scene = scene;
  58305. this._renderList = renderList;
  58306. }
  58307. // private
  58308. PostProcessRenderPass.prototype._incRefCount = function () {
  58309. if (this._refCount === 0) {
  58310. this._scene.customRenderTargets.push(this._renderTexture);
  58311. }
  58312. return ++this._refCount;
  58313. };
  58314. PostProcessRenderPass.prototype._decRefCount = function () {
  58315. this._refCount--;
  58316. if (this._refCount <= 0) {
  58317. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  58318. }
  58319. return this._refCount;
  58320. };
  58321. PostProcessRenderPass.prototype._update = function () {
  58322. this.setRenderList(this._renderList);
  58323. };
  58324. // public
  58325. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  58326. this._renderTexture.renderList = renderList;
  58327. };
  58328. PostProcessRenderPass.prototype.getRenderTexture = function () {
  58329. return this._renderTexture;
  58330. };
  58331. return PostProcessRenderPass;
  58332. }());
  58333. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  58334. })(BABYLON || (BABYLON = {}));
  58335. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  58336. var BABYLON;
  58337. (function (BABYLON) {
  58338. var PostProcessRenderEffect = /** @class */ (function () {
  58339. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  58340. this._name = name;
  58341. this._singleInstance = singleInstance || true;
  58342. this._getPostProcess = getPostProcess;
  58343. this._cameras = {};
  58344. this._indicesForCamera = {};
  58345. this._postProcesses = {};
  58346. this._renderPasses = {};
  58347. this._renderEffectAsPasses = {};
  58348. }
  58349. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  58350. get: function () {
  58351. for (var index in this._postProcesses) {
  58352. if (!this._postProcesses[index].isSupported) {
  58353. return false;
  58354. }
  58355. }
  58356. return true;
  58357. },
  58358. enumerable: true,
  58359. configurable: true
  58360. });
  58361. PostProcessRenderEffect.prototype._update = function () {
  58362. for (var renderPassName in this._renderPasses) {
  58363. this._renderPasses[renderPassName]._update();
  58364. }
  58365. };
  58366. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  58367. this._renderPasses[renderPass._name] = renderPass;
  58368. this._linkParameters();
  58369. };
  58370. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  58371. delete this._renderPasses[renderPass._name];
  58372. this._linkParameters();
  58373. };
  58374. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  58375. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  58376. this._linkParameters();
  58377. };
  58378. PostProcessRenderEffect.prototype.getPass = function (passName) {
  58379. for (var renderPassName in this._renderPasses) {
  58380. if (renderPassName === passName) {
  58381. return this._renderPasses[passName];
  58382. }
  58383. }
  58384. return null;
  58385. };
  58386. PostProcessRenderEffect.prototype.emptyPasses = function () {
  58387. this._renderPasses = {};
  58388. this._linkParameters();
  58389. };
  58390. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  58391. var cameraKey;
  58392. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  58393. if (!cams) {
  58394. return;
  58395. }
  58396. for (var i = 0; i < cams.length; i++) {
  58397. var camera = cams[i];
  58398. var cameraName = camera.name;
  58399. if (this._singleInstance) {
  58400. cameraKey = 0;
  58401. }
  58402. else {
  58403. cameraKey = cameraName;
  58404. }
  58405. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  58406. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  58407. if (!this._indicesForCamera[cameraName]) {
  58408. this._indicesForCamera[cameraName] = [];
  58409. }
  58410. this._indicesForCamera[cameraName].push(index);
  58411. if (!this._cameras[cameraName]) {
  58412. this._cameras[cameraName] = camera;
  58413. }
  58414. for (var passName in this._renderPasses) {
  58415. this._renderPasses[passName]._incRefCount();
  58416. }
  58417. }
  58418. this._linkParameters();
  58419. };
  58420. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  58421. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  58422. if (!cams) {
  58423. return;
  58424. }
  58425. for (var i = 0; i < cams.length; i++) {
  58426. var camera = cams[i];
  58427. var cameraName = camera.name;
  58428. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  58429. if (this._cameras[cameraName]) {
  58430. //this._indicesForCamera.splice(index, 1);
  58431. this._cameras[cameraName] = null;
  58432. }
  58433. for (var passName in this._renderPasses) {
  58434. this._renderPasses[passName]._decRefCount();
  58435. }
  58436. }
  58437. };
  58438. PostProcessRenderEffect.prototype._enable = function (cameras) {
  58439. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  58440. if (!cams) {
  58441. return;
  58442. }
  58443. for (var i = 0; i < cams.length; i++) {
  58444. var camera = cams[i];
  58445. var cameraName = camera.name;
  58446. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  58447. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  58448. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  58449. }
  58450. }
  58451. for (var passName in this._renderPasses) {
  58452. this._renderPasses[passName]._incRefCount();
  58453. }
  58454. }
  58455. };
  58456. PostProcessRenderEffect.prototype._disable = function (cameras) {
  58457. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  58458. if (!cams) {
  58459. return;
  58460. }
  58461. for (var i = 0; i < cams.length; i++) {
  58462. var camera = cams[i];
  58463. var cameraName = camera.Name;
  58464. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  58465. for (var passName in this._renderPasses) {
  58466. this._renderPasses[passName]._decRefCount();
  58467. }
  58468. }
  58469. };
  58470. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  58471. if (this._singleInstance) {
  58472. return this._postProcesses[0];
  58473. }
  58474. else {
  58475. if (!camera) {
  58476. return null;
  58477. }
  58478. return this._postProcesses[camera.name];
  58479. }
  58480. };
  58481. PostProcessRenderEffect.prototype._linkParameters = function () {
  58482. var _this = this;
  58483. for (var index in this._postProcesses) {
  58484. if (this.applyParameters) {
  58485. this.applyParameters(this._postProcesses[index]);
  58486. }
  58487. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  58488. _this._linkTextures(effect);
  58489. });
  58490. }
  58491. };
  58492. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  58493. for (var renderPassName in this._renderPasses) {
  58494. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  58495. }
  58496. for (var renderEffectName in this._renderEffectAsPasses) {
  58497. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  58498. }
  58499. };
  58500. return PostProcessRenderEffect;
  58501. }());
  58502. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  58503. })(BABYLON || (BABYLON = {}));
  58504. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  58505. var BABYLON;
  58506. (function (BABYLON) {
  58507. var PostProcessRenderPipeline = /** @class */ (function () {
  58508. function PostProcessRenderPipeline(engine, name) {
  58509. this._engine = engine;
  58510. this._name = name;
  58511. this._renderEffects = {};
  58512. this._renderEffectsForIsolatedPass = new Array();
  58513. this._cameras = [];
  58514. }
  58515. PostProcessRenderPipeline.prototype.getClassName = function () {
  58516. return "PostProcessRenderPipeline";
  58517. };
  58518. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  58519. get: function () {
  58520. for (var renderEffectName in this._renderEffects) {
  58521. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  58522. if (!this._renderEffects[renderEffectName].isSupported) {
  58523. return false;
  58524. }
  58525. }
  58526. }
  58527. return true;
  58528. },
  58529. enumerable: true,
  58530. configurable: true
  58531. });
  58532. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  58533. this._renderEffects[renderEffect._name] = renderEffect;
  58534. };
  58535. // private
  58536. PostProcessRenderPipeline.prototype._rebuild = function () {
  58537. };
  58538. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  58539. var renderEffects = this._renderEffects[renderEffectName];
  58540. if (!renderEffects) {
  58541. return;
  58542. }
  58543. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  58544. };
  58545. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  58546. var renderEffects = this._renderEffects[renderEffectName];
  58547. if (!renderEffects) {
  58548. return;
  58549. }
  58550. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  58551. };
  58552. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  58553. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  58554. if (!cams) {
  58555. return;
  58556. }
  58557. var indicesToDelete = [];
  58558. var i;
  58559. for (i = 0; i < cams.length; i++) {
  58560. var camera = cams[i];
  58561. var cameraName = camera.name;
  58562. if (this._cameras.indexOf(camera) === -1) {
  58563. this._cameras[cameraName] = camera;
  58564. }
  58565. else if (unique) {
  58566. indicesToDelete.push(i);
  58567. }
  58568. }
  58569. for (i = 0; i < indicesToDelete.length; i++) {
  58570. cameras.splice(indicesToDelete[i], 1);
  58571. }
  58572. for (var renderEffectName in this._renderEffects) {
  58573. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  58574. this._renderEffects[renderEffectName]._attachCameras(cams);
  58575. }
  58576. }
  58577. };
  58578. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  58579. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  58580. if (!cams) {
  58581. return;
  58582. }
  58583. for (var renderEffectName in this._renderEffects) {
  58584. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  58585. this._renderEffects[renderEffectName]._detachCameras(cams);
  58586. }
  58587. }
  58588. for (var i = 0; i < cams.length; i++) {
  58589. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  58590. }
  58591. };
  58592. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  58593. var _this = this;
  58594. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  58595. if (!cams) {
  58596. return;
  58597. }
  58598. var pass = null;
  58599. var renderEffectName;
  58600. for (renderEffectName in this._renderEffects) {
  58601. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  58602. pass = this._renderEffects[renderEffectName].getPass(passName);
  58603. if (pass != null) {
  58604. break;
  58605. }
  58606. }
  58607. }
  58608. if (pass === null) {
  58609. return;
  58610. }
  58611. for (renderEffectName in this._renderEffects) {
  58612. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  58613. this._renderEffects[renderEffectName]._disable(cams);
  58614. }
  58615. }
  58616. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  58617. for (var i = 0; i < cams.length; i++) {
  58618. var camera = cams[i];
  58619. var cameraName = camera.name;
  58620. 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); });
  58621. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  58622. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  58623. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  58624. }
  58625. };
  58626. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  58627. var _this = this;
  58628. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  58629. if (!cams) {
  58630. return;
  58631. }
  58632. for (var i = 0; i < cams.length; i++) {
  58633. var camera = cams[i];
  58634. var cameraName = camera.name;
  58635. 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); });
  58636. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  58637. }
  58638. for (var renderEffectName in this._renderEffects) {
  58639. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  58640. this._renderEffects[renderEffectName]._enable(cams);
  58641. }
  58642. }
  58643. };
  58644. PostProcessRenderPipeline.prototype._update = function () {
  58645. for (var renderEffectName in this._renderEffects) {
  58646. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  58647. this._renderEffects[renderEffectName]._update();
  58648. }
  58649. }
  58650. for (var i = 0; i < this._cameras.length; i++) {
  58651. var cameraName = this._cameras[i].name;
  58652. if (this._renderEffectsForIsolatedPass[cameraName]) {
  58653. this._renderEffectsForIsolatedPass[cameraName]._update();
  58654. }
  58655. }
  58656. };
  58657. PostProcessRenderPipeline.prototype._reset = function () {
  58658. this._renderEffects = {};
  58659. this._renderEffectsForIsolatedPass = new Array();
  58660. };
  58661. PostProcessRenderPipeline.prototype.dispose = function () {
  58662. // Must be implemented by children
  58663. };
  58664. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  58665. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  58666. __decorate([
  58667. BABYLON.serialize()
  58668. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  58669. return PostProcessRenderPipeline;
  58670. }());
  58671. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  58672. })(BABYLON || (BABYLON = {}));
  58673. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  58674. var BABYLON;
  58675. (function (BABYLON) {
  58676. var DepthRenderer = /** @class */ (function () {
  58677. function DepthRenderer(scene, type) {
  58678. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  58679. var _this = this;
  58680. this._scene = scene;
  58681. var engine = scene.getEngine();
  58682. // Render target
  58683. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  58684. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58685. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58686. this._depthMap.refreshRate = 1;
  58687. this._depthMap.renderParticles = false;
  58688. this._depthMap.renderList = null;
  58689. // set default depth value to 1.0 (far away)
  58690. this._depthMap.onClearObservable.add(function (engine) {
  58691. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  58692. });
  58693. // Custom render function
  58694. var renderSubMesh = function (subMesh) {
  58695. var mesh = subMesh.getRenderingMesh();
  58696. var scene = _this._scene;
  58697. var engine = scene.getEngine();
  58698. var material = subMesh.getMaterial();
  58699. if (!material) {
  58700. return;
  58701. }
  58702. // Culling and reverse (right handed system)
  58703. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  58704. // Managing instances
  58705. var batch = mesh._getInstancesRenderList(subMesh._id);
  58706. if (batch.mustReturn) {
  58707. return;
  58708. }
  58709. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  58710. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  58711. engine.enableEffect(_this._effect);
  58712. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  58713. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  58714. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  58715. // Alpha test
  58716. if (material && material.needAlphaTesting()) {
  58717. var alphaTexture = material.getAlphaTestTexture();
  58718. if (alphaTexture) {
  58719. _this._effect.setTexture("diffuseSampler", alphaTexture);
  58720. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  58721. }
  58722. }
  58723. // Bones
  58724. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  58725. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  58726. }
  58727. // Draw
  58728. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  58729. }
  58730. };
  58731. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  58732. var index;
  58733. if (depthOnlySubMeshes.length) {
  58734. engine.setColorWrite(false);
  58735. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  58736. renderSubMesh(depthOnlySubMeshes.data[index]);
  58737. }
  58738. engine.setColorWrite(true);
  58739. }
  58740. for (index = 0; index < opaqueSubMeshes.length; index++) {
  58741. renderSubMesh(opaqueSubMeshes.data[index]);
  58742. }
  58743. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  58744. renderSubMesh(alphaTestSubMeshes.data[index]);
  58745. }
  58746. };
  58747. }
  58748. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  58749. var material = subMesh.getMaterial();
  58750. if (material.disableDepthWrite) {
  58751. return false;
  58752. }
  58753. var defines = [];
  58754. var attribs = [BABYLON.VertexBuffer.PositionKind];
  58755. var mesh = subMesh.getMesh();
  58756. // Alpha test
  58757. if (material && material.needAlphaTesting()) {
  58758. defines.push("#define ALPHATEST");
  58759. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  58760. attribs.push(BABYLON.VertexBuffer.UVKind);
  58761. defines.push("#define UV1");
  58762. }
  58763. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  58764. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  58765. defines.push("#define UV2");
  58766. }
  58767. }
  58768. // Bones
  58769. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58770. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58771. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58772. if (mesh.numBoneInfluencers > 4) {
  58773. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58774. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58775. }
  58776. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58777. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  58778. }
  58779. else {
  58780. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58781. }
  58782. // Instances
  58783. if (useInstances) {
  58784. defines.push("#define INSTANCES");
  58785. attribs.push("world0");
  58786. attribs.push("world1");
  58787. attribs.push("world2");
  58788. attribs.push("world3");
  58789. }
  58790. // Get correct effect
  58791. var join = defines.join("\n");
  58792. if (this._cachedDefines !== join) {
  58793. this._cachedDefines = join;
  58794. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  58795. }
  58796. return this._effect.isReady();
  58797. };
  58798. DepthRenderer.prototype.getDepthMap = function () {
  58799. return this._depthMap;
  58800. };
  58801. // Methods
  58802. DepthRenderer.prototype.dispose = function () {
  58803. this._depthMap.dispose();
  58804. };
  58805. return DepthRenderer;
  58806. }());
  58807. BABYLON.DepthRenderer = DepthRenderer;
  58808. })(BABYLON || (BABYLON = {}));
  58809. //# sourceMappingURL=babylon.depthRenderer.js.map
  58810. var BABYLON;
  58811. (function (BABYLON) {
  58812. var SSAORenderingPipeline = /** @class */ (function (_super) {
  58813. __extends(SSAORenderingPipeline, _super);
  58814. /**
  58815. * @constructor
  58816. * @param {string} name - The rendering pipeline name
  58817. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58818. * @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 }
  58819. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58820. */
  58821. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  58822. var _this = _super.call(this, scene.getEngine(), name) || this;
  58823. // Members
  58824. /**
  58825. * The PassPostProcess id in the pipeline that contains the original scene color
  58826. * @type {string}
  58827. */
  58828. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  58829. /**
  58830. * The SSAO PostProcess id in the pipeline
  58831. * @type {string}
  58832. */
  58833. _this.SSAORenderEffect = "SSAORenderEffect";
  58834. /**
  58835. * The horizontal blur PostProcess id in the pipeline
  58836. * @type {string}
  58837. */
  58838. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  58839. /**
  58840. * The vertical blur PostProcess id in the pipeline
  58841. * @type {string}
  58842. */
  58843. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  58844. /**
  58845. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  58846. * @type {string}
  58847. */
  58848. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  58849. /**
  58850. * The output strength of the SSAO post-process. Default value is 1.0.
  58851. * @type {number}
  58852. */
  58853. _this.totalStrength = 1.0;
  58854. /**
  58855. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  58856. * @type {number}
  58857. */
  58858. _this.radius = 0.0001;
  58859. /**
  58860. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  58861. * Must not be equal to fallOff and superior to fallOff.
  58862. * Default value is 0.975
  58863. * @type {number}
  58864. */
  58865. _this.area = 0.0075;
  58866. /**
  58867. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  58868. * Must not be equal to area and inferior to area.
  58869. * Default value is 0.0
  58870. * @type {number}
  58871. */
  58872. _this.fallOff = 0.000001;
  58873. /**
  58874. * The base color of the SSAO post-process
  58875. * The final result is "base + ssao" between [0, 1]
  58876. * @type {number}
  58877. */
  58878. _this.base = 0.5;
  58879. _this._firstUpdate = true;
  58880. _this._scene = scene;
  58881. // Set up assets
  58882. _this._createRandomTexture();
  58883. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  58884. var ssaoRatio = ratio.ssaoRatio || ratio;
  58885. var combineRatio = ratio.combineRatio || ratio;
  58886. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  58887. _this._createSSAOPostProcess(ssaoRatio);
  58888. _this._createBlurPostProcess(ssaoRatio);
  58889. _this._createSSAOCombinePostProcess(combineRatio);
  58890. // Set up pipeline
  58891. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  58892. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  58893. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  58894. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  58895. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  58896. // Finish
  58897. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58898. if (cameras)
  58899. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  58900. return _this;
  58901. }
  58902. // Public Methods
  58903. /**
  58904. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  58905. */
  58906. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  58907. if (disableDepthRender === void 0) { disableDepthRender = false; }
  58908. for (var i = 0; i < this._scene.cameras.length; i++) {
  58909. var camera = this._scene.cameras[i];
  58910. this._originalColorPostProcess.dispose(camera);
  58911. this._ssaoPostProcess.dispose(camera);
  58912. this._blurHPostProcess.dispose(camera);
  58913. this._blurVPostProcess.dispose(camera);
  58914. this._ssaoCombinePostProcess.dispose(camera);
  58915. }
  58916. this._randomTexture.dispose();
  58917. if (disableDepthRender)
  58918. this._scene.disableDepthRenderer();
  58919. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  58920. _super.prototype.dispose.call(this);
  58921. };
  58922. // Private Methods
  58923. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  58924. var _this = this;
  58925. var size = 16;
  58926. 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);
  58927. 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);
  58928. this._blurHPostProcess.onActivateObservable.add(function () {
  58929. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  58930. _this._blurHPostProcess.kernel = size * dw;
  58931. });
  58932. this._blurVPostProcess.onActivateObservable.add(function () {
  58933. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  58934. _this._blurVPostProcess.kernel = size * dw;
  58935. });
  58936. };
  58937. SSAORenderingPipeline.prototype._rebuild = function () {
  58938. this._firstUpdate = true;
  58939. _super.prototype._rebuild.call(this);
  58940. };
  58941. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  58942. var _this = this;
  58943. var numSamples = 16;
  58944. var sampleSphere = [
  58945. 0.5381, 0.1856, -0.4319,
  58946. 0.1379, 0.2486, 0.4430,
  58947. 0.3371, 0.5679, -0.0057,
  58948. -0.6999, -0.0451, -0.0019,
  58949. 0.0689, -0.1598, -0.8547,
  58950. 0.0560, 0.0069, -0.1843,
  58951. -0.0146, 0.1402, 0.0762,
  58952. 0.0100, -0.1924, -0.0344,
  58953. -0.3577, -0.5301, -0.4358,
  58954. -0.3169, 0.1063, 0.0158,
  58955. 0.0103, -0.5869, 0.0046,
  58956. -0.0897, -0.4940, 0.3287,
  58957. 0.7119, -0.0154, -0.0918,
  58958. -0.0533, 0.0596, -0.5411,
  58959. 0.0352, -0.0631, 0.5460,
  58960. -0.4776, 0.2847, -0.0271
  58961. ];
  58962. var samplesFactor = 1.0 / numSamples;
  58963. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  58964. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  58965. "area", "fallOff", "base", "range", "viewport"
  58966. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  58967. this._ssaoPostProcess.onApply = function (effect) {
  58968. if (_this._firstUpdate) {
  58969. effect.setArray3("sampleSphere", sampleSphere);
  58970. effect.setFloat("samplesFactor", samplesFactor);
  58971. effect.setFloat("randTextureTiles", 4.0);
  58972. }
  58973. effect.setFloat("totalStrength", _this.totalStrength);
  58974. effect.setFloat("radius", _this.radius);
  58975. effect.setFloat("area", _this.area);
  58976. effect.setFloat("fallOff", _this.fallOff);
  58977. effect.setFloat("base", _this.base);
  58978. effect.setTexture("textureSampler", _this._depthTexture);
  58979. effect.setTexture("randomSampler", _this._randomTexture);
  58980. };
  58981. };
  58982. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  58983. var _this = this;
  58984. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  58985. this._ssaoCombinePostProcess.onApply = function (effect) {
  58986. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  58987. };
  58988. };
  58989. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  58990. var size = 512;
  58991. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  58992. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58993. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58994. var context = this._randomTexture.getContext();
  58995. var rand = function (min, max) {
  58996. return Math.random() * (max - min) + min;
  58997. };
  58998. var randVector = BABYLON.Vector3.Zero();
  58999. for (var x = 0; x < size; x++) {
  59000. for (var y = 0; y < size; y++) {
  59001. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  59002. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  59003. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  59004. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  59005. context.fillRect(x, y, 1, 1);
  59006. }
  59007. }
  59008. this._randomTexture.update(false);
  59009. };
  59010. __decorate([
  59011. BABYLON.serialize()
  59012. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  59013. __decorate([
  59014. BABYLON.serialize()
  59015. ], SSAORenderingPipeline.prototype, "radius", void 0);
  59016. __decorate([
  59017. BABYLON.serialize()
  59018. ], SSAORenderingPipeline.prototype, "area", void 0);
  59019. __decorate([
  59020. BABYLON.serialize()
  59021. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  59022. __decorate([
  59023. BABYLON.serialize()
  59024. ], SSAORenderingPipeline.prototype, "base", void 0);
  59025. return SSAORenderingPipeline;
  59026. }(BABYLON.PostProcessRenderPipeline));
  59027. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  59028. })(BABYLON || (BABYLON = {}));
  59029. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  59030. var BABYLON;
  59031. (function (BABYLON) {
  59032. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  59033. __extends(SSAO2RenderingPipeline, _super);
  59034. /**
  59035. * @constructor
  59036. * @param {string} name - The rendering pipeline name
  59037. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  59038. * @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 }
  59039. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  59040. */
  59041. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  59042. var _this = _super.call(this, scene.getEngine(), name) || this;
  59043. // Members
  59044. /**
  59045. * The PassPostProcess id in the pipeline that contains the original scene color
  59046. * @type {string}
  59047. */
  59048. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  59049. /**
  59050. * The SSAO PostProcess id in the pipeline
  59051. * @type {string}
  59052. */
  59053. _this.SSAORenderEffect = "SSAORenderEffect";
  59054. /**
  59055. * The horizontal blur PostProcess id in the pipeline
  59056. * @type {string}
  59057. */
  59058. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  59059. /**
  59060. * The vertical blur PostProcess id in the pipeline
  59061. * @type {string}
  59062. */
  59063. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  59064. /**
  59065. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  59066. * @type {string}
  59067. */
  59068. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  59069. /**
  59070. * The output strength of the SSAO post-process. Default value is 1.0.
  59071. * @type {number}
  59072. */
  59073. _this.totalStrength = 1.0;
  59074. /**
  59075. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  59076. * @type {number}
  59077. */
  59078. _this.maxZ = 100.0;
  59079. /**
  59080. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  59081. * @type {number}
  59082. */
  59083. _this.minZAspect = 0.2;
  59084. /**
  59085. * Number of samples used for the SSAO calculations. Default value is 8
  59086. * @type {number}
  59087. */
  59088. _this._samples = 8;
  59089. /**
  59090. * Are we using bilateral blur ?
  59091. * @type {boolean}
  59092. */
  59093. _this._expensiveBlur = true;
  59094. /**
  59095. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  59096. * @type {number}
  59097. */
  59098. _this.radius = 2.0;
  59099. /**
  59100. * The base color of the SSAO post-process
  59101. * The final result is "base + ssao" between [0, 1]
  59102. * @type {number}
  59103. */
  59104. _this.base = 0.1;
  59105. _this._firstUpdate = true;
  59106. _this._scene = scene;
  59107. if (!_this.isSupported) {
  59108. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  59109. return _this;
  59110. }
  59111. var ssaoRatio = ratio.ssaoRatio || ratio;
  59112. var blurRatio = ratio.blurRatio || ratio;
  59113. // Set up assets
  59114. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  59115. _this._createRandomTexture();
  59116. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  59117. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  59118. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  59119. _this._createSSAOPostProcess(1.0);
  59120. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  59121. _this._createSSAOCombinePostProcess(blurRatio);
  59122. // Set up pipeline
  59123. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  59124. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  59125. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  59126. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  59127. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  59128. // Finish
  59129. scene.postProcessRenderPipelineManager.addPipeline(_this);
  59130. if (cameras)
  59131. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  59132. return _this;
  59133. }
  59134. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  59135. get: function () {
  59136. return this._samples;
  59137. },
  59138. set: function (n) {
  59139. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  59140. this._samples = n;
  59141. this._sampleSphere = this._generateHemisphere();
  59142. this._firstUpdate = true;
  59143. },
  59144. enumerable: true,
  59145. configurable: true
  59146. });
  59147. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  59148. get: function () {
  59149. return this._expensiveBlur;
  59150. },
  59151. set: function (b) {
  59152. 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"]);
  59153. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  59154. this._expensiveBlur = b;
  59155. this._firstUpdate = true;
  59156. },
  59157. enumerable: true,
  59158. configurable: true
  59159. });
  59160. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  59161. /**
  59162. * Support test.
  59163. * @type {boolean}
  59164. */
  59165. get: function () {
  59166. var engine = BABYLON.Engine.LastCreatedEngine;
  59167. if (!engine) {
  59168. return false;
  59169. }
  59170. return engine.getCaps().drawBuffersExtension;
  59171. },
  59172. enumerable: true,
  59173. configurable: true
  59174. });
  59175. // Public Methods
  59176. /**
  59177. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  59178. */
  59179. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  59180. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  59181. for (var i = 0; i < this._scene.cameras.length; i++) {
  59182. var camera = this._scene.cameras[i];
  59183. this._originalColorPostProcess.dispose(camera);
  59184. this._ssaoPostProcess.dispose(camera);
  59185. this._blurHPostProcess.dispose(camera);
  59186. this._blurVPostProcess.dispose(camera);
  59187. this._ssaoCombinePostProcess.dispose(camera);
  59188. }
  59189. this._randomTexture.dispose();
  59190. if (disableGeometryBufferRenderer)
  59191. this._scene.disableGeometryBufferRenderer();
  59192. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  59193. _super.prototype.dispose.call(this);
  59194. };
  59195. // Private Methods
  59196. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  59197. var _this = this;
  59198. this._samplerOffsets = [];
  59199. var expensive = this.expensiveBlur;
  59200. for (var i = -8; i < 8; i++) {
  59201. this._samplerOffsets.push(i * 2 + 0.5);
  59202. }
  59203. 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");
  59204. this._blurHPostProcess.onApply = function (effect) {
  59205. if (!_this._scene.activeCamera) {
  59206. return;
  59207. }
  59208. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  59209. effect.setFloat("near", _this._scene.activeCamera.minZ);
  59210. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  59211. effect.setFloat("radius", _this.radius);
  59212. effect.setTexture("depthSampler", _this._depthTexture);
  59213. if (_this._firstUpdate) {
  59214. effect.setArray("samplerOffsets", _this._samplerOffsets);
  59215. }
  59216. };
  59217. 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");
  59218. this._blurVPostProcess.onApply = function (effect) {
  59219. if (!_this._scene.activeCamera) {
  59220. return;
  59221. }
  59222. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  59223. effect.setFloat("near", _this._scene.activeCamera.minZ);
  59224. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  59225. effect.setFloat("radius", _this.radius);
  59226. effect.setTexture("depthSampler", _this._depthTexture);
  59227. if (_this._firstUpdate) {
  59228. effect.setArray("samplerOffsets", _this._samplerOffsets);
  59229. _this._firstUpdate = false;
  59230. }
  59231. };
  59232. };
  59233. SSAO2RenderingPipeline.prototype._rebuild = function () {
  59234. this._firstUpdate = true;
  59235. _super.prototype._rebuild.call(this);
  59236. };
  59237. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  59238. var numSamples = this.samples;
  59239. var result = [];
  59240. var vector, scale;
  59241. var rand = function (min, max) {
  59242. return Math.random() * (max - min) + min;
  59243. };
  59244. var i = 0;
  59245. while (i < numSamples) {
  59246. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  59247. vector.normalize();
  59248. scale = i / numSamples;
  59249. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  59250. vector.scaleInPlace(scale);
  59251. result.push(vector.x, vector.y, vector.z);
  59252. i++;
  59253. }
  59254. return result;
  59255. };
  59256. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  59257. var _this = this;
  59258. var numSamples = this.samples;
  59259. this._sampleSphere = this._generateHemisphere();
  59260. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  59261. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  59262. "base", "range", "projection", "near", "far", "texelSize",
  59263. "xViewport", "yViewport", "maxZ", "minZAspect"
  59264. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  59265. this._ssaoPostProcess.onApply = function (effect) {
  59266. if (_this._firstUpdate) {
  59267. effect.setArray3("sampleSphere", _this._sampleSphere);
  59268. effect.setFloat("randTextureTiles", 4.0);
  59269. }
  59270. if (!_this._scene.activeCamera) {
  59271. return;
  59272. }
  59273. effect.setFloat("samplesFactor", 1 / _this.samples);
  59274. effect.setFloat("totalStrength", _this.totalStrength);
  59275. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  59276. effect.setFloat("radius", _this.radius);
  59277. effect.setFloat("maxZ", _this.maxZ);
  59278. effect.setFloat("minZAspect", _this.minZAspect);
  59279. effect.setFloat("base", _this.base);
  59280. effect.setFloat("near", _this._scene.activeCamera.minZ);
  59281. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  59282. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  59283. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  59284. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  59285. effect.setTexture("textureSampler", _this._depthTexture);
  59286. effect.setTexture("normalSampler", _this._normalTexture);
  59287. effect.setTexture("randomSampler", _this._randomTexture);
  59288. };
  59289. };
  59290. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  59291. var _this = this;
  59292. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  59293. this._ssaoCombinePostProcess.onApply = function (effect) {
  59294. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  59295. };
  59296. };
  59297. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  59298. var size = 512;
  59299. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  59300. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  59301. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  59302. var context = this._randomTexture.getContext();
  59303. var rand = function (min, max) {
  59304. return Math.random() * (max - min) + min;
  59305. };
  59306. var randVector = BABYLON.Vector3.Zero();
  59307. for (var x = 0; x < size; x++) {
  59308. for (var y = 0; y < size; y++) {
  59309. randVector.x = rand(0.0, 1.0);
  59310. randVector.y = rand(0.0, 1.0);
  59311. randVector.z = 0.0;
  59312. randVector.normalize();
  59313. randVector.scaleInPlace(255);
  59314. randVector.x = Math.floor(randVector.x);
  59315. randVector.y = Math.floor(randVector.y);
  59316. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  59317. context.fillRect(x, y, 1, 1);
  59318. }
  59319. }
  59320. this._randomTexture.update(false);
  59321. };
  59322. __decorate([
  59323. BABYLON.serialize()
  59324. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  59325. __decorate([
  59326. BABYLON.serialize()
  59327. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  59328. __decorate([
  59329. BABYLON.serialize()
  59330. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  59331. __decorate([
  59332. BABYLON.serialize("samples")
  59333. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  59334. __decorate([
  59335. BABYLON.serialize("expensiveBlur")
  59336. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  59337. __decorate([
  59338. BABYLON.serialize()
  59339. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  59340. __decorate([
  59341. BABYLON.serialize()
  59342. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  59343. return SSAO2RenderingPipeline;
  59344. }(BABYLON.PostProcessRenderPipeline));
  59345. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  59346. })(BABYLON || (BABYLON = {}));
  59347. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  59348. // BABYLON.JS Chromatic Aberration GLSL Shader
  59349. // Author: Olivier Guyot
  59350. // Separates very slightly R, G and B colors on the edges of the screen
  59351. // Inspired by Francois Tarlier & Martins Upitis
  59352. var BABYLON;
  59353. (function (BABYLON) {
  59354. var LensRenderingPipeline = /** @class */ (function (_super) {
  59355. __extends(LensRenderingPipeline, _super);
  59356. /**
  59357. * @constructor
  59358. *
  59359. * Effect parameters are as follow:
  59360. * {
  59361. * chromatic_aberration: number; // from 0 to x (1 for realism)
  59362. * edge_blur: number; // from 0 to x (1 for realism)
  59363. * distortion: number; // from 0 to x (1 for realism)
  59364. * grain_amount: number; // from 0 to 1
  59365. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  59366. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  59367. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  59368. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  59369. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  59370. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  59371. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  59372. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  59373. * }
  59374. * Note: if an effect parameter is unset, effect is disabled
  59375. *
  59376. * @param {string} name - The rendering pipeline name
  59377. * @param {object} parameters - An object containing all parameters (see above)
  59378. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  59379. * @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)
  59380. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  59381. */
  59382. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  59383. if (ratio === void 0) { ratio = 1.0; }
  59384. var _this = _super.call(this, scene.getEngine(), name) || this;
  59385. // Lens effects can be of the following:
  59386. // - chromatic aberration (slight shift of RGB colors)
  59387. // - blur on the edge of the lens
  59388. // - lens distortion
  59389. // - depth-of-field blur & highlights enhancing
  59390. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  59391. // - grain effect (noise or custom texture)
  59392. // Two additional texture samplers are needed:
  59393. // - depth map (for depth-of-field)
  59394. // - grain texture
  59395. /**
  59396. * The chromatic aberration PostProcess id in the pipeline
  59397. * @type {string}
  59398. */
  59399. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  59400. /**
  59401. * The highlights enhancing PostProcess id in the pipeline
  59402. * @type {string}
  59403. */
  59404. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  59405. /**
  59406. * The depth-of-field PostProcess id in the pipeline
  59407. * @type {string}
  59408. */
  59409. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  59410. _this._scene = scene;
  59411. // Fetch texture samplers
  59412. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  59413. if (parameters.grain_texture) {
  59414. _this._grainTexture = parameters.grain_texture;
  59415. }
  59416. else {
  59417. _this._createGrainTexture();
  59418. }
  59419. // save parameters
  59420. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  59421. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  59422. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  59423. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  59424. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  59425. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  59426. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  59427. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  59428. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  59429. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  59430. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  59431. // Create effects
  59432. _this._createChromaticAberrationPostProcess(ratio);
  59433. _this._createHighlightsPostProcess(ratio);
  59434. _this._createDepthOfFieldPostProcess(ratio / 4);
  59435. // Set up pipeline
  59436. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  59437. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  59438. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  59439. if (_this._highlightsGain === -1) {
  59440. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  59441. }
  59442. // Finish
  59443. scene.postProcessRenderPipelineManager.addPipeline(_this);
  59444. if (cameras) {
  59445. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  59446. }
  59447. return _this;
  59448. }
  59449. // public methods (self explanatory)
  59450. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  59451. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  59452. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  59453. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  59454. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  59455. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  59456. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  59457. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  59458. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  59459. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  59460. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  59461. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  59462. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  59463. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  59464. };
  59465. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  59466. this._highlightsPostProcess.updateEffect();
  59467. };
  59468. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  59469. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  59470. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  59471. this._highlightsGain = amount;
  59472. };
  59473. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  59474. if (this._highlightsGain === -1) {
  59475. this._highlightsGain = 1.0;
  59476. }
  59477. this._highlightsThreshold = amount;
  59478. };
  59479. LensRenderingPipeline.prototype.disableHighlights = function () {
  59480. this._highlightsGain = -1;
  59481. };
  59482. /**
  59483. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  59484. */
  59485. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  59486. if (disableDepthRender === void 0) { disableDepthRender = false; }
  59487. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  59488. this._chromaticAberrationPostProcess = null;
  59489. this._highlightsPostProcess = null;
  59490. this._depthOfFieldPostProcess = null;
  59491. this._grainTexture.dispose();
  59492. if (disableDepthRender)
  59493. this._scene.disableDepthRenderer();
  59494. };
  59495. // colors shifting and distortion
  59496. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  59497. var _this = this;
  59498. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  59499. [], // samplers
  59500. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  59501. this._chromaticAberrationPostProcess.onApply = function (effect) {
  59502. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  59503. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  59504. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  59505. };
  59506. };
  59507. // highlights enhancing
  59508. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  59509. var _this = this;
  59510. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  59511. [], // samplers
  59512. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  59513. this._highlightsPostProcess.onApply = function (effect) {
  59514. effect.setFloat('gain', _this._highlightsGain);
  59515. effect.setFloat('threshold', _this._highlightsThreshold);
  59516. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  59517. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  59518. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  59519. };
  59520. };
  59521. // colors shifting and distortion
  59522. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  59523. var _this = this;
  59524. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  59525. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  59526. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  59527. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  59528. this._depthOfFieldPostProcess.onApply = function (effect) {
  59529. effect.setTexture("depthSampler", _this._depthTexture);
  59530. effect.setTexture("grainSampler", _this._grainTexture);
  59531. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  59532. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  59533. effect.setFloat('grain_amount', _this._grainAmount);
  59534. effect.setBool('blur_noise', _this._blurNoise);
  59535. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  59536. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  59537. effect.setFloat('distortion', _this._distortion);
  59538. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  59539. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  59540. effect.setFloat('aperture', _this._dofAperture);
  59541. effect.setFloat('darken', _this._dofDarken);
  59542. effect.setFloat('edge_blur', _this._edgeBlur);
  59543. effect.setBool('highlights', (_this._highlightsGain !== -1));
  59544. if (_this._scene.activeCamera) {
  59545. effect.setFloat('near', _this._scene.activeCamera.minZ);
  59546. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  59547. }
  59548. };
  59549. };
  59550. // creates a black and white random noise texture, 512x512
  59551. LensRenderingPipeline.prototype._createGrainTexture = function () {
  59552. var size = 512;
  59553. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59554. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  59555. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  59556. var context = this._grainTexture.getContext();
  59557. var rand = function (min, max) {
  59558. return Math.random() * (max - min) + min;
  59559. };
  59560. var value;
  59561. for (var x = 0; x < size; x++) {
  59562. for (var y = 0; y < size; y++) {
  59563. value = Math.floor(rand(0.42, 0.58) * 255);
  59564. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  59565. context.fillRect(x, y, 1, 1);
  59566. }
  59567. }
  59568. this._grainTexture.update(false);
  59569. };
  59570. return LensRenderingPipeline;
  59571. }(BABYLON.PostProcessRenderPipeline));
  59572. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  59573. })(BABYLON || (BABYLON = {}));
  59574. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  59575. var BABYLON;
  59576. (function (BABYLON) {
  59577. var StandardRenderingPipeline = /** @class */ (function (_super) {
  59578. __extends(StandardRenderingPipeline, _super);
  59579. /**
  59580. * @constructor
  59581. * @param {string} name - The rendering pipeline name
  59582. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  59583. * @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)
  59584. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  59585. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  59586. */
  59587. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  59588. if (originalPostProcess === void 0) { originalPostProcess = null; }
  59589. var _this = _super.call(this, scene.getEngine(), name) || this;
  59590. _this.downSampleX4PostProcess = null;
  59591. _this.brightPassPostProcess = null;
  59592. _this.blurHPostProcesses = [];
  59593. _this.blurVPostProcesses = [];
  59594. _this.textureAdderPostProcess = null;
  59595. _this.volumetricLightPostProcess = null;
  59596. _this.volumetricLightSmoothXPostProcess = null;
  59597. _this.volumetricLightSmoothYPostProcess = null;
  59598. _this.volumetricLightMergePostProces = null;
  59599. _this.volumetricLightFinalPostProcess = null;
  59600. _this.luminancePostProcess = null;
  59601. _this.luminanceDownSamplePostProcesses = [];
  59602. _this.hdrPostProcess = null;
  59603. _this.textureAdderFinalPostProcess = null;
  59604. _this.lensFlareFinalPostProcess = null;
  59605. _this.hdrFinalPostProcess = null;
  59606. _this.lensFlarePostProcess = null;
  59607. _this.lensFlareComposePostProcess = null;
  59608. _this.motionBlurPostProcess = null;
  59609. _this.depthOfFieldPostProcess = null;
  59610. // Values
  59611. _this.brightThreshold = 1.0;
  59612. _this.blurWidth = 512.0;
  59613. _this.horizontalBlur = false;
  59614. _this.exposure = 1.0;
  59615. _this.lensTexture = null;
  59616. _this.volumetricLightCoefficient = 0.2;
  59617. _this.volumetricLightPower = 4.0;
  59618. _this.volumetricLightBlurScale = 64.0;
  59619. _this.sourceLight = null;
  59620. _this.hdrMinimumLuminance = 1.0;
  59621. _this.hdrDecreaseRate = 0.5;
  59622. _this.hdrIncreaseRate = 0.5;
  59623. _this.lensColorTexture = null;
  59624. _this.lensFlareStrength = 20.0;
  59625. _this.lensFlareGhostDispersal = 1.4;
  59626. _this.lensFlareHaloWidth = 0.7;
  59627. _this.lensFlareDistortionStrength = 16.0;
  59628. _this.lensStarTexture = null;
  59629. _this.lensFlareDirtTexture = null;
  59630. _this.depthOfFieldDistance = 10.0;
  59631. _this.depthOfFieldBlurWidth = 64.0;
  59632. _this.motionStrength = 1.0;
  59633. // IAnimatable
  59634. _this.animations = [];
  59635. _this._currentDepthOfFieldSource = null;
  59636. _this._hdrCurrentLuminance = 1.0;
  59637. // Getters and setters
  59638. _this._bloomEnabled = true;
  59639. _this._depthOfFieldEnabled = false;
  59640. _this._vlsEnabled = false;
  59641. _this._lensFlareEnabled = false;
  59642. _this._hdrEnabled = false;
  59643. _this._motionBlurEnabled = false;
  59644. _this._motionBlurSamples = 64.0;
  59645. _this._volumetricLightStepsCount = 50.0;
  59646. _this._cameras = cameras || [];
  59647. // Initialize
  59648. _this._scene = scene;
  59649. _this._basePostProcess = originalPostProcess;
  59650. _this._ratio = ratio;
  59651. // Misc
  59652. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59653. // Finish
  59654. scene.postProcessRenderPipelineManager.addPipeline(_this);
  59655. _this._buildPipeline();
  59656. return _this;
  59657. }
  59658. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  59659. get: function () {
  59660. return this._bloomEnabled;
  59661. },
  59662. set: function (enabled) {
  59663. if (this._bloomEnabled === enabled) {
  59664. return;
  59665. }
  59666. this._bloomEnabled = enabled;
  59667. this._buildPipeline();
  59668. },
  59669. enumerable: true,
  59670. configurable: true
  59671. });
  59672. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  59673. get: function () {
  59674. return this._depthOfFieldEnabled;
  59675. },
  59676. set: function (enabled) {
  59677. if (this._depthOfFieldEnabled === enabled) {
  59678. return;
  59679. }
  59680. this._depthOfFieldEnabled = enabled;
  59681. this._buildPipeline();
  59682. },
  59683. enumerable: true,
  59684. configurable: true
  59685. });
  59686. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  59687. get: function () {
  59688. return this._lensFlareEnabled;
  59689. },
  59690. set: function (enabled) {
  59691. if (this._lensFlareEnabled === enabled) {
  59692. return;
  59693. }
  59694. this._lensFlareEnabled = enabled;
  59695. this._buildPipeline();
  59696. },
  59697. enumerable: true,
  59698. configurable: true
  59699. });
  59700. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  59701. get: function () {
  59702. return this._hdrEnabled;
  59703. },
  59704. set: function (enabled) {
  59705. if (this._hdrEnabled === enabled) {
  59706. return;
  59707. }
  59708. this._hdrEnabled = enabled;
  59709. this._buildPipeline();
  59710. },
  59711. enumerable: true,
  59712. configurable: true
  59713. });
  59714. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  59715. get: function () {
  59716. return this._vlsEnabled;
  59717. },
  59718. set: function (enabled) {
  59719. if (this._vlsEnabled === enabled) {
  59720. return;
  59721. }
  59722. if (enabled) {
  59723. var geometry = this._scene.enableGeometryBufferRenderer();
  59724. if (!geometry) {
  59725. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  59726. return;
  59727. }
  59728. }
  59729. this._vlsEnabled = enabled;
  59730. this._buildPipeline();
  59731. },
  59732. enumerable: true,
  59733. configurable: true
  59734. });
  59735. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  59736. get: function () {
  59737. return this._motionBlurEnabled;
  59738. },
  59739. set: function (enabled) {
  59740. if (this._motionBlurEnabled === enabled) {
  59741. return;
  59742. }
  59743. this._motionBlurEnabled = enabled;
  59744. this._buildPipeline();
  59745. },
  59746. enumerable: true,
  59747. configurable: true
  59748. });
  59749. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  59750. get: function () {
  59751. return this._volumetricLightStepsCount;
  59752. },
  59753. set: function (count) {
  59754. if (this.volumetricLightPostProcess) {
  59755. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  59756. }
  59757. this._volumetricLightStepsCount = count;
  59758. },
  59759. enumerable: true,
  59760. configurable: true
  59761. });
  59762. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  59763. get: function () {
  59764. return this._motionBlurSamples;
  59765. },
  59766. set: function (samples) {
  59767. if (this.motionBlurPostProcess) {
  59768. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  59769. }
  59770. this._motionBlurSamples = samples;
  59771. },
  59772. enumerable: true,
  59773. configurable: true
  59774. });
  59775. StandardRenderingPipeline.prototype._buildPipeline = function () {
  59776. var _this = this;
  59777. var ratio = this._ratio;
  59778. var scene = this._scene;
  59779. this._disposePostProcesses();
  59780. this._reset();
  59781. // Create pass post-process
  59782. if (!this._basePostProcess) {
  59783. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  59784. this.originalPostProcess.onApply = function (effect) {
  59785. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  59786. };
  59787. }
  59788. else {
  59789. this.originalPostProcess = this._basePostProcess;
  59790. }
  59791. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  59792. this._currentDepthOfFieldSource = this.originalPostProcess;
  59793. if (this._vlsEnabled) {
  59794. // Create volumetric light
  59795. this._createVolumetricLightPostProcess(scene, ratio);
  59796. // Create volumetric light final post-process
  59797. 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);
  59798. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  59799. }
  59800. if (this._bloomEnabled) {
  59801. // Create down sample X4 post-process
  59802. this._createDownSampleX4PostProcess(scene, ratio / 2);
  59803. // Create bright pass post-process
  59804. this._createBrightPassPostProcess(scene, ratio / 2);
  59805. // Create gaussian blur post-processes (down sampling blurs)
  59806. this._createBlurPostProcesses(scene, ratio / 4, 1);
  59807. // Create texture adder post-process
  59808. this._createTextureAdderPostProcess(scene, ratio);
  59809. // Create depth-of-field source post-process
  59810. 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);
  59811. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  59812. }
  59813. if (this._lensFlareEnabled) {
  59814. // Create lens flare post-process
  59815. this._createLensFlarePostProcess(scene, ratio);
  59816. // Create depth-of-field source post-process post lens-flare and disable it now
  59817. 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);
  59818. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  59819. }
  59820. if (this._hdrEnabled) {
  59821. // Create luminance
  59822. this._createLuminancePostProcesses(scene, this._floatTextureType);
  59823. // Create HDR
  59824. this._createHdrPostProcess(scene, ratio);
  59825. // Create depth-of-field source post-process post hdr and disable it now
  59826. 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);
  59827. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  59828. }
  59829. if (this._depthOfFieldEnabled) {
  59830. // Create gaussian blur used by depth-of-field
  59831. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  59832. // Create depth-of-field post-process
  59833. this._createDepthOfFieldPostProcess(scene, ratio);
  59834. }
  59835. if (this._motionBlurEnabled) {
  59836. // Create motion blur post-process
  59837. this._createMotionBlurPostProcess(scene, ratio);
  59838. }
  59839. if (this._cameras !== null) {
  59840. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  59841. }
  59842. };
  59843. // Down Sample X4 Post-Processs
  59844. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  59845. var _this = this;
  59846. var downSampleX4Offsets = new Array(32);
  59847. 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);
  59848. this.downSampleX4PostProcess.onApply = function (effect) {
  59849. var id = 0;
  59850. var width = _this.downSampleX4PostProcess.width;
  59851. var height = _this.downSampleX4PostProcess.height;
  59852. for (var i = -2; i < 2; i++) {
  59853. for (var j = -2; j < 2; j++) {
  59854. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  59855. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  59856. id += 2;
  59857. }
  59858. }
  59859. effect.setArray2("dsOffsets", downSampleX4Offsets);
  59860. };
  59861. // Add to pipeline
  59862. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  59863. };
  59864. // Brightpass Post-Process
  59865. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  59866. var _this = this;
  59867. var brightOffsets = new Array(8);
  59868. 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);
  59869. this.brightPassPostProcess.onApply = function (effect) {
  59870. var sU = (1.0 / _this.brightPassPostProcess.width);
  59871. var sV = (1.0 / _this.brightPassPostProcess.height);
  59872. brightOffsets[0] = -0.5 * sU;
  59873. brightOffsets[1] = 0.5 * sV;
  59874. brightOffsets[2] = 0.5 * sU;
  59875. brightOffsets[3] = 0.5 * sV;
  59876. brightOffsets[4] = -0.5 * sU;
  59877. brightOffsets[5] = -0.5 * sV;
  59878. brightOffsets[6] = 0.5 * sU;
  59879. brightOffsets[7] = -0.5 * sV;
  59880. effect.setArray2("dsOffsets", brightOffsets);
  59881. effect.setFloat("brightThreshold", _this.brightThreshold);
  59882. };
  59883. // Add to pipeline
  59884. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  59885. };
  59886. // Create blur H&V post-processes
  59887. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  59888. var _this = this;
  59889. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  59890. var engine = scene.getEngine();
  59891. 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);
  59892. 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);
  59893. blurX.onActivateObservable.add(function () {
  59894. var dw = blurX.width / engine.getRenderWidth();
  59895. blurX.kernel = _this[blurWidthKey] * dw;
  59896. });
  59897. blurY.onActivateObservable.add(function () {
  59898. var dw = blurY.height / engine.getRenderHeight();
  59899. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  59900. });
  59901. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  59902. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  59903. this.blurHPostProcesses.push(blurX);
  59904. this.blurVPostProcesses.push(blurY);
  59905. };
  59906. // Create texture adder post-process
  59907. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  59908. var _this = this;
  59909. 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);
  59910. this.textureAdderPostProcess.onApply = function (effect) {
  59911. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  59912. effect.setTexture("lensSampler", _this.lensTexture);
  59913. effect.setFloat("exposure", _this.exposure);
  59914. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  59915. };
  59916. // Add to pipeline
  59917. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  59918. };
  59919. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  59920. var _this = this;
  59921. var geometryRenderer = scene.enableGeometryBufferRenderer();
  59922. geometryRenderer.enablePosition = true;
  59923. var geometry = geometryRenderer.getGBuffer();
  59924. // Base post-process
  59925. 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));
  59926. var depthValues = BABYLON.Vector2.Zero();
  59927. this.volumetricLightPostProcess.onApply = function (effect) {
  59928. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  59929. var generator = _this.sourceLight.getShadowGenerator();
  59930. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  59931. effect.setTexture("positionSampler", geometry.textures[2]);
  59932. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  59933. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  59934. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  59935. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  59936. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  59937. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  59938. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  59939. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  59940. effect.setVector2("depthValues", depthValues);
  59941. }
  59942. };
  59943. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  59944. // Smooth
  59945. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  59946. // Merge
  59947. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  59948. this.volumetricLightMergePostProces.onApply = function (effect) {
  59949. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  59950. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  59951. };
  59952. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  59953. };
  59954. // Create luminance
  59955. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  59956. var _this = this;
  59957. // Create luminance
  59958. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  59959. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  59960. var offsets = [];
  59961. this.luminancePostProcess.onApply = function (effect) {
  59962. var sU = (1.0 / _this.luminancePostProcess.width);
  59963. var sV = (1.0 / _this.luminancePostProcess.height);
  59964. offsets[0] = -0.5 * sU;
  59965. offsets[1] = 0.5 * sV;
  59966. offsets[2] = 0.5 * sU;
  59967. offsets[3] = 0.5 * sV;
  59968. offsets[4] = -0.5 * sU;
  59969. offsets[5] = -0.5 * sV;
  59970. offsets[6] = 0.5 * sU;
  59971. offsets[7] = -0.5 * sV;
  59972. effect.setArray2("lumOffsets", offsets);
  59973. };
  59974. // Add to pipeline
  59975. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  59976. // Create down sample luminance
  59977. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  59978. var size = Math.pow(3, i);
  59979. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  59980. if (i === 0) {
  59981. defines += "#define FINAL_DOWN_SAMPLER";
  59982. }
  59983. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  59984. this.luminanceDownSamplePostProcesses.push(postProcess);
  59985. }
  59986. // Create callbacks and add effects
  59987. var lastLuminance = this.luminancePostProcess;
  59988. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  59989. var downSampleOffsets = new Array(18);
  59990. pp.onApply = function (effect) {
  59991. if (!lastLuminance) {
  59992. return;
  59993. }
  59994. var id = 0;
  59995. for (var x = -1; x < 2; x++) {
  59996. for (var y = -1; y < 2; y++) {
  59997. downSampleOffsets[id] = x / lastLuminance.width;
  59998. downSampleOffsets[id + 1] = y / lastLuminance.height;
  59999. id += 2;
  60000. }
  60001. }
  60002. effect.setArray2("dsOffsets", downSampleOffsets);
  60003. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  60004. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  60005. lastLuminance = _this.luminancePostProcess;
  60006. }
  60007. else {
  60008. lastLuminance = pp;
  60009. }
  60010. };
  60011. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  60012. pp.onAfterRender = function (effect) {
  60013. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  60014. 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);
  60015. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  60016. };
  60017. }
  60018. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  60019. });
  60020. };
  60021. // Create HDR post-process
  60022. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  60023. var _this = this;
  60024. 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);
  60025. var outputLiminance = 1;
  60026. var time = 0;
  60027. var lastTime = 0;
  60028. this.hdrPostProcess.onApply = function (effect) {
  60029. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  60030. time += scene.getEngine().getDeltaTime();
  60031. if (outputLiminance < 0) {
  60032. outputLiminance = _this._hdrCurrentLuminance;
  60033. }
  60034. else {
  60035. var dt = (lastTime - time) / 1000.0;
  60036. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  60037. outputLiminance += _this.hdrDecreaseRate * dt;
  60038. }
  60039. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  60040. outputLiminance -= _this.hdrIncreaseRate * dt;
  60041. }
  60042. else {
  60043. outputLiminance = _this._hdrCurrentLuminance;
  60044. }
  60045. }
  60046. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  60047. effect.setFloat("averageLuminance", outputLiminance);
  60048. lastTime = time;
  60049. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  60050. };
  60051. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  60052. };
  60053. // Create lens flare post-process
  60054. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  60055. var _this = this;
  60056. 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);
  60057. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  60058. this._createBlurPostProcesses(scene, ratio / 4, 2);
  60059. 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);
  60060. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  60061. var resolution = new BABYLON.Vector2(0, 0);
  60062. // Lens flare
  60063. this.lensFlarePostProcess.onApply = function (effect) {
  60064. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  60065. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  60066. effect.setFloat("strength", _this.lensFlareStrength);
  60067. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  60068. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  60069. // Shift
  60070. resolution.x = _this.lensFlarePostProcess.width;
  60071. resolution.y = _this.lensFlarePostProcess.height;
  60072. effect.setVector2("resolution", resolution);
  60073. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  60074. };
  60075. // Compose
  60076. 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);
  60077. 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);
  60078. this.lensFlareComposePostProcess.onApply = function (effect) {
  60079. if (!_this._scene.activeCamera) {
  60080. return;
  60081. }
  60082. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  60083. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  60084. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  60085. // Lens start rotation matrix
  60086. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  60087. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  60088. 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));
  60089. camRot *= 4.0;
  60090. 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);
  60091. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  60092. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  60093. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  60094. };
  60095. };
  60096. // Create depth-of-field post-process
  60097. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  60098. var _this = this;
  60099. 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);
  60100. this.depthOfFieldPostProcess.onApply = function (effect) {
  60101. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  60102. effect.setTexture("depthSampler", _this._getDepthTexture());
  60103. effect.setFloat("distance", _this.depthOfFieldDistance);
  60104. };
  60105. // Add to pipeline
  60106. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  60107. };
  60108. // Create motion blur post-process
  60109. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  60110. var _this = this;
  60111. 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);
  60112. var motionScale = 0;
  60113. var prevViewProjection = BABYLON.Matrix.Identity();
  60114. var invViewProjection = BABYLON.Matrix.Identity();
  60115. var viewProjection = BABYLON.Matrix.Identity();
  60116. var screenSize = BABYLON.Vector2.Zero();
  60117. this.motionBlurPostProcess.onApply = function (effect) {
  60118. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  60119. viewProjection.invertToRef(invViewProjection);
  60120. effect.setMatrix("inverseViewProjection", invViewProjection);
  60121. effect.setMatrix("prevViewProjection", prevViewProjection);
  60122. prevViewProjection = viewProjection;
  60123. screenSize.x = _this.motionBlurPostProcess.width;
  60124. screenSize.y = _this.motionBlurPostProcess.height;
  60125. effect.setVector2("screenSize", screenSize);
  60126. motionScale = scene.getEngine().getFps() / 60.0;
  60127. effect.setFloat("motionScale", motionScale);
  60128. effect.setFloat("motionStrength", _this.motionStrength);
  60129. effect.setTexture("depthSampler", _this._getDepthTexture());
  60130. };
  60131. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  60132. };
  60133. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  60134. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  60135. var renderer = this._scene.enableGeometryBufferRenderer();
  60136. return renderer.getGBuffer().textures[0];
  60137. }
  60138. return this._scene.enableDepthRenderer().getDepthMap();
  60139. };
  60140. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  60141. for (var i = 0; i < this._cameras.length; i++) {
  60142. var camera = this._cameras[i];
  60143. if (this.originalPostProcess) {
  60144. this.originalPostProcess.dispose(camera);
  60145. }
  60146. if (this.downSampleX4PostProcess) {
  60147. this.downSampleX4PostProcess.dispose(camera);
  60148. }
  60149. if (this.brightPassPostProcess) {
  60150. this.brightPassPostProcess.dispose(camera);
  60151. }
  60152. if (this.textureAdderPostProcess) {
  60153. this.textureAdderPostProcess.dispose(camera);
  60154. }
  60155. if (this.textureAdderFinalPostProcess) {
  60156. this.textureAdderFinalPostProcess.dispose(camera);
  60157. }
  60158. if (this.volumetricLightPostProcess) {
  60159. this.volumetricLightPostProcess.dispose(camera);
  60160. }
  60161. if (this.volumetricLightSmoothXPostProcess) {
  60162. this.volumetricLightSmoothXPostProcess.dispose(camera);
  60163. }
  60164. if (this.volumetricLightSmoothYPostProcess) {
  60165. this.volumetricLightSmoothYPostProcess.dispose(camera);
  60166. }
  60167. if (this.volumetricLightMergePostProces) {
  60168. this.volumetricLightMergePostProces.dispose(camera);
  60169. }
  60170. if (this.volumetricLightFinalPostProcess) {
  60171. this.volumetricLightFinalPostProcess.dispose(camera);
  60172. }
  60173. if (this.lensFlarePostProcess) {
  60174. this.lensFlarePostProcess.dispose(camera);
  60175. }
  60176. if (this.lensFlareComposePostProcess) {
  60177. this.lensFlareComposePostProcess.dispose(camera);
  60178. }
  60179. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  60180. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  60181. }
  60182. if (this.luminancePostProcess) {
  60183. this.luminancePostProcess.dispose(camera);
  60184. }
  60185. if (this.hdrPostProcess) {
  60186. this.hdrPostProcess.dispose(camera);
  60187. }
  60188. if (this.hdrFinalPostProcess) {
  60189. this.hdrFinalPostProcess.dispose(camera);
  60190. }
  60191. if (this.depthOfFieldPostProcess) {
  60192. this.depthOfFieldPostProcess.dispose(camera);
  60193. }
  60194. if (this.motionBlurPostProcess) {
  60195. this.motionBlurPostProcess.dispose(camera);
  60196. }
  60197. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  60198. this.blurHPostProcesses[j].dispose(camera);
  60199. }
  60200. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  60201. this.blurVPostProcesses[j].dispose(camera);
  60202. }
  60203. }
  60204. this.originalPostProcess = null;
  60205. this.downSampleX4PostProcess = null;
  60206. this.brightPassPostProcess = null;
  60207. this.textureAdderPostProcess = null;
  60208. this.textureAdderFinalPostProcess = null;
  60209. this.volumetricLightPostProcess = null;
  60210. this.volumetricLightSmoothXPostProcess = null;
  60211. this.volumetricLightSmoothYPostProcess = null;
  60212. this.volumetricLightMergePostProces = null;
  60213. this.volumetricLightFinalPostProcess = null;
  60214. this.lensFlarePostProcess = null;
  60215. this.lensFlareComposePostProcess = null;
  60216. this.luminancePostProcess = null;
  60217. this.hdrPostProcess = null;
  60218. this.hdrFinalPostProcess = null;
  60219. this.depthOfFieldPostProcess = null;
  60220. this.motionBlurPostProcess = null;
  60221. this.luminanceDownSamplePostProcesses = [];
  60222. this.blurHPostProcesses = [];
  60223. this.blurVPostProcesses = [];
  60224. };
  60225. // Dispose
  60226. StandardRenderingPipeline.prototype.dispose = function () {
  60227. this._disposePostProcesses();
  60228. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  60229. _super.prototype.dispose.call(this);
  60230. };
  60231. // Serialize rendering pipeline
  60232. StandardRenderingPipeline.prototype.serialize = function () {
  60233. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  60234. serializationObject.customType = "StandardRenderingPipeline";
  60235. return serializationObject;
  60236. };
  60237. /**
  60238. * Static members
  60239. */
  60240. // Parse serialized pipeline
  60241. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  60242. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  60243. };
  60244. // Luminance steps
  60245. StandardRenderingPipeline.LuminanceSteps = 6;
  60246. __decorate([
  60247. BABYLON.serialize()
  60248. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  60249. __decorate([
  60250. BABYLON.serialize()
  60251. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  60252. __decorate([
  60253. BABYLON.serialize()
  60254. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  60255. __decorate([
  60256. BABYLON.serialize()
  60257. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  60258. __decorate([
  60259. BABYLON.serializeAsTexture("lensTexture")
  60260. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  60261. __decorate([
  60262. BABYLON.serialize()
  60263. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  60264. __decorate([
  60265. BABYLON.serialize()
  60266. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  60267. __decorate([
  60268. BABYLON.serialize()
  60269. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  60270. __decorate([
  60271. BABYLON.serialize()
  60272. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  60273. __decorate([
  60274. BABYLON.serialize()
  60275. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  60276. __decorate([
  60277. BABYLON.serialize()
  60278. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  60279. __decorate([
  60280. BABYLON.serializeAsTexture("lensColorTexture")
  60281. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  60282. __decorate([
  60283. BABYLON.serialize()
  60284. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  60285. __decorate([
  60286. BABYLON.serialize()
  60287. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  60288. __decorate([
  60289. BABYLON.serialize()
  60290. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  60291. __decorate([
  60292. BABYLON.serialize()
  60293. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  60294. __decorate([
  60295. BABYLON.serializeAsTexture("lensStarTexture")
  60296. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  60297. __decorate([
  60298. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  60299. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  60300. __decorate([
  60301. BABYLON.serialize()
  60302. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  60303. __decorate([
  60304. BABYLON.serialize()
  60305. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  60306. __decorate([
  60307. BABYLON.serialize()
  60308. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  60309. __decorate([
  60310. BABYLON.serialize()
  60311. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  60312. __decorate([
  60313. BABYLON.serialize()
  60314. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  60315. __decorate([
  60316. BABYLON.serialize()
  60317. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  60318. __decorate([
  60319. BABYLON.serialize()
  60320. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  60321. __decorate([
  60322. BABYLON.serialize()
  60323. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  60324. __decorate([
  60325. BABYLON.serialize()
  60326. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  60327. __decorate([
  60328. BABYLON.serialize()
  60329. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  60330. __decorate([
  60331. BABYLON.serialize()
  60332. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  60333. __decorate([
  60334. BABYLON.serialize()
  60335. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  60336. return StandardRenderingPipeline;
  60337. }(BABYLON.PostProcessRenderPipeline));
  60338. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  60339. })(BABYLON || (BABYLON = {}));
  60340. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  60341. var BABYLON;
  60342. (function (BABYLON) {
  60343. var FxaaPostProcess = /** @class */ (function (_super) {
  60344. __extends(FxaaPostProcess, _super);
  60345. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  60346. if (camera === void 0) { camera = null; }
  60347. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60348. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  60349. _this.onApplyObservable.add(function (effect) {
  60350. var texelSize = _this.texelSize;
  60351. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  60352. });
  60353. return _this;
  60354. }
  60355. return FxaaPostProcess;
  60356. }(BABYLON.PostProcess));
  60357. BABYLON.FxaaPostProcess = FxaaPostProcess;
  60358. })(BABYLON || (BABYLON = {}));
  60359. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  60360. var BABYLON;
  60361. (function (BABYLON) {
  60362. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  60363. __extends(DefaultRenderingPipeline, _super);
  60364. /**
  60365. * @constructor
  60366. * @param {string} name - The rendering pipeline name
  60367. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  60368. * @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)
  60369. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  60370. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  60371. */
  60372. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  60373. if (automaticBuild === void 0) { automaticBuild = true; }
  60374. var _this = _super.call(this, scene.getEngine(), name) || this;
  60375. _this.PassPostProcessId = "PassPostProcessEffect";
  60376. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  60377. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  60378. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  60379. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  60380. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  60381. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  60382. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  60383. // IAnimatable
  60384. _this.animations = [];
  60385. // Values
  60386. _this._bloomEnabled = false;
  60387. _this._fxaaEnabled = false;
  60388. _this._imageProcessingEnabled = true;
  60389. _this._bloomScale = 0.6;
  60390. _this._buildAllowed = true;
  60391. /**
  60392. * Specifies the size of the bloom blur kernel, relative to the final output size
  60393. */
  60394. _this.bloomKernel = 64;
  60395. /**
  60396. * Specifies the weight of the bloom in the final rendering
  60397. */
  60398. _this._bloomWeight = 0.15;
  60399. _this._cameras = cameras || [];
  60400. _this._buildAllowed = automaticBuild;
  60401. // Initialize
  60402. _this._scene = scene;
  60403. var caps = _this._scene.getEngine().getCaps();
  60404. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  60405. // Misc
  60406. if (_this._hdr) {
  60407. if (caps.textureHalfFloatRender) {
  60408. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60409. }
  60410. else if (caps.textureFloatRender) {
  60411. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60412. }
  60413. }
  60414. else {
  60415. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60416. }
  60417. // Attach
  60418. scene.postProcessRenderPipelineManager.addPipeline(_this);
  60419. _this._buildPipeline();
  60420. return _this;
  60421. }
  60422. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  60423. get: function () {
  60424. return this._bloomWeight;
  60425. },
  60426. set: function (value) {
  60427. if (this._bloomWeight === value) {
  60428. return;
  60429. }
  60430. this._bloomWeight = value;
  60431. if (this._hdr && this.copyBack) {
  60432. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  60433. }
  60434. },
  60435. enumerable: true,
  60436. configurable: true
  60437. });
  60438. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  60439. get: function () {
  60440. return this._bloomScale;
  60441. },
  60442. set: function (value) {
  60443. if (this._bloomScale === value) {
  60444. return;
  60445. }
  60446. this._bloomScale = value;
  60447. this._buildPipeline();
  60448. },
  60449. enumerable: true,
  60450. configurable: true
  60451. });
  60452. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  60453. get: function () {
  60454. return this._bloomEnabled;
  60455. },
  60456. set: function (enabled) {
  60457. if (this._bloomEnabled === enabled) {
  60458. return;
  60459. }
  60460. this._bloomEnabled = enabled;
  60461. this._buildPipeline();
  60462. },
  60463. enumerable: true,
  60464. configurable: true
  60465. });
  60466. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  60467. get: function () {
  60468. return this._fxaaEnabled;
  60469. },
  60470. set: function (enabled) {
  60471. if (this._fxaaEnabled === enabled) {
  60472. return;
  60473. }
  60474. this._fxaaEnabled = enabled;
  60475. this._buildPipeline();
  60476. },
  60477. enumerable: true,
  60478. configurable: true
  60479. });
  60480. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  60481. get: function () {
  60482. return this._imageProcessingEnabled;
  60483. },
  60484. set: function (enabled) {
  60485. if (this._imageProcessingEnabled === enabled) {
  60486. return;
  60487. }
  60488. this._imageProcessingEnabled = enabled;
  60489. this._buildPipeline();
  60490. },
  60491. enumerable: true,
  60492. configurable: true
  60493. });
  60494. /**
  60495. * Force the compilation of the entire pipeline.
  60496. */
  60497. DefaultRenderingPipeline.prototype.prepare = function () {
  60498. var previousState = this._buildAllowed;
  60499. this._buildAllowed = true;
  60500. this._buildPipeline();
  60501. this._buildAllowed = previousState;
  60502. };
  60503. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  60504. var _this = this;
  60505. if (!this._buildAllowed) {
  60506. return;
  60507. }
  60508. var engine = this._scene.getEngine();
  60509. this._disposePostProcesses();
  60510. this._reset();
  60511. if (this.bloomEnabled) {
  60512. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  60513. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  60514. if (!this._hdr) {
  60515. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  60516. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  60517. this.highlights.autoClear = false;
  60518. this.highlights.alwaysForcePOT = true;
  60519. }
  60520. 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);
  60521. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  60522. this.blurX.alwaysForcePOT = true;
  60523. this.blurX.autoClear = false;
  60524. this.blurX.onActivateObservable.add(function () {
  60525. var dw = _this.blurX.width / engine.getRenderWidth(true);
  60526. _this.blurX.kernel = _this.bloomKernel * dw;
  60527. });
  60528. 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);
  60529. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  60530. this.blurY.alwaysForcePOT = true;
  60531. this.blurY.autoClear = false;
  60532. this.blurY.onActivateObservable.add(function () {
  60533. var dh = _this.blurY.height / engine.getRenderHeight(true);
  60534. _this.blurY.kernel = _this.bloomKernel * dh;
  60535. });
  60536. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  60537. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  60538. this.copyBack.alwaysForcePOT = true;
  60539. if (this._hdr) {
  60540. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  60541. var w = this.bloomWeight;
  60542. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  60543. }
  60544. else {
  60545. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  60546. }
  60547. this.copyBack.autoClear = false;
  60548. }
  60549. if (this._imageProcessingEnabled) {
  60550. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  60551. if (this._hdr) {
  60552. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  60553. }
  60554. else {
  60555. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  60556. }
  60557. }
  60558. if (this.fxaaEnabled) {
  60559. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  60560. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  60561. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  60562. }
  60563. else if (this._hdr && this.imageProcessing) {
  60564. this.finalMerge = this.imageProcessing;
  60565. }
  60566. else {
  60567. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  60568. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  60569. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  60570. }
  60571. if (this.bloomEnabled) {
  60572. if (this._hdr) {
  60573. this.copyBack.shareOutputWith(this.blurX);
  60574. if (this.imageProcessing) {
  60575. this.imageProcessing.shareOutputWith(this.pass);
  60576. this.imageProcessing.autoClear = false;
  60577. }
  60578. else if (this.fxaa) {
  60579. this.fxaa.shareOutputWith(this.pass);
  60580. }
  60581. else {
  60582. this.finalMerge.shareOutputWith(this.pass);
  60583. }
  60584. }
  60585. else {
  60586. if (this.fxaa) {
  60587. this.fxaa.shareOutputWith(this.pass);
  60588. }
  60589. else {
  60590. this.finalMerge.shareOutputWith(this.pass);
  60591. }
  60592. }
  60593. }
  60594. if (this._cameras !== null) {
  60595. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  60596. }
  60597. };
  60598. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  60599. for (var i = 0; i < this._cameras.length; i++) {
  60600. var camera = this._cameras[i];
  60601. if (this.pass) {
  60602. this.pass.dispose(camera);
  60603. }
  60604. if (this.highlights) {
  60605. this.highlights.dispose(camera);
  60606. }
  60607. if (this.blurX) {
  60608. this.blurX.dispose(camera);
  60609. }
  60610. if (this.blurY) {
  60611. this.blurY.dispose(camera);
  60612. }
  60613. if (this.copyBack) {
  60614. this.copyBack.dispose(camera);
  60615. }
  60616. if (this.imageProcessing) {
  60617. this.imageProcessing.dispose(camera);
  60618. }
  60619. if (this.fxaa) {
  60620. this.fxaa.dispose(camera);
  60621. }
  60622. if (this.finalMerge) {
  60623. this.finalMerge.dispose(camera);
  60624. }
  60625. }
  60626. this.pass = null;
  60627. this.highlights = null;
  60628. this.blurX = null;
  60629. this.blurY = null;
  60630. this.copyBack = null;
  60631. this.imageProcessing = null;
  60632. this.fxaa = null;
  60633. this.finalMerge = null;
  60634. };
  60635. // Dispose
  60636. DefaultRenderingPipeline.prototype.dispose = function () {
  60637. this._disposePostProcesses();
  60638. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  60639. _super.prototype.dispose.call(this);
  60640. };
  60641. // Serialize rendering pipeline
  60642. DefaultRenderingPipeline.prototype.serialize = function () {
  60643. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  60644. serializationObject.customType = "DefaultRenderingPipeline";
  60645. return serializationObject;
  60646. };
  60647. // Parse serialized pipeline
  60648. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  60649. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  60650. };
  60651. __decorate([
  60652. BABYLON.serialize()
  60653. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  60654. __decorate([
  60655. BABYLON.serialize()
  60656. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  60657. __decorate([
  60658. BABYLON.serialize()
  60659. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  60660. __decorate([
  60661. BABYLON.serialize()
  60662. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  60663. __decorate([
  60664. BABYLON.serialize()
  60665. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  60666. __decorate([
  60667. BABYLON.serialize()
  60668. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  60669. __decorate([
  60670. BABYLON.serialize()
  60671. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  60672. __decorate([
  60673. BABYLON.serialize()
  60674. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  60675. return DefaultRenderingPipeline;
  60676. }(BABYLON.PostProcessRenderPipeline));
  60677. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  60678. })(BABYLON || (BABYLON = {}));
  60679. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  60680. var BABYLON;
  60681. (function (BABYLON) {
  60682. var GeometryBufferRenderer = /** @class */ (function () {
  60683. function GeometryBufferRenderer(scene, ratio) {
  60684. if (ratio === void 0) { ratio = 1; }
  60685. this._enablePosition = false;
  60686. this._scene = scene;
  60687. this._ratio = ratio;
  60688. // Render target
  60689. this._createRenderTargets();
  60690. }
  60691. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  60692. set: function (meshes) {
  60693. this._multiRenderTarget.renderList = meshes;
  60694. },
  60695. enumerable: true,
  60696. configurable: true
  60697. });
  60698. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  60699. get: function () {
  60700. return this._multiRenderTarget.isSupported;
  60701. },
  60702. enumerable: true,
  60703. configurable: true
  60704. });
  60705. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  60706. get: function () {
  60707. return this._enablePosition;
  60708. },
  60709. set: function (enable) {
  60710. this._enablePosition = enable;
  60711. this.dispose();
  60712. this._createRenderTargets();
  60713. },
  60714. enumerable: true,
  60715. configurable: true
  60716. });
  60717. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  60718. var material = subMesh.getMaterial();
  60719. if (material && material.disableDepthWrite) {
  60720. return false;
  60721. }
  60722. var defines = [];
  60723. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  60724. var mesh = subMesh.getMesh();
  60725. // Alpha test
  60726. if (material && material.needAlphaTesting()) {
  60727. defines.push("#define ALPHATEST");
  60728. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60729. attribs.push(BABYLON.VertexBuffer.UVKind);
  60730. defines.push("#define UV1");
  60731. }
  60732. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60733. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60734. defines.push("#define UV2");
  60735. }
  60736. }
  60737. // Buffers
  60738. if (this._enablePosition) {
  60739. defines.push("#define POSITION");
  60740. }
  60741. // Bones
  60742. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60743. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60744. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60745. if (mesh.numBoneInfluencers > 4) {
  60746. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60747. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60748. }
  60749. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60750. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  60751. }
  60752. else {
  60753. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60754. }
  60755. // Instances
  60756. if (useInstances) {
  60757. defines.push("#define INSTANCES");
  60758. attribs.push("world0");
  60759. attribs.push("world1");
  60760. attribs.push("world2");
  60761. attribs.push("world3");
  60762. }
  60763. // Get correct effect
  60764. var join = defines.join("\n");
  60765. if (this._cachedDefines !== join) {
  60766. this._cachedDefines = join;
  60767. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  60768. }
  60769. return this._effect.isReady();
  60770. };
  60771. GeometryBufferRenderer.prototype.getGBuffer = function () {
  60772. return this._multiRenderTarget;
  60773. };
  60774. // Methods
  60775. GeometryBufferRenderer.prototype.dispose = function () {
  60776. this.getGBuffer().dispose();
  60777. };
  60778. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  60779. var _this = this;
  60780. var engine = this._scene.getEngine();
  60781. var count = this._enablePosition ? 3 : 2;
  60782. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  60783. if (!this.isSupported) {
  60784. return;
  60785. }
  60786. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60787. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60788. this._multiRenderTarget.refreshRate = 1;
  60789. this._multiRenderTarget.renderParticles = false;
  60790. this._multiRenderTarget.renderList = null;
  60791. // set default depth value to 1.0 (far away)
  60792. this._multiRenderTarget.onClearObservable.add(function (engine) {
  60793. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  60794. });
  60795. // Custom render function
  60796. var renderSubMesh = function (subMesh) {
  60797. var mesh = subMesh.getRenderingMesh();
  60798. var scene = _this._scene;
  60799. var engine = scene.getEngine();
  60800. var material = subMesh.getMaterial();
  60801. if (!material) {
  60802. return;
  60803. }
  60804. // Culling
  60805. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  60806. // Managing instances
  60807. var batch = mesh._getInstancesRenderList(subMesh._id);
  60808. if (batch.mustReturn) {
  60809. return;
  60810. }
  60811. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  60812. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  60813. engine.enableEffect(_this._effect);
  60814. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  60815. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  60816. _this._effect.setMatrix("view", scene.getViewMatrix());
  60817. // Alpha test
  60818. if (material && material.needAlphaTesting()) {
  60819. var alphaTexture = material.getAlphaTestTexture();
  60820. if (alphaTexture) {
  60821. _this._effect.setTexture("diffuseSampler", alphaTexture);
  60822. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  60823. }
  60824. }
  60825. // Bones
  60826. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  60827. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  60828. }
  60829. // Draw
  60830. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  60831. }
  60832. };
  60833. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  60834. var index;
  60835. if (depthOnlySubMeshes.length) {
  60836. engine.setColorWrite(false);
  60837. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  60838. renderSubMesh(depthOnlySubMeshes.data[index]);
  60839. }
  60840. engine.setColorWrite(true);
  60841. }
  60842. for (index = 0; index < opaqueSubMeshes.length; index++) {
  60843. renderSubMesh(opaqueSubMeshes.data[index]);
  60844. }
  60845. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  60846. renderSubMesh(alphaTestSubMeshes.data[index]);
  60847. }
  60848. };
  60849. };
  60850. return GeometryBufferRenderer;
  60851. }());
  60852. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  60853. })(BABYLON || (BABYLON = {}));
  60854. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  60855. var BABYLON;
  60856. (function (BABYLON) {
  60857. var RefractionPostProcess = /** @class */ (function (_super) {
  60858. __extends(RefractionPostProcess, _super);
  60859. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  60860. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  60861. _this.color = color;
  60862. _this.depth = depth;
  60863. _this.colorLevel = colorLevel;
  60864. _this.onActivateObservable.add(function (cam) {
  60865. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  60866. });
  60867. _this.onApplyObservable.add(function (effect) {
  60868. effect.setColor3("baseColor", _this.color);
  60869. effect.setFloat("depth", _this.depth);
  60870. effect.setFloat("colorLevel", _this.colorLevel);
  60871. effect.setTexture("refractionSampler", _this._refRexture);
  60872. });
  60873. return _this;
  60874. }
  60875. // Methods
  60876. RefractionPostProcess.prototype.dispose = function (camera) {
  60877. if (this._refRexture) {
  60878. this._refRexture.dispose();
  60879. }
  60880. _super.prototype.dispose.call(this, camera);
  60881. };
  60882. return RefractionPostProcess;
  60883. }(BABYLON.PostProcess));
  60884. BABYLON.RefractionPostProcess = RefractionPostProcess;
  60885. })(BABYLON || (BABYLON = {}));
  60886. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  60887. var BABYLON;
  60888. (function (BABYLON) {
  60889. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  60890. __extends(BlackAndWhitePostProcess, _super);
  60891. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  60892. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  60893. _this.degree = 1;
  60894. _this.onApplyObservable.add(function (effect) {
  60895. effect.setFloat("degree", _this.degree);
  60896. });
  60897. return _this;
  60898. }
  60899. return BlackAndWhitePostProcess;
  60900. }(BABYLON.PostProcess));
  60901. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  60902. })(BABYLON || (BABYLON = {}));
  60903. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  60904. var BABYLON;
  60905. (function (BABYLON) {
  60906. var ConvolutionPostProcess = /** @class */ (function (_super) {
  60907. __extends(ConvolutionPostProcess, _super);
  60908. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  60909. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  60910. _this.kernel = kernel;
  60911. _this.onApply = function (effect) {
  60912. effect.setFloat2("screenSize", _this.width, _this.height);
  60913. effect.setArray("kernel", _this.kernel);
  60914. };
  60915. return _this;
  60916. }
  60917. // Statics
  60918. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  60919. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  60920. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  60921. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  60922. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  60923. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  60924. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  60925. return ConvolutionPostProcess;
  60926. }(BABYLON.PostProcess));
  60927. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  60928. })(BABYLON || (BABYLON = {}));
  60929. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  60930. var BABYLON;
  60931. (function (BABYLON) {
  60932. var FilterPostProcess = /** @class */ (function (_super) {
  60933. __extends(FilterPostProcess, _super);
  60934. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  60935. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  60936. _this.kernelMatrix = kernelMatrix;
  60937. _this.onApply = function (effect) {
  60938. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  60939. };
  60940. return _this;
  60941. }
  60942. return FilterPostProcess;
  60943. }(BABYLON.PostProcess));
  60944. BABYLON.FilterPostProcess = FilterPostProcess;
  60945. })(BABYLON || (BABYLON = {}));
  60946. //# sourceMappingURL=babylon.filterPostProcess.js.map
  60947. var BABYLON;
  60948. (function (BABYLON) {
  60949. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  60950. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  60951. __extends(VolumetricLightScatteringPostProcess, _super);
  60952. /**
  60953. * @constructor
  60954. * @param {string} name - The post-process name
  60955. * @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)
  60956. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  60957. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  60958. * @param {number} samples - The post-process quality, default 100
  60959. * @param {number} samplingMode - The post-process filtering mode
  60960. * @param {BABYLON.Engine} engine - The babylon engine
  60961. * @param {boolean} reusable - If the post-process is reusable
  60962. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  60963. */
  60964. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  60965. if (samples === void 0) { samples = 100; }
  60966. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  60967. 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;
  60968. _this._screenCoordinates = BABYLON.Vector2.Zero();
  60969. /**
  60970. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  60971. * @type {Vector3}
  60972. */
  60973. _this.customMeshPosition = BABYLON.Vector3.Zero();
  60974. /**
  60975. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  60976. * @type {boolean}
  60977. */
  60978. _this.useCustomMeshPosition = false;
  60979. /**
  60980. * If the post-process should inverse the light scattering direction
  60981. * @type {boolean}
  60982. */
  60983. _this.invert = true;
  60984. /**
  60985. * Array containing the excluded meshes not rendered in the internal pass
  60986. */
  60987. _this.excludedMeshes = new Array();
  60988. /**
  60989. * Controls the overall intensity of the post-process
  60990. * @type {number}
  60991. */
  60992. _this.exposure = 0.3;
  60993. /**
  60994. * Dissipates each sample's contribution in range [0, 1]
  60995. * @type {number}
  60996. */
  60997. _this.decay = 0.96815;
  60998. /**
  60999. * Controls the overall intensity of each sample
  61000. * @type {number}
  61001. */
  61002. _this.weight = 0.58767;
  61003. /**
  61004. * Controls the density of each sample
  61005. * @type {number}
  61006. */
  61007. _this.density = 0.926;
  61008. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  61009. engine = scene.getEngine();
  61010. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  61011. // Configure mesh
  61012. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  61013. // Configure
  61014. _this._createPass(scene, ratio.passRatio || ratio);
  61015. _this.onActivate = function (camera) {
  61016. if (!_this.isSupported) {
  61017. _this.dispose(camera);
  61018. }
  61019. _this.onActivate = null;
  61020. };
  61021. _this.onApplyObservable.add(function (effect) {
  61022. _this._updateMeshScreenCoordinates(scene);
  61023. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  61024. effect.setFloat("exposure", _this.exposure);
  61025. effect.setFloat("decay", _this.decay);
  61026. effect.setFloat("weight", _this.weight);
  61027. effect.setFloat("density", _this.density);
  61028. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  61029. });
  61030. return _this;
  61031. }
  61032. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  61033. get: function () {
  61034. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  61035. return false;
  61036. },
  61037. set: function (useDiffuseColor) {
  61038. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  61039. },
  61040. enumerable: true,
  61041. configurable: true
  61042. });
  61043. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  61044. return "VolumetricLightScatteringPostProcess";
  61045. };
  61046. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  61047. var mesh = subMesh.getMesh();
  61048. // Render this.mesh as default
  61049. if (mesh === this.mesh && mesh.material) {
  61050. return mesh.material.isReady(mesh);
  61051. }
  61052. var defines = [];
  61053. var attribs = [BABYLON.VertexBuffer.PositionKind];
  61054. var material = subMesh.getMaterial();
  61055. // Alpha test
  61056. if (material) {
  61057. if (material.needAlphaTesting()) {
  61058. defines.push("#define ALPHATEST");
  61059. }
  61060. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61061. attribs.push(BABYLON.VertexBuffer.UVKind);
  61062. defines.push("#define UV1");
  61063. }
  61064. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  61065. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  61066. defines.push("#define UV2");
  61067. }
  61068. }
  61069. // Bones
  61070. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61071. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61072. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61073. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61074. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  61075. }
  61076. else {
  61077. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61078. }
  61079. // Instances
  61080. if (useInstances) {
  61081. defines.push("#define INSTANCES");
  61082. attribs.push("world0");
  61083. attribs.push("world1");
  61084. attribs.push("world2");
  61085. attribs.push("world3");
  61086. }
  61087. // Get correct effect
  61088. var join = defines.join("\n");
  61089. if (this._cachedDefines !== join) {
  61090. this._cachedDefines = join;
  61091. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  61092. }
  61093. return this._volumetricLightScatteringPass.isReady();
  61094. };
  61095. /**
  61096. * Sets the new light position for light scattering effect
  61097. * @param {BABYLON.Vector3} The new custom light position
  61098. */
  61099. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  61100. this.customMeshPosition = position;
  61101. };
  61102. /**
  61103. * Returns the light position for light scattering effect
  61104. * @return {BABYLON.Vector3} The custom light position
  61105. */
  61106. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  61107. return this.customMeshPosition;
  61108. };
  61109. /**
  61110. * Disposes the internal assets and detaches the post-process from the camera
  61111. */
  61112. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  61113. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  61114. if (rttIndex !== -1) {
  61115. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  61116. }
  61117. this._volumetricLightScatteringRTT.dispose();
  61118. _super.prototype.dispose.call(this, camera);
  61119. };
  61120. /**
  61121. * Returns the render target texture used by the post-process
  61122. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  61123. */
  61124. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  61125. return this._volumetricLightScatteringRTT;
  61126. };
  61127. // Private methods
  61128. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  61129. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  61130. return true;
  61131. }
  61132. return false;
  61133. };
  61134. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  61135. var _this = this;
  61136. var engine = scene.getEngine();
  61137. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  61138. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61139. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61140. this._volumetricLightScatteringRTT.renderList = null;
  61141. this._volumetricLightScatteringRTT.renderParticles = false;
  61142. var camera = this.getCamera();
  61143. if (camera) {
  61144. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  61145. }
  61146. else {
  61147. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  61148. }
  61149. // Custom render function for submeshes
  61150. var renderSubMesh = function (subMesh) {
  61151. var mesh = subMesh.getRenderingMesh();
  61152. if (_this._meshExcluded(mesh)) {
  61153. return;
  61154. }
  61155. var material = subMesh.getMaterial();
  61156. if (!material) {
  61157. return;
  61158. }
  61159. var scene = mesh.getScene();
  61160. var engine = scene.getEngine();
  61161. // Culling
  61162. engine.setState(material.backFaceCulling);
  61163. // Managing instances
  61164. var batch = mesh._getInstancesRenderList(subMesh._id);
  61165. if (batch.mustReturn) {
  61166. return;
  61167. }
  61168. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  61169. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  61170. var effect = _this._volumetricLightScatteringPass;
  61171. if (mesh === _this.mesh) {
  61172. if (subMesh.effect) {
  61173. effect = subMesh.effect;
  61174. }
  61175. else {
  61176. effect = material.getEffect();
  61177. }
  61178. }
  61179. engine.enableEffect(effect);
  61180. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  61181. if (mesh === _this.mesh) {
  61182. material.bind(mesh.getWorldMatrix(), mesh);
  61183. }
  61184. else {
  61185. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  61186. // Alpha test
  61187. if (material && material.needAlphaTesting()) {
  61188. var alphaTexture = material.getAlphaTestTexture();
  61189. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  61190. if (alphaTexture) {
  61191. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  61192. }
  61193. }
  61194. // Bones
  61195. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  61196. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  61197. }
  61198. }
  61199. // Draw
  61200. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  61201. }
  61202. };
  61203. // Render target texture callbacks
  61204. var savedSceneClearColor;
  61205. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  61206. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  61207. savedSceneClearColor = scene.clearColor;
  61208. scene.clearColor = sceneClearColor;
  61209. });
  61210. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  61211. scene.clearColor = savedSceneClearColor;
  61212. });
  61213. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  61214. var engine = scene.getEngine();
  61215. var index;
  61216. if (depthOnlySubMeshes.length) {
  61217. engine.setColorWrite(false);
  61218. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  61219. renderSubMesh(depthOnlySubMeshes.data[index]);
  61220. }
  61221. engine.setColorWrite(true);
  61222. }
  61223. for (index = 0; index < opaqueSubMeshes.length; index++) {
  61224. renderSubMesh(opaqueSubMeshes.data[index]);
  61225. }
  61226. engine.setAlphaTesting(true);
  61227. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  61228. renderSubMesh(alphaTestSubMeshes.data[index]);
  61229. }
  61230. engine.setAlphaTesting(false);
  61231. if (transparentSubMeshes.length) {
  61232. // Sort sub meshes
  61233. for (index = 0; index < transparentSubMeshes.length; index++) {
  61234. var submesh = transparentSubMeshes.data[index];
  61235. var boundingInfo = submesh.getBoundingInfo();
  61236. if (boundingInfo && scene.activeCamera) {
  61237. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  61238. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  61239. }
  61240. }
  61241. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  61242. sortedArray.sort(function (a, b) {
  61243. // Alpha index first
  61244. if (a._alphaIndex > b._alphaIndex) {
  61245. return 1;
  61246. }
  61247. if (a._alphaIndex < b._alphaIndex) {
  61248. return -1;
  61249. }
  61250. // Then distance to camera
  61251. if (a._distanceToCamera < b._distanceToCamera) {
  61252. return 1;
  61253. }
  61254. if (a._distanceToCamera > b._distanceToCamera) {
  61255. return -1;
  61256. }
  61257. return 0;
  61258. });
  61259. // Render sub meshes
  61260. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  61261. for (index = 0; index < sortedArray.length; index++) {
  61262. renderSubMesh(sortedArray[index]);
  61263. }
  61264. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  61265. }
  61266. };
  61267. };
  61268. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  61269. var transform = scene.getTransformMatrix();
  61270. var meshPosition;
  61271. if (this.useCustomMeshPosition) {
  61272. meshPosition = this.customMeshPosition;
  61273. }
  61274. else if (this.attachedNode) {
  61275. meshPosition = this.attachedNode.position;
  61276. }
  61277. else {
  61278. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  61279. }
  61280. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  61281. this._screenCoordinates.x = pos.x / this._viewPort.width;
  61282. this._screenCoordinates.y = pos.y / this._viewPort.height;
  61283. if (this.invert)
  61284. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  61285. };
  61286. // Static methods
  61287. /**
  61288. * Creates a default mesh for the Volumeric Light Scattering post-process
  61289. * @param {string} The mesh name
  61290. * @param {BABYLON.Scene} The scene where to create the mesh
  61291. * @return {BABYLON.Mesh} the default mesh
  61292. */
  61293. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  61294. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  61295. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  61296. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  61297. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  61298. mesh.material = material;
  61299. return mesh;
  61300. };
  61301. __decorate([
  61302. BABYLON.serializeAsVector3()
  61303. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  61304. __decorate([
  61305. BABYLON.serialize()
  61306. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  61307. __decorate([
  61308. BABYLON.serialize()
  61309. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  61310. __decorate([
  61311. BABYLON.serializeAsMeshReference()
  61312. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  61313. __decorate([
  61314. BABYLON.serialize()
  61315. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  61316. __decorate([
  61317. BABYLON.serialize()
  61318. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  61319. __decorate([
  61320. BABYLON.serialize()
  61321. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  61322. __decorate([
  61323. BABYLON.serialize()
  61324. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  61325. __decorate([
  61326. BABYLON.serialize()
  61327. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  61328. return VolumetricLightScatteringPostProcess;
  61329. }(BABYLON.PostProcess));
  61330. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  61331. })(BABYLON || (BABYLON = {}));
  61332. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  61333. //
  61334. // This post-process allows the modification of rendered colors by using
  61335. // a 'look-up table' (LUT). This effect is also called Color Grading.
  61336. //
  61337. // The object needs to be provided an url to a texture containing the color
  61338. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  61339. // Use an image editing software to tweak the LUT to match your needs.
  61340. //
  61341. // For an example of a color LUT, see here:
  61342. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  61343. // For explanations on color grading, see here:
  61344. // http://udn.epicgames.com/Three/ColorGrading.html
  61345. //
  61346. var BABYLON;
  61347. (function (BABYLON) {
  61348. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  61349. __extends(ColorCorrectionPostProcess, _super);
  61350. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  61351. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  61352. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  61353. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  61354. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61355. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61356. _this.onApply = function (effect) {
  61357. effect.setTexture("colorTable", _this._colorTableTexture);
  61358. };
  61359. return _this;
  61360. }
  61361. return ColorCorrectionPostProcess;
  61362. }(BABYLON.PostProcess));
  61363. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  61364. })(BABYLON || (BABYLON = {}));
  61365. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  61366. var BABYLON;
  61367. (function (BABYLON) {
  61368. var TonemappingOperator;
  61369. (function (TonemappingOperator) {
  61370. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  61371. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  61372. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  61373. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  61374. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  61375. ;
  61376. var TonemapPostProcess = /** @class */ (function (_super) {
  61377. __extends(TonemapPostProcess, _super);
  61378. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  61379. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  61380. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61381. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  61382. _this._operator = _operator;
  61383. _this.exposureAdjustment = exposureAdjustment;
  61384. var defines = "#define ";
  61385. if (_this._operator === TonemappingOperator.Hable)
  61386. defines += "HABLE_TONEMAPPING";
  61387. else if (_this._operator === TonemappingOperator.Reinhard)
  61388. defines += "REINHARD_TONEMAPPING";
  61389. else if (_this._operator === TonemappingOperator.HejiDawson)
  61390. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  61391. else if (_this._operator === TonemappingOperator.Photographic)
  61392. defines += "PHOTOGRAPHIC_TONEMAPPING";
  61393. //sadly a second call to create the effect.
  61394. _this.updateEffect(defines);
  61395. _this.onApply = function (effect) {
  61396. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  61397. };
  61398. return _this;
  61399. }
  61400. return TonemapPostProcess;
  61401. }(BABYLON.PostProcess));
  61402. BABYLON.TonemapPostProcess = TonemapPostProcess;
  61403. })(BABYLON || (BABYLON = {}));
  61404. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  61405. var BABYLON;
  61406. (function (BABYLON) {
  61407. var DisplayPassPostProcess = /** @class */ (function (_super) {
  61408. __extends(DisplayPassPostProcess, _super);
  61409. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  61410. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  61411. }
  61412. return DisplayPassPostProcess;
  61413. }(BABYLON.PostProcess));
  61414. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  61415. })(BABYLON || (BABYLON = {}));
  61416. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  61417. var BABYLON;
  61418. (function (BABYLON) {
  61419. var HighlightsPostProcess = /** @class */ (function (_super) {
  61420. __extends(HighlightsPostProcess, _super);
  61421. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  61422. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61423. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  61424. }
  61425. return HighlightsPostProcess;
  61426. }(BABYLON.PostProcess));
  61427. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  61428. })(BABYLON || (BABYLON = {}));
  61429. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  61430. var BABYLON;
  61431. (function (BABYLON) {
  61432. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  61433. __extends(ImageProcessingPostProcess, _super);
  61434. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  61435. if (camera === void 0) { camera = null; }
  61436. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61437. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  61438. _this._fromLinearSpace = true;
  61439. /**
  61440. * Defines cache preventing GC.
  61441. */
  61442. _this._defines = {
  61443. IMAGEPROCESSING: false,
  61444. VIGNETTE: false,
  61445. VIGNETTEBLENDMODEMULTIPLY: false,
  61446. VIGNETTEBLENDMODEOPAQUE: false,
  61447. TONEMAPPING: false,
  61448. CONTRAST: false,
  61449. COLORCURVES: false,
  61450. COLORGRADING: false,
  61451. COLORGRADING3D: false,
  61452. FROMLINEARSPACE: false,
  61453. SAMPLER3DGREENDEPTH: false,
  61454. SAMPLER3DBGRMAP: false,
  61455. IMAGEPROCESSINGPOSTPROCESS: false,
  61456. EXPOSURE: false,
  61457. };
  61458. // Setup the configuration as forced by the constructor. This would then not force the
  61459. // scene materials output in linear space and let untouched the default forward pass.
  61460. if (imageProcessingConfiguration) {
  61461. imageProcessingConfiguration.applyByPostProcess = true;
  61462. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  61463. // This will cause the shader to be compiled
  61464. _this.fromLinearSpace = false;
  61465. }
  61466. else {
  61467. _this._attachImageProcessingConfiguration(null, true);
  61468. _this.imageProcessingConfiguration.applyByPostProcess = true;
  61469. }
  61470. _this.onApply = function (effect) {
  61471. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  61472. };
  61473. return _this;
  61474. }
  61475. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  61476. /**
  61477. * Gets the image processing configuration used either in this material.
  61478. */
  61479. get: function () {
  61480. return this._imageProcessingConfiguration;
  61481. },
  61482. /**
  61483. * Sets the Default image processing configuration used either in the this material.
  61484. *
  61485. * If sets to null, the scene one is in use.
  61486. */
  61487. set: function (value) {
  61488. this._attachImageProcessingConfiguration(value);
  61489. },
  61490. enumerable: true,
  61491. configurable: true
  61492. });
  61493. /**
  61494. * Attaches a new image processing configuration to the PBR Material.
  61495. * @param configuration
  61496. */
  61497. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  61498. var _this = this;
  61499. if (doNotBuild === void 0) { doNotBuild = false; }
  61500. if (configuration === this._imageProcessingConfiguration) {
  61501. return;
  61502. }
  61503. // Detaches observer.
  61504. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  61505. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  61506. }
  61507. // Pick the scene configuration if needed.
  61508. if (!configuration) {
  61509. var scene = null;
  61510. var engine = this.getEngine();
  61511. var camera = this.getCamera();
  61512. if (camera) {
  61513. scene = camera.getScene();
  61514. }
  61515. else if (engine && engine.scenes) {
  61516. var scenes = engine.scenes;
  61517. scene = scenes[scenes.length - 1];
  61518. }
  61519. else {
  61520. scene = BABYLON.Engine.LastCreatedScene;
  61521. }
  61522. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  61523. }
  61524. else {
  61525. this._imageProcessingConfiguration = configuration;
  61526. }
  61527. // Attaches observer.
  61528. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  61529. _this._updateParameters();
  61530. });
  61531. // Ensure the effect will be rebuilt.
  61532. if (!doNotBuild) {
  61533. this._updateParameters();
  61534. }
  61535. };
  61536. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  61537. /**
  61538. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  61539. */
  61540. get: function () {
  61541. return this.imageProcessingConfiguration.colorCurves;
  61542. },
  61543. /**
  61544. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  61545. */
  61546. set: function (value) {
  61547. this.imageProcessingConfiguration.colorCurves = value;
  61548. },
  61549. enumerable: true,
  61550. configurable: true
  61551. });
  61552. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  61553. /**
  61554. * Gets wether the color curves effect is enabled.
  61555. */
  61556. get: function () {
  61557. return this.imageProcessingConfiguration.colorCurvesEnabled;
  61558. },
  61559. /**
  61560. * Sets wether the color curves effect is enabled.
  61561. */
  61562. set: function (value) {
  61563. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  61564. },
  61565. enumerable: true,
  61566. configurable: true
  61567. });
  61568. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  61569. /**
  61570. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  61571. */
  61572. get: function () {
  61573. return this.imageProcessingConfiguration.colorGradingTexture;
  61574. },
  61575. /**
  61576. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  61577. */
  61578. set: function (value) {
  61579. this.imageProcessingConfiguration.colorGradingTexture = value;
  61580. },
  61581. enumerable: true,
  61582. configurable: true
  61583. });
  61584. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  61585. /**
  61586. * Gets wether the color grading effect is enabled.
  61587. */
  61588. get: function () {
  61589. return this.imageProcessingConfiguration.colorGradingEnabled;
  61590. },
  61591. /**
  61592. * Gets wether the color grading effect is enabled.
  61593. */
  61594. set: function (value) {
  61595. this.imageProcessingConfiguration.colorGradingEnabled = value;
  61596. },
  61597. enumerable: true,
  61598. configurable: true
  61599. });
  61600. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  61601. /**
  61602. * Gets exposure used in the effect.
  61603. */
  61604. get: function () {
  61605. return this.imageProcessingConfiguration.exposure;
  61606. },
  61607. /**
  61608. * Sets exposure used in the effect.
  61609. */
  61610. set: function (value) {
  61611. this.imageProcessingConfiguration.exposure = value;
  61612. },
  61613. enumerable: true,
  61614. configurable: true
  61615. });
  61616. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  61617. /**
  61618. * Gets wether tonemapping is enabled or not.
  61619. */
  61620. get: function () {
  61621. return this._imageProcessingConfiguration.toneMappingEnabled;
  61622. },
  61623. /**
  61624. * Sets wether tonemapping is enabled or not
  61625. */
  61626. set: function (value) {
  61627. this._imageProcessingConfiguration.toneMappingEnabled = value;
  61628. },
  61629. enumerable: true,
  61630. configurable: true
  61631. });
  61632. ;
  61633. ;
  61634. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  61635. /**
  61636. * Gets contrast used in the effect.
  61637. */
  61638. get: function () {
  61639. return this.imageProcessingConfiguration.contrast;
  61640. },
  61641. /**
  61642. * Sets contrast used in the effect.
  61643. */
  61644. set: function (value) {
  61645. this.imageProcessingConfiguration.contrast = value;
  61646. },
  61647. enumerable: true,
  61648. configurable: true
  61649. });
  61650. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  61651. /**
  61652. * Gets Vignette stretch size.
  61653. */
  61654. get: function () {
  61655. return this.imageProcessingConfiguration.vignetteStretch;
  61656. },
  61657. /**
  61658. * Sets Vignette stretch size.
  61659. */
  61660. set: function (value) {
  61661. this.imageProcessingConfiguration.vignetteStretch = value;
  61662. },
  61663. enumerable: true,
  61664. configurable: true
  61665. });
  61666. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  61667. /**
  61668. * Gets Vignette centre X Offset.
  61669. */
  61670. get: function () {
  61671. return this.imageProcessingConfiguration.vignetteCentreX;
  61672. },
  61673. /**
  61674. * Sets Vignette centre X Offset.
  61675. */
  61676. set: function (value) {
  61677. this.imageProcessingConfiguration.vignetteCentreX = value;
  61678. },
  61679. enumerable: true,
  61680. configurable: true
  61681. });
  61682. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  61683. /**
  61684. * Gets Vignette centre Y Offset.
  61685. */
  61686. get: function () {
  61687. return this.imageProcessingConfiguration.vignetteCentreY;
  61688. },
  61689. /**
  61690. * Sets Vignette centre Y Offset.
  61691. */
  61692. set: function (value) {
  61693. this.imageProcessingConfiguration.vignetteCentreY = value;
  61694. },
  61695. enumerable: true,
  61696. configurable: true
  61697. });
  61698. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  61699. /**
  61700. * Gets Vignette weight or intensity of the vignette effect.
  61701. */
  61702. get: function () {
  61703. return this.imageProcessingConfiguration.vignetteWeight;
  61704. },
  61705. /**
  61706. * Sets Vignette weight or intensity of the vignette effect.
  61707. */
  61708. set: function (value) {
  61709. this.imageProcessingConfiguration.vignetteWeight = value;
  61710. },
  61711. enumerable: true,
  61712. configurable: true
  61713. });
  61714. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  61715. /**
  61716. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  61717. * if vignetteEnabled is set to true.
  61718. */
  61719. get: function () {
  61720. return this.imageProcessingConfiguration.vignetteColor;
  61721. },
  61722. /**
  61723. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  61724. * if vignetteEnabled is set to true.
  61725. */
  61726. set: function (value) {
  61727. this.imageProcessingConfiguration.vignetteColor = value;
  61728. },
  61729. enumerable: true,
  61730. configurable: true
  61731. });
  61732. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  61733. /**
  61734. * Gets Camera field of view used by the Vignette effect.
  61735. */
  61736. get: function () {
  61737. return this.imageProcessingConfiguration.vignetteCameraFov;
  61738. },
  61739. /**
  61740. * Sets Camera field of view used by the Vignette effect.
  61741. */
  61742. set: function (value) {
  61743. this.imageProcessingConfiguration.vignetteCameraFov = value;
  61744. },
  61745. enumerable: true,
  61746. configurable: true
  61747. });
  61748. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  61749. /**
  61750. * Gets the vignette blend mode allowing different kind of effect.
  61751. */
  61752. get: function () {
  61753. return this.imageProcessingConfiguration.vignetteBlendMode;
  61754. },
  61755. /**
  61756. * Sets the vignette blend mode allowing different kind of effect.
  61757. */
  61758. set: function (value) {
  61759. this.imageProcessingConfiguration.vignetteBlendMode = value;
  61760. },
  61761. enumerable: true,
  61762. configurable: true
  61763. });
  61764. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  61765. /**
  61766. * Gets wether the vignette effect is enabled.
  61767. */
  61768. get: function () {
  61769. return this.imageProcessingConfiguration.vignetteEnabled;
  61770. },
  61771. /**
  61772. * Sets wether the vignette effect is enabled.
  61773. */
  61774. set: function (value) {
  61775. this.imageProcessingConfiguration.vignetteEnabled = value;
  61776. },
  61777. enumerable: true,
  61778. configurable: true
  61779. });
  61780. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  61781. /**
  61782. * Gets wether the input of the processing is in Gamma or Linear Space.
  61783. */
  61784. get: function () {
  61785. return this._fromLinearSpace;
  61786. },
  61787. /**
  61788. * Sets wether the input of the processing is in Gamma or Linear Space.
  61789. */
  61790. set: function (value) {
  61791. if (this._fromLinearSpace === value) {
  61792. return;
  61793. }
  61794. this._fromLinearSpace = value;
  61795. this._updateParameters();
  61796. },
  61797. enumerable: true,
  61798. configurable: true
  61799. });
  61800. ImageProcessingPostProcess.prototype.getClassName = function () {
  61801. return "ImageProcessingPostProcess";
  61802. };
  61803. ImageProcessingPostProcess.prototype._updateParameters = function () {
  61804. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  61805. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  61806. var defines = "";
  61807. for (var define in this._defines) {
  61808. if (this._defines[define]) {
  61809. defines += "#define " + define + ";\r\n";
  61810. }
  61811. }
  61812. var samplers = ["textureSampler"];
  61813. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  61814. var uniforms = ["scale"];
  61815. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  61816. this.updateEffect(defines, uniforms, samplers);
  61817. };
  61818. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  61819. _super.prototype.dispose.call(this, camera);
  61820. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  61821. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  61822. }
  61823. this.imageProcessingConfiguration.applyByPostProcess = false;
  61824. };
  61825. __decorate([
  61826. BABYLON.serialize()
  61827. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  61828. return ImageProcessingPostProcess;
  61829. }(BABYLON.PostProcess));
  61830. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  61831. })(BABYLON || (BABYLON = {}));
  61832. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  61833. var BABYLON;
  61834. (function (BABYLON) {
  61835. var BlurPostProcess = /** @class */ (function (_super) {
  61836. __extends(BlurPostProcess, _super);
  61837. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  61838. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  61839. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61840. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  61841. _this.direction = direction;
  61842. _this._packedFloat = false;
  61843. _this.onApplyObservable.add(function (effect) {
  61844. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  61845. });
  61846. _this.kernel = kernel;
  61847. return _this;
  61848. }
  61849. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  61850. /**
  61851. * Gets the length in pixels of the blur sample region
  61852. */
  61853. get: function () {
  61854. return this._idealKernel;
  61855. },
  61856. /**
  61857. * Sets the length in pixels of the blur sample region
  61858. */
  61859. set: function (v) {
  61860. if (this._idealKernel === v) {
  61861. return;
  61862. }
  61863. v = Math.max(v, 1);
  61864. this._idealKernel = v;
  61865. this._kernel = this._nearestBestKernel(v);
  61866. this._updateParameters();
  61867. },
  61868. enumerable: true,
  61869. configurable: true
  61870. });
  61871. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  61872. /**
  61873. * Gets wether or not the blur is unpacking/repacking floats
  61874. */
  61875. get: function () {
  61876. return this._packedFloat;
  61877. },
  61878. /**
  61879. * Sets wether or not the blur needs to unpack/repack floats
  61880. */
  61881. set: function (v) {
  61882. if (this._packedFloat === v) {
  61883. return;
  61884. }
  61885. this._packedFloat = v;
  61886. this._updateParameters();
  61887. },
  61888. enumerable: true,
  61889. configurable: true
  61890. });
  61891. BlurPostProcess.prototype._updateParameters = function () {
  61892. // Generate sampling offsets and weights
  61893. var N = this._kernel;
  61894. var centerIndex = (N - 1) / 2;
  61895. // Generate Gaussian sampling weights over kernel
  61896. var offsets = [];
  61897. var weights = [];
  61898. var totalWeight = 0;
  61899. for (var i = 0; i < N; i++) {
  61900. var u = i / (N - 1);
  61901. var w = this._gaussianWeight(u * 2.0 - 1);
  61902. offsets[i] = (i - centerIndex);
  61903. weights[i] = w;
  61904. totalWeight += w;
  61905. }
  61906. // Normalize weights
  61907. for (var i = 0; i < weights.length; i++) {
  61908. weights[i] /= totalWeight;
  61909. }
  61910. // Optimize: combine samples to take advantage of hardware linear sampling
  61911. // Walk from left to center, combining pairs (symmetrically)
  61912. var linearSamplingWeights = [];
  61913. var linearSamplingOffsets = [];
  61914. var linearSamplingMap = [];
  61915. for (var i = 0; i <= centerIndex; i += 2) {
  61916. var j = Math.min(i + 1, Math.floor(centerIndex));
  61917. var singleCenterSample = i === j;
  61918. if (singleCenterSample) {
  61919. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  61920. }
  61921. else {
  61922. var sharedCell = j === centerIndex;
  61923. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  61924. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  61925. if (offsetLinear === 0) {
  61926. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  61927. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  61928. }
  61929. else {
  61930. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  61931. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  61932. }
  61933. }
  61934. }
  61935. for (var i = 0; i < linearSamplingMap.length; i++) {
  61936. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  61937. linearSamplingWeights[i] = linearSamplingMap[i].w;
  61938. }
  61939. // Replace with optimized
  61940. offsets = linearSamplingOffsets;
  61941. weights = linearSamplingWeights;
  61942. // Generate shaders
  61943. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  61944. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  61945. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  61946. var defines = "";
  61947. for (var i = 0; i < varyingCount; i++) {
  61948. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  61949. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  61950. }
  61951. var depCount = 0;
  61952. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  61953. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  61954. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  61955. depCount++;
  61956. }
  61957. if (this.packedFloat) {
  61958. defines += "#define PACKEDFLOAT 1";
  61959. }
  61960. this.updateEffect(defines, null, null, {
  61961. varyingCount: varyingCount,
  61962. depCount: depCount
  61963. });
  61964. };
  61965. /**
  61966. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  61967. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  61968. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  61969. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  61970. * The gaps between physical kernels are compensated for in the weighting of the samples
  61971. * @param idealKernel Ideal blur kernel.
  61972. * @return Nearest best kernel.
  61973. */
  61974. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  61975. var v = Math.round(idealKernel);
  61976. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  61977. var k = _a[_i];
  61978. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  61979. return Math.max(k, 3);
  61980. }
  61981. }
  61982. return Math.max(v, 3);
  61983. };
  61984. /**
  61985. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  61986. * @param x The point on the Gaussian distribution to sample.
  61987. * @return the value of the Gaussian function at x.
  61988. */
  61989. BlurPostProcess.prototype._gaussianWeight = function (x) {
  61990. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  61991. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  61992. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  61993. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  61994. // truncated at around 1.3% of peak strength.
  61995. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  61996. var sigma = (1 / 3);
  61997. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  61998. var exponent = -((x * x) / (2.0 * sigma * sigma));
  61999. var weight = (1.0 / denominator) * Math.exp(exponent);
  62000. return weight;
  62001. };
  62002. /**
  62003. * Generates a string that can be used as a floating point number in GLSL.
  62004. * @param x Value to print.
  62005. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  62006. * @return GLSL float string.
  62007. */
  62008. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  62009. if (decimalFigures === void 0) { decimalFigures = 8; }
  62010. return x.toFixed(decimalFigures).replace(/0+$/, '');
  62011. };
  62012. return BlurPostProcess;
  62013. }(BABYLON.PostProcess));
  62014. BABYLON.BlurPostProcess = BlurPostProcess;
  62015. })(BABYLON || (BABYLON = {}));
  62016. //# sourceMappingURL=babylon.blurPostProcess.js.map
  62017. var BABYLON;
  62018. (function (BABYLON) {
  62019. var Bone = /** @class */ (function (_super) {
  62020. __extends(Bone, _super);
  62021. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  62022. if (parentBone === void 0) { parentBone = null; }
  62023. if (localMatrix === void 0) { localMatrix = null; }
  62024. if (restPose === void 0) { restPose = null; }
  62025. if (baseMatrix === void 0) { baseMatrix = null; }
  62026. if (index === void 0) { index = null; }
  62027. var _this = _super.call(this, name, skeleton.getScene()) || this;
  62028. _this.name = name;
  62029. _this.children = new Array();
  62030. _this.animations = new Array();
  62031. // Set this value to map this bone to a different index in the transform matrices.
  62032. // Set this value to -1 to exclude the bone from the transform matrices.
  62033. _this._index = null;
  62034. _this._worldTransform = new BABYLON.Matrix();
  62035. _this._absoluteTransform = new BABYLON.Matrix();
  62036. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  62037. _this._scaleMatrix = BABYLON.Matrix.Identity();
  62038. _this._scaleVector = BABYLON.Vector3.One();
  62039. _this._negateScaleChildren = BABYLON.Vector3.One();
  62040. _this._scalingDeterminant = 1;
  62041. _this._skeleton = skeleton;
  62042. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  62043. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  62044. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  62045. _this._index = index;
  62046. skeleton.bones.push(_this);
  62047. _this.setParent(parentBone, false);
  62048. _this._updateDifferenceMatrix();
  62049. return _this;
  62050. }
  62051. Object.defineProperty(Bone.prototype, "_matrix", {
  62052. get: function () {
  62053. return this._localMatrix;
  62054. },
  62055. set: function (val) {
  62056. if (this._localMatrix) {
  62057. this._localMatrix.copyFrom(val);
  62058. }
  62059. else {
  62060. this._localMatrix = val;
  62061. }
  62062. },
  62063. enumerable: true,
  62064. configurable: true
  62065. });
  62066. // Members
  62067. Bone.prototype.getSkeleton = function () {
  62068. return this._skeleton;
  62069. };
  62070. Bone.prototype.getParent = function () {
  62071. return this._parent;
  62072. };
  62073. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  62074. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  62075. if (this._parent === parent) {
  62076. return;
  62077. }
  62078. if (this._parent) {
  62079. var index = this._parent.children.indexOf(this);
  62080. if (index !== -1) {
  62081. this._parent.children.splice(index, 1);
  62082. }
  62083. }
  62084. this._parent = parent;
  62085. if (this._parent) {
  62086. this._parent.children.push(this);
  62087. }
  62088. if (updateDifferenceMatrix) {
  62089. this._updateDifferenceMatrix();
  62090. }
  62091. };
  62092. Bone.prototype.getLocalMatrix = function () {
  62093. return this._localMatrix;
  62094. };
  62095. Bone.prototype.getBaseMatrix = function () {
  62096. return this._baseMatrix;
  62097. };
  62098. Bone.prototype.getRestPose = function () {
  62099. return this._restPose;
  62100. };
  62101. Bone.prototype.returnToRest = function () {
  62102. this.updateMatrix(this._restPose.clone());
  62103. };
  62104. Bone.prototype.getWorldMatrix = function () {
  62105. return this._worldTransform;
  62106. };
  62107. Bone.prototype.getInvertedAbsoluteTransform = function () {
  62108. return this._invertedAbsoluteTransform;
  62109. };
  62110. Bone.prototype.getAbsoluteTransform = function () {
  62111. return this._absoluteTransform;
  62112. };
  62113. Object.defineProperty(Bone.prototype, "position", {
  62114. // Properties (matches AbstractMesh properties)
  62115. get: function () {
  62116. return this.getPosition();
  62117. },
  62118. set: function (newPosition) {
  62119. this.setPosition(newPosition);
  62120. },
  62121. enumerable: true,
  62122. configurable: true
  62123. });
  62124. Object.defineProperty(Bone.prototype, "rotation", {
  62125. get: function () {
  62126. return this.getRotation();
  62127. },
  62128. set: function (newRotation) {
  62129. this.setRotation(newRotation);
  62130. },
  62131. enumerable: true,
  62132. configurable: true
  62133. });
  62134. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  62135. get: function () {
  62136. return this.getRotationQuaternion();
  62137. },
  62138. set: function (newRotation) {
  62139. this.setRotationQuaternion(newRotation);
  62140. },
  62141. enumerable: true,
  62142. configurable: true
  62143. });
  62144. Object.defineProperty(Bone.prototype, "scaling", {
  62145. get: function () {
  62146. return this.getScale();
  62147. },
  62148. set: function (newScaling) {
  62149. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  62150. },
  62151. enumerable: true,
  62152. configurable: true
  62153. });
  62154. // Methods
  62155. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  62156. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  62157. this._baseMatrix = matrix.clone();
  62158. this._localMatrix = matrix.clone();
  62159. this._skeleton._markAsDirty();
  62160. if (updateDifferenceMatrix) {
  62161. this._updateDifferenceMatrix();
  62162. }
  62163. };
  62164. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  62165. if (!rootMatrix) {
  62166. rootMatrix = this._baseMatrix;
  62167. }
  62168. if (this._parent) {
  62169. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  62170. }
  62171. else {
  62172. this._absoluteTransform.copyFrom(rootMatrix);
  62173. }
  62174. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  62175. for (var index = 0; index < this.children.length; index++) {
  62176. this.children[index]._updateDifferenceMatrix();
  62177. }
  62178. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  62179. };
  62180. Bone.prototype.markAsDirty = function () {
  62181. this._currentRenderId++;
  62182. this._skeleton._markAsDirty();
  62183. };
  62184. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  62185. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  62186. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  62187. // all animation may be coming from a library skeleton, so may need to create animation
  62188. if (this.animations.length === 0) {
  62189. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  62190. this.animations[0].setKeys([]);
  62191. }
  62192. // get animation info / verify there is such a range from the source bone
  62193. var sourceRange = source.animations[0].getRange(rangeName);
  62194. if (!sourceRange) {
  62195. return false;
  62196. }
  62197. var from = sourceRange.from;
  62198. var to = sourceRange.to;
  62199. var sourceKeys = source.animations[0].getKeys();
  62200. // rescaling prep
  62201. var sourceBoneLength = source.length;
  62202. var sourceParent = source.getParent();
  62203. var parent = this.getParent();
  62204. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  62205. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  62206. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  62207. var destKeys = this.animations[0].getKeys();
  62208. // loop vars declaration
  62209. var orig;
  62210. var origTranslation;
  62211. var mat;
  62212. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  62213. orig = sourceKeys[key];
  62214. if (orig.frame >= from && orig.frame <= to) {
  62215. if (rescaleAsRequired) {
  62216. mat = orig.value.clone();
  62217. // scale based on parent ratio, when bone has parent
  62218. if (parentScalingReqd) {
  62219. origTranslation = mat.getTranslation();
  62220. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  62221. // scale based on skeleton dimension ratio when root bone, and value is passed
  62222. }
  62223. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  62224. origTranslation = mat.getTranslation();
  62225. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  62226. // use original when root bone, and no data for skelDimensionsRatio
  62227. }
  62228. else {
  62229. mat = orig.value;
  62230. }
  62231. }
  62232. else {
  62233. mat = orig.value;
  62234. }
  62235. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  62236. }
  62237. }
  62238. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  62239. return true;
  62240. };
  62241. /**
  62242. * Translate the bone in local or world space.
  62243. * @param vec The amount to translate the bone.
  62244. * @param space The space that the translation is in.
  62245. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62246. */
  62247. Bone.prototype.translate = function (vec, space, mesh) {
  62248. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62249. var lm = this.getLocalMatrix();
  62250. if (space == BABYLON.Space.LOCAL) {
  62251. lm.m[12] += vec.x;
  62252. lm.m[13] += vec.y;
  62253. lm.m[14] += vec.z;
  62254. }
  62255. else {
  62256. var wm = null;
  62257. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  62258. if (mesh) {
  62259. wm = mesh.getWorldMatrix();
  62260. }
  62261. this._skeleton.computeAbsoluteTransforms();
  62262. var tmat = Bone._tmpMats[0];
  62263. var tvec = Bone._tmpVecs[0];
  62264. if (this._parent) {
  62265. if (mesh && wm) {
  62266. tmat.copyFrom(this._parent.getAbsoluteTransform());
  62267. tmat.multiplyToRef(wm, tmat);
  62268. }
  62269. else {
  62270. tmat.copyFrom(this._parent.getAbsoluteTransform());
  62271. }
  62272. }
  62273. tmat.m[12] = 0;
  62274. tmat.m[13] = 0;
  62275. tmat.m[14] = 0;
  62276. tmat.invert();
  62277. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  62278. lm.m[12] += tvec.x;
  62279. lm.m[13] += tvec.y;
  62280. lm.m[14] += tvec.z;
  62281. }
  62282. this.markAsDirty();
  62283. };
  62284. /**
  62285. * Set the postion of the bone in local or world space.
  62286. * @param position The position to set the bone.
  62287. * @param space The space that the position is in.
  62288. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62289. */
  62290. Bone.prototype.setPosition = function (position, space, mesh) {
  62291. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62292. var lm = this.getLocalMatrix();
  62293. if (space == BABYLON.Space.LOCAL) {
  62294. lm.m[12] = position.x;
  62295. lm.m[13] = position.y;
  62296. lm.m[14] = position.z;
  62297. }
  62298. else {
  62299. var wm = null;
  62300. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  62301. if (mesh) {
  62302. wm = mesh.getWorldMatrix();
  62303. }
  62304. this._skeleton.computeAbsoluteTransforms();
  62305. var tmat = Bone._tmpMats[0];
  62306. var vec = Bone._tmpVecs[0];
  62307. if (this._parent) {
  62308. if (mesh && wm) {
  62309. tmat.copyFrom(this._parent.getAbsoluteTransform());
  62310. tmat.multiplyToRef(wm, tmat);
  62311. }
  62312. else {
  62313. tmat.copyFrom(this._parent.getAbsoluteTransform());
  62314. }
  62315. }
  62316. tmat.invert();
  62317. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  62318. lm.m[12] = vec.x;
  62319. lm.m[13] = vec.y;
  62320. lm.m[14] = vec.z;
  62321. }
  62322. this.markAsDirty();
  62323. };
  62324. /**
  62325. * Set the absolute postion of the bone (world space).
  62326. * @param position The position to set the bone.
  62327. * @param mesh The mesh that this bone is attached to.
  62328. */
  62329. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  62330. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  62331. };
  62332. /**
  62333. * Set the scale of the bone on the x, y and z axes.
  62334. * @param x The scale of the bone on the x axis.
  62335. * @param x The scale of the bone on the y axis.
  62336. * @param z The scale of the bone on the z axis.
  62337. * @param scaleChildren Set this to true if children of the bone should be scaled.
  62338. */
  62339. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  62340. if (scaleChildren === void 0) { scaleChildren = false; }
  62341. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  62342. if (!scaleChildren) {
  62343. this._negateScaleChildren.x = 1 / x;
  62344. this._negateScaleChildren.y = 1 / y;
  62345. this._negateScaleChildren.z = 1 / z;
  62346. }
  62347. this._syncScaleVector();
  62348. }
  62349. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  62350. };
  62351. /**
  62352. * Scale the bone on the x, y and z axes.
  62353. * @param x The amount to scale the bone on the x axis.
  62354. * @param x The amount to scale the bone on the y axis.
  62355. * @param z The amount to scale the bone on the z axis.
  62356. * @param scaleChildren Set this to true if children of the bone should be scaled.
  62357. */
  62358. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  62359. if (scaleChildren === void 0) { scaleChildren = false; }
  62360. var locMat = this.getLocalMatrix();
  62361. var origLocMat = Bone._tmpMats[0];
  62362. origLocMat.copyFrom(locMat);
  62363. var origLocMatInv = Bone._tmpMats[1];
  62364. origLocMatInv.copyFrom(origLocMat);
  62365. origLocMatInv.invert();
  62366. var scaleMat = Bone._tmpMats[2];
  62367. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  62368. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  62369. this._scaleVector.x *= x;
  62370. this._scaleVector.y *= y;
  62371. this._scaleVector.z *= z;
  62372. locMat.multiplyToRef(origLocMatInv, locMat);
  62373. locMat.multiplyToRef(scaleMat, locMat);
  62374. locMat.multiplyToRef(origLocMat, locMat);
  62375. var parent = this.getParent();
  62376. if (parent) {
  62377. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  62378. }
  62379. else {
  62380. this.getAbsoluteTransform().copyFrom(locMat);
  62381. }
  62382. var len = this.children.length;
  62383. scaleMat.invert();
  62384. for (var i = 0; i < len; i++) {
  62385. var child = this.children[i];
  62386. var cm = child.getLocalMatrix();
  62387. cm.multiplyToRef(scaleMat, cm);
  62388. var lm = child.getLocalMatrix();
  62389. lm.m[12] *= x;
  62390. lm.m[13] *= y;
  62391. lm.m[14] *= z;
  62392. }
  62393. this.computeAbsoluteTransforms();
  62394. if (scaleChildren) {
  62395. for (var i = 0; i < len; i++) {
  62396. this.children[i].scale(x, y, z, scaleChildren);
  62397. }
  62398. }
  62399. this.markAsDirty();
  62400. };
  62401. /**
  62402. * Set the yaw, pitch, and roll of the bone in local or world space.
  62403. * @param yaw The rotation of the bone on the y axis.
  62404. * @param pitch The rotation of the bone on the x axis.
  62405. * @param roll The rotation of the bone on the z axis.
  62406. * @param space The space that the axes of rotation are in.
  62407. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62408. */
  62409. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  62410. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62411. var rotMat = Bone._tmpMats[0];
  62412. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  62413. var rotMatInv = Bone._tmpMats[1];
  62414. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  62415. rotMatInv.multiplyToRef(rotMat, rotMat);
  62416. this._rotateWithMatrix(rotMat, space, mesh);
  62417. };
  62418. /**
  62419. * Rotate the bone on an axis in local or world space.
  62420. * @param axis The axis to rotate the bone on.
  62421. * @param amount The amount to rotate the bone.
  62422. * @param space The space that the axis is in.
  62423. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62424. */
  62425. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  62426. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62427. var rmat = Bone._tmpMats[0];
  62428. rmat.m[12] = 0;
  62429. rmat.m[13] = 0;
  62430. rmat.m[14] = 0;
  62431. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  62432. this._rotateWithMatrix(rmat, space, mesh);
  62433. };
  62434. /**
  62435. * Set the rotation of the bone to a particular axis angle in local or world space.
  62436. * @param axis The axis to rotate the bone on.
  62437. * @param angle The angle that the bone should be rotated to.
  62438. * @param space The space that the axis is in.
  62439. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62440. */
  62441. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  62442. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62443. var rotMat = Bone._tmpMats[0];
  62444. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  62445. var rotMatInv = Bone._tmpMats[1];
  62446. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  62447. rotMatInv.multiplyToRef(rotMat, rotMat);
  62448. this._rotateWithMatrix(rotMat, space, mesh);
  62449. };
  62450. /**
  62451. * Set the euler rotation of the bone in local of world space.
  62452. * @param rotation The euler rotation that the bone should be set to.
  62453. * @param space The space that the rotation is in.
  62454. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62455. */
  62456. Bone.prototype.setRotation = function (rotation, space, mesh) {
  62457. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62458. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  62459. };
  62460. /**
  62461. * Set the quaternion rotation of the bone in local of world space.
  62462. * @param quat The quaternion rotation that the bone should be set to.
  62463. * @param space The space that the rotation is in.
  62464. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62465. */
  62466. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  62467. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62468. var rotMatInv = Bone._tmpMats[0];
  62469. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  62470. var rotMat = Bone._tmpMats[1];
  62471. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  62472. rotMatInv.multiplyToRef(rotMat, rotMat);
  62473. this._rotateWithMatrix(rotMat, space, mesh);
  62474. };
  62475. /**
  62476. * Set the rotation matrix of the bone in local of world space.
  62477. * @param rotMat The rotation matrix that the bone should be set to.
  62478. * @param space The space that the rotation is in.
  62479. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62480. */
  62481. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  62482. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62483. var rotMatInv = Bone._tmpMats[0];
  62484. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  62485. var rotMat2 = Bone._tmpMats[1];
  62486. rotMat2.copyFrom(rotMat);
  62487. rotMatInv.multiplyToRef(rotMat, rotMat2);
  62488. this._rotateWithMatrix(rotMat2, space, mesh);
  62489. };
  62490. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  62491. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62492. var lmat = this.getLocalMatrix();
  62493. var lx = lmat.m[12];
  62494. var ly = lmat.m[13];
  62495. var lz = lmat.m[14];
  62496. var parent = this.getParent();
  62497. var parentScale = Bone._tmpMats[3];
  62498. var parentScaleInv = Bone._tmpMats[4];
  62499. if (parent) {
  62500. if (space == BABYLON.Space.WORLD) {
  62501. if (mesh) {
  62502. parentScale.copyFrom(mesh.getWorldMatrix());
  62503. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  62504. }
  62505. else {
  62506. parentScale.copyFrom(parent.getAbsoluteTransform());
  62507. }
  62508. }
  62509. else {
  62510. parentScale = parent._scaleMatrix;
  62511. }
  62512. parentScaleInv.copyFrom(parentScale);
  62513. parentScaleInv.invert();
  62514. lmat.multiplyToRef(parentScale, lmat);
  62515. lmat.multiplyToRef(rmat, lmat);
  62516. lmat.multiplyToRef(parentScaleInv, lmat);
  62517. }
  62518. else {
  62519. if (space == BABYLON.Space.WORLD && mesh) {
  62520. parentScale.copyFrom(mesh.getWorldMatrix());
  62521. parentScaleInv.copyFrom(parentScale);
  62522. parentScaleInv.invert();
  62523. lmat.multiplyToRef(parentScale, lmat);
  62524. lmat.multiplyToRef(rmat, lmat);
  62525. lmat.multiplyToRef(parentScaleInv, lmat);
  62526. }
  62527. else {
  62528. lmat.multiplyToRef(rmat, lmat);
  62529. }
  62530. }
  62531. lmat.m[12] = lx;
  62532. lmat.m[13] = ly;
  62533. lmat.m[14] = lz;
  62534. this.computeAbsoluteTransforms();
  62535. this.markAsDirty();
  62536. };
  62537. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  62538. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62539. if (space == BABYLON.Space.WORLD) {
  62540. var scaleMatrix = Bone._tmpMats[2];
  62541. scaleMatrix.copyFrom(this._scaleMatrix);
  62542. rotMatInv.copyFrom(this.getAbsoluteTransform());
  62543. if (mesh) {
  62544. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  62545. var meshScale = Bone._tmpMats[3];
  62546. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  62547. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  62548. }
  62549. rotMatInv.invert();
  62550. scaleMatrix.m[0] *= this._scalingDeterminant;
  62551. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  62552. }
  62553. else {
  62554. rotMatInv.copyFrom(this.getLocalMatrix());
  62555. rotMatInv.invert();
  62556. var scaleMatrix = Bone._tmpMats[2];
  62557. scaleMatrix.copyFrom(this._scaleMatrix);
  62558. if (this._parent) {
  62559. var pscaleMatrix = Bone._tmpMats[3];
  62560. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  62561. pscaleMatrix.invert();
  62562. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  62563. }
  62564. else {
  62565. scaleMatrix.m[0] *= this._scalingDeterminant;
  62566. }
  62567. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  62568. }
  62569. };
  62570. /**
  62571. * Get the scale of the bone
  62572. * @returns the scale of the bone
  62573. */
  62574. Bone.prototype.getScale = function () {
  62575. return this._scaleVector.clone();
  62576. };
  62577. /**
  62578. * Copy the scale of the bone to a vector3.
  62579. * @param result The vector3 to copy the scale to
  62580. */
  62581. Bone.prototype.getScaleToRef = function (result) {
  62582. result.copyFrom(this._scaleVector);
  62583. };
  62584. /**
  62585. * Get the position of the bone in local or world space.
  62586. * @param space The space that the returned position is in.
  62587. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62588. * @returns The position of the bone
  62589. */
  62590. Bone.prototype.getPosition = function (space, mesh) {
  62591. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62592. if (mesh === void 0) { mesh = null; }
  62593. var pos = BABYLON.Vector3.Zero();
  62594. this.getPositionToRef(space, mesh, pos);
  62595. return pos;
  62596. };
  62597. /**
  62598. * Copy the position of the bone to a vector3 in local or world space.
  62599. * @param space The space that the returned position is in.
  62600. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62601. * @param result The vector3 to copy the position to.
  62602. */
  62603. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  62604. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62605. if (space == BABYLON.Space.LOCAL) {
  62606. var lm = this.getLocalMatrix();
  62607. result.x = lm.m[12];
  62608. result.y = lm.m[13];
  62609. result.z = lm.m[14];
  62610. }
  62611. else {
  62612. var wm = null;
  62613. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  62614. if (mesh) {
  62615. wm = mesh.getWorldMatrix();
  62616. }
  62617. this._skeleton.computeAbsoluteTransforms();
  62618. var tmat = Bone._tmpMats[0];
  62619. if (mesh && wm) {
  62620. tmat.copyFrom(this.getAbsoluteTransform());
  62621. tmat.multiplyToRef(wm, tmat);
  62622. }
  62623. else {
  62624. tmat = this.getAbsoluteTransform();
  62625. }
  62626. result.x = tmat.m[12];
  62627. result.y = tmat.m[13];
  62628. result.z = tmat.m[14];
  62629. }
  62630. };
  62631. /**
  62632. * Get the absolute position of the bone (world space).
  62633. * @param mesh The mesh that this bone is attached to.
  62634. * @returns The absolute position of the bone
  62635. */
  62636. Bone.prototype.getAbsolutePosition = function (mesh) {
  62637. if (mesh === void 0) { mesh = null; }
  62638. var pos = BABYLON.Vector3.Zero();
  62639. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  62640. return pos;
  62641. };
  62642. /**
  62643. * Copy the absolute position of the bone (world space) to the result param.
  62644. * @param mesh The mesh that this bone is attached to.
  62645. * @param result The vector3 to copy the absolute position to.
  62646. */
  62647. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  62648. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  62649. };
  62650. /**
  62651. * Compute the absolute transforms of this bone and its children.
  62652. */
  62653. Bone.prototype.computeAbsoluteTransforms = function () {
  62654. if (this._parent) {
  62655. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  62656. }
  62657. else {
  62658. this._absoluteTransform.copyFrom(this._localMatrix);
  62659. var poseMatrix = this._skeleton.getPoseMatrix();
  62660. if (poseMatrix) {
  62661. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  62662. }
  62663. }
  62664. var children = this.children;
  62665. var len = children.length;
  62666. for (var i = 0; i < len; i++) {
  62667. children[i].computeAbsoluteTransforms();
  62668. }
  62669. };
  62670. Bone.prototype._syncScaleVector = function () {
  62671. var lm = this.getLocalMatrix();
  62672. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  62673. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  62674. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  62675. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  62676. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  62677. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  62678. this._scaleVector.x = xs * Math.sqrt(xsq);
  62679. this._scaleVector.y = ys * Math.sqrt(ysq);
  62680. this._scaleVector.z = zs * Math.sqrt(zsq);
  62681. if (this._parent) {
  62682. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  62683. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  62684. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  62685. }
  62686. 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);
  62687. };
  62688. /**
  62689. * Get the world direction from an axis that is in the local space of the bone.
  62690. * @param localAxis The local direction that is used to compute the world direction.
  62691. * @param mesh The mesh that this bone is attached to.
  62692. * @returns The world direction
  62693. */
  62694. Bone.prototype.getDirection = function (localAxis, mesh) {
  62695. if (mesh === void 0) { mesh = null; }
  62696. var result = BABYLON.Vector3.Zero();
  62697. this.getDirectionToRef(localAxis, mesh, result);
  62698. return result;
  62699. };
  62700. /**
  62701. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  62702. * @param localAxis The local direction that is used to compute the world direction.
  62703. * @param mesh The mesh that this bone is attached to.
  62704. * @param result The vector3 that the world direction will be copied to.
  62705. */
  62706. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  62707. if (mesh === void 0) { mesh = null; }
  62708. var wm = null;
  62709. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  62710. if (mesh) {
  62711. wm = mesh.getWorldMatrix();
  62712. }
  62713. this._skeleton.computeAbsoluteTransforms();
  62714. var mat = Bone._tmpMats[0];
  62715. mat.copyFrom(this.getAbsoluteTransform());
  62716. if (mesh && wm) {
  62717. mat.multiplyToRef(wm, mat);
  62718. }
  62719. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  62720. result.normalize();
  62721. };
  62722. /**
  62723. * Get the euler rotation of the bone in local or world space.
  62724. * @param space The space that the rotation should be in.
  62725. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62726. * @returns The euler rotation
  62727. */
  62728. Bone.prototype.getRotation = function (space, mesh) {
  62729. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62730. if (mesh === void 0) { mesh = null; }
  62731. var result = BABYLON.Vector3.Zero();
  62732. this.getRotationToRef(space, mesh, result);
  62733. return result;
  62734. };
  62735. /**
  62736. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  62737. * @param space The space that the rotation should be in.
  62738. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62739. * @param result The vector3 that the rotation should be copied to.
  62740. */
  62741. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  62742. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62743. if (mesh === void 0) { mesh = null; }
  62744. var quat = Bone._tmpQuat;
  62745. this.getRotationQuaternionToRef(space, mesh, quat);
  62746. quat.toEulerAnglesToRef(result);
  62747. };
  62748. /**
  62749. * Get the quaternion rotation of the bone in either local or world space.
  62750. * @param space The space that the rotation should be in.
  62751. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62752. * @returns The quaternion rotation
  62753. */
  62754. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  62755. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62756. if (mesh === void 0) { mesh = null; }
  62757. var result = BABYLON.Quaternion.Identity();
  62758. this.getRotationQuaternionToRef(space, mesh, result);
  62759. return result;
  62760. };
  62761. /**
  62762. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  62763. * @param space The space that the rotation should be in.
  62764. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62765. * @param result The quaternion that the rotation should be copied to.
  62766. */
  62767. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  62768. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62769. if (mesh === void 0) { mesh = null; }
  62770. if (space == BABYLON.Space.LOCAL) {
  62771. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  62772. }
  62773. else {
  62774. var mat = Bone._tmpMats[0];
  62775. var amat = this.getAbsoluteTransform();
  62776. if (mesh) {
  62777. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  62778. }
  62779. else {
  62780. mat.copyFrom(amat);
  62781. }
  62782. mat.m[0] *= this._scalingDeterminant;
  62783. mat.m[1] *= this._scalingDeterminant;
  62784. mat.m[2] *= this._scalingDeterminant;
  62785. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  62786. }
  62787. };
  62788. /**
  62789. * Get the rotation matrix of the bone in local or world space.
  62790. * @param space The space that the rotation should be in.
  62791. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62792. * @returns The rotation matrix
  62793. */
  62794. Bone.prototype.getRotationMatrix = function (space, mesh) {
  62795. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62796. var result = BABYLON.Matrix.Identity();
  62797. this.getRotationMatrixToRef(space, mesh, result);
  62798. return result;
  62799. };
  62800. /**
  62801. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  62802. * @param space The space that the rotation should be in.
  62803. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62804. * @param result The quaternion that the rotation should be copied to.
  62805. */
  62806. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  62807. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62808. if (space == BABYLON.Space.LOCAL) {
  62809. this.getLocalMatrix().getRotationMatrixToRef(result);
  62810. }
  62811. else {
  62812. var mat = Bone._tmpMats[0];
  62813. var amat = this.getAbsoluteTransform();
  62814. if (mesh) {
  62815. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  62816. }
  62817. else {
  62818. mat.copyFrom(amat);
  62819. }
  62820. mat.m[0] *= this._scalingDeterminant;
  62821. mat.m[1] *= this._scalingDeterminant;
  62822. mat.m[2] *= this._scalingDeterminant;
  62823. mat.getRotationMatrixToRef(result);
  62824. }
  62825. };
  62826. /**
  62827. * Get the world position of a point that is in the local space of the bone.
  62828. * @param position The local position
  62829. * @param mesh The mesh that this bone is attached to.
  62830. * @returns The world position
  62831. */
  62832. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  62833. if (mesh === void 0) { mesh = null; }
  62834. var result = BABYLON.Vector3.Zero();
  62835. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  62836. return result;
  62837. };
  62838. /**
  62839. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  62840. * @param position The local position
  62841. * @param mesh The mesh that this bone is attached to.
  62842. * @param result The vector3 that the world position should be copied to.
  62843. */
  62844. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  62845. if (mesh === void 0) { mesh = null; }
  62846. var wm = null;
  62847. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  62848. if (mesh) {
  62849. wm = mesh.getWorldMatrix();
  62850. }
  62851. this._skeleton.computeAbsoluteTransforms();
  62852. var tmat = Bone._tmpMats[0];
  62853. if (mesh && wm) {
  62854. tmat.copyFrom(this.getAbsoluteTransform());
  62855. tmat.multiplyToRef(wm, tmat);
  62856. }
  62857. else {
  62858. tmat = this.getAbsoluteTransform();
  62859. }
  62860. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  62861. };
  62862. /**
  62863. * Get the local position of a point that is in world space.
  62864. * @param position The world position
  62865. * @param mesh The mesh that this bone is attached to.
  62866. * @returns The local position
  62867. */
  62868. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  62869. if (mesh === void 0) { mesh = null; }
  62870. var result = BABYLON.Vector3.Zero();
  62871. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  62872. return result;
  62873. };
  62874. /**
  62875. * Get the local position of a point that is in world space and copy it to the result param.
  62876. * @param position The world position
  62877. * @param mesh The mesh that this bone is attached to.
  62878. * @param result The vector3 that the local position should be copied to.
  62879. */
  62880. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  62881. if (mesh === void 0) { mesh = null; }
  62882. var wm = null;
  62883. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  62884. if (mesh) {
  62885. wm = mesh.getWorldMatrix();
  62886. }
  62887. this._skeleton.computeAbsoluteTransforms();
  62888. var tmat = Bone._tmpMats[0];
  62889. tmat.copyFrom(this.getAbsoluteTransform());
  62890. if (mesh && wm) {
  62891. tmat.multiplyToRef(wm, tmat);
  62892. }
  62893. tmat.invert();
  62894. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  62895. };
  62896. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62897. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  62898. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  62899. return Bone;
  62900. }(BABYLON.Node));
  62901. BABYLON.Bone = Bone;
  62902. })(BABYLON || (BABYLON = {}));
  62903. //# sourceMappingURL=babylon.bone.js.map
  62904. var BABYLON;
  62905. (function (BABYLON) {
  62906. var BoneIKController = /** @class */ (function () {
  62907. function BoneIKController(mesh, bone, options) {
  62908. this.targetPosition = BABYLON.Vector3.Zero();
  62909. this.poleTargetPosition = BABYLON.Vector3.Zero();
  62910. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  62911. this.poleAngle = 0;
  62912. this.slerpAmount = 1;
  62913. this._bone1Quat = BABYLON.Quaternion.Identity();
  62914. this._bone1Mat = BABYLON.Matrix.Identity();
  62915. this._bone2Ang = Math.PI;
  62916. this._maxAngle = Math.PI;
  62917. this._rightHandedSystem = false;
  62918. this._bendAxis = BABYLON.Vector3.Right();
  62919. this._slerping = false;
  62920. this._adjustRoll = 0;
  62921. this._bone2 = bone;
  62922. this._bone1 = bone.getParent();
  62923. if (!this._bone1) {
  62924. return;
  62925. }
  62926. this.mesh = mesh;
  62927. var bonePos = bone.getPosition();
  62928. if (bone.getAbsoluteTransform().determinant() > 0) {
  62929. this._rightHandedSystem = true;
  62930. this._bendAxis.x = 0;
  62931. this._bendAxis.y = 0;
  62932. this._bendAxis.z = -1;
  62933. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  62934. this._adjustRoll = Math.PI * .5;
  62935. this._bendAxis.z = 1;
  62936. }
  62937. }
  62938. if (this._bone1.length) {
  62939. var boneScale1 = this._bone1.getScale();
  62940. var boneScale2 = this._bone2.getScale();
  62941. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  62942. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  62943. }
  62944. else if (this._bone1.children[0]) {
  62945. mesh.computeWorldMatrix(true);
  62946. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  62947. var pos2 = this._bone2.getAbsolutePosition(mesh);
  62948. var pos3 = this._bone1.getAbsolutePosition(mesh);
  62949. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  62950. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  62951. }
  62952. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  62953. this.maxAngle = Math.PI;
  62954. if (options) {
  62955. if (options.targetMesh) {
  62956. this.targetMesh = options.targetMesh;
  62957. this.targetMesh.computeWorldMatrix(true);
  62958. }
  62959. if (options.poleTargetMesh) {
  62960. this.poleTargetMesh = options.poleTargetMesh;
  62961. this.poleTargetMesh.computeWorldMatrix(true);
  62962. }
  62963. else if (options.poleTargetBone) {
  62964. this.poleTargetBone = options.poleTargetBone;
  62965. }
  62966. else if (this._bone1.getParent()) {
  62967. this.poleTargetBone = this._bone1.getParent();
  62968. }
  62969. if (options.poleTargetLocalOffset) {
  62970. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  62971. }
  62972. if (options.poleAngle) {
  62973. this.poleAngle = options.poleAngle;
  62974. }
  62975. if (options.bendAxis) {
  62976. this._bendAxis.copyFrom(options.bendAxis);
  62977. }
  62978. if (options.maxAngle) {
  62979. this.maxAngle = options.maxAngle;
  62980. }
  62981. if (options.slerpAmount) {
  62982. this.slerpAmount = options.slerpAmount;
  62983. }
  62984. }
  62985. }
  62986. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  62987. get: function () {
  62988. return this._maxAngle;
  62989. },
  62990. set: function (value) {
  62991. this._setMaxAngle(value);
  62992. },
  62993. enumerable: true,
  62994. configurable: true
  62995. });
  62996. BoneIKController.prototype._setMaxAngle = function (ang) {
  62997. if (ang < 0) {
  62998. ang = 0;
  62999. }
  63000. if (ang > Math.PI || ang == undefined) {
  63001. ang = Math.PI;
  63002. }
  63003. this._maxAngle = ang;
  63004. var a = this._bone1Length;
  63005. var b = this._bone2Length;
  63006. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  63007. };
  63008. BoneIKController.prototype.update = function () {
  63009. var bone1 = this._bone1;
  63010. if (!bone1) {
  63011. return;
  63012. }
  63013. var target = this.targetPosition;
  63014. var poleTarget = this.poleTargetPosition;
  63015. var mat1 = BoneIKController._tmpMats[0];
  63016. var mat2 = BoneIKController._tmpMats[1];
  63017. if (this.targetMesh) {
  63018. target.copyFrom(this.targetMesh.getAbsolutePosition());
  63019. }
  63020. if (this.poleTargetBone) {
  63021. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  63022. }
  63023. else if (this.poleTargetMesh) {
  63024. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  63025. }
  63026. var bonePos = BoneIKController._tmpVecs[0];
  63027. var zaxis = BoneIKController._tmpVecs[1];
  63028. var xaxis = BoneIKController._tmpVecs[2];
  63029. var yaxis = BoneIKController._tmpVecs[3];
  63030. var upAxis = BoneIKController._tmpVecs[4];
  63031. var _tmpQuat = BoneIKController._tmpQuat;
  63032. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  63033. poleTarget.subtractToRef(bonePos, upAxis);
  63034. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  63035. upAxis.y = 1;
  63036. }
  63037. else {
  63038. upAxis.normalize();
  63039. }
  63040. target.subtractToRef(bonePos, yaxis);
  63041. yaxis.normalize();
  63042. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  63043. zaxis.normalize();
  63044. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  63045. xaxis.normalize();
  63046. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  63047. var a = this._bone1Length;
  63048. var b = this._bone2Length;
  63049. var c = BABYLON.Vector3.Distance(bonePos, target);
  63050. if (this._maxReach > 0) {
  63051. c = Math.min(this._maxReach, c);
  63052. }
  63053. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  63054. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  63055. if (acosa > 1) {
  63056. acosa = 1;
  63057. }
  63058. if (acosb > 1) {
  63059. acosb = 1;
  63060. }
  63061. if (acosa < -1) {
  63062. acosa = -1;
  63063. }
  63064. if (acosb < -1) {
  63065. acosb = -1;
  63066. }
  63067. var angA = Math.acos(acosa);
  63068. var angB = Math.acos(acosb);
  63069. var angC = -angA - angB;
  63070. if (this._rightHandedSystem) {
  63071. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  63072. mat2.multiplyToRef(mat1, mat1);
  63073. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  63074. mat2.multiplyToRef(mat1, mat1);
  63075. }
  63076. else {
  63077. var _tmpVec = BoneIKController._tmpVecs[5];
  63078. _tmpVec.copyFrom(this._bendAxis);
  63079. _tmpVec.x *= -1;
  63080. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  63081. mat2.multiplyToRef(mat1, mat1);
  63082. }
  63083. if (this.poleAngle) {
  63084. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  63085. mat1.multiplyToRef(mat2, mat1);
  63086. }
  63087. if (this._bone1) {
  63088. if (this.slerpAmount < 1) {
  63089. if (!this._slerping) {
  63090. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  63091. }
  63092. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  63093. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  63094. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  63095. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  63096. this._slerping = true;
  63097. }
  63098. else {
  63099. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  63100. this._bone1Mat.copyFrom(mat1);
  63101. this._slerping = false;
  63102. }
  63103. }
  63104. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  63105. this._bone2Ang = angC;
  63106. };
  63107. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63108. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  63109. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  63110. return BoneIKController;
  63111. }());
  63112. BABYLON.BoneIKController = BoneIKController;
  63113. })(BABYLON || (BABYLON = {}));
  63114. //# sourceMappingURL=babylon.boneIKController.js.map
  63115. var BABYLON;
  63116. (function (BABYLON) {
  63117. var BoneLookController = /** @class */ (function () {
  63118. /**
  63119. * Create a BoneLookController
  63120. * @param mesh the mesh that the bone belongs to
  63121. * @param bone the bone that will be looking to the target
  63122. * @param target the target Vector3 to look at
  63123. * @param settings optional settings:
  63124. * - maxYaw: the maximum angle the bone will yaw to
  63125. * - minYaw: the minimum angle the bone will yaw to
  63126. * - maxPitch: the maximum angle the bone will pitch to
  63127. * - minPitch: the minimum angle the bone will yaw to
  63128. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  63129. * - upAxis: the up axis of the coordinate system
  63130. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  63131. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  63132. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  63133. * - adjustYaw: used to make an adjustment to the yaw of the bone
  63134. * - adjustPitch: used to make an adjustment to the pitch of the bone
  63135. * - adjustRoll: used to make an adjustment to the roll of the bone
  63136. **/
  63137. function BoneLookController(mesh, bone, target, options) {
  63138. /**
  63139. * The up axis of the coordinate system that is used when the bone is rotated.
  63140. */
  63141. this.upAxis = BABYLON.Vector3.Up();
  63142. /**
  63143. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  63144. */
  63145. this.upAxisSpace = BABYLON.Space.LOCAL;
  63146. /**
  63147. * Used to make an adjustment to the yaw of the bone.
  63148. */
  63149. this.adjustYaw = 0;
  63150. /**
  63151. * Used to make an adjustment to the pitch of the bone.
  63152. */
  63153. this.adjustPitch = 0;
  63154. /**
  63155. * Used to make an adjustment to the roll of the bone.
  63156. */
  63157. this.adjustRoll = 0;
  63158. /**
  63159. * 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).
  63160. */
  63161. this.slerpAmount = 1;
  63162. this._boneQuat = BABYLON.Quaternion.Identity();
  63163. this._slerping = false;
  63164. this._firstFrameSkipped = false;
  63165. this._fowardAxis = BABYLON.Vector3.Forward();
  63166. this.mesh = mesh;
  63167. this.bone = bone;
  63168. this.target = target;
  63169. if (options) {
  63170. if (options.adjustYaw) {
  63171. this.adjustYaw = options.adjustYaw;
  63172. }
  63173. if (options.adjustPitch) {
  63174. this.adjustPitch = options.adjustPitch;
  63175. }
  63176. if (options.adjustRoll) {
  63177. this.adjustRoll = options.adjustRoll;
  63178. }
  63179. if (options.maxYaw != null) {
  63180. this.maxYaw = options.maxYaw;
  63181. }
  63182. else {
  63183. this.maxYaw = Math.PI;
  63184. }
  63185. if (options.minYaw != null) {
  63186. this.minYaw = options.minYaw;
  63187. }
  63188. else {
  63189. this.minYaw = -Math.PI;
  63190. }
  63191. if (options.maxPitch != null) {
  63192. this.maxPitch = options.maxPitch;
  63193. }
  63194. else {
  63195. this.maxPitch = Math.PI;
  63196. }
  63197. if (options.minPitch != null) {
  63198. this.minPitch = options.minPitch;
  63199. }
  63200. else {
  63201. this.minPitch = -Math.PI;
  63202. }
  63203. if (options.slerpAmount != null) {
  63204. this.slerpAmount = options.slerpAmount;
  63205. }
  63206. if (options.upAxis != null) {
  63207. this.upAxis = options.upAxis;
  63208. }
  63209. if (options.upAxisSpace != null) {
  63210. this.upAxisSpace = options.upAxisSpace;
  63211. }
  63212. if (options.yawAxis != null || options.pitchAxis != null) {
  63213. var newYawAxis = BABYLON.Axis.Y;
  63214. var newPitchAxis = BABYLON.Axis.X;
  63215. if (options.yawAxis != null) {
  63216. newYawAxis = options.yawAxis.clone();
  63217. newYawAxis.normalize();
  63218. }
  63219. if (options.pitchAxis != null) {
  63220. newPitchAxis = options.pitchAxis.clone();
  63221. newPitchAxis.normalize();
  63222. }
  63223. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  63224. this._transformYawPitch = BABYLON.Matrix.Identity();
  63225. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  63226. this._transformYawPitchInv = this._transformYawPitch.clone();
  63227. this._transformYawPitch.invert();
  63228. }
  63229. }
  63230. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  63231. this.upAxisSpace = BABYLON.Space.LOCAL;
  63232. }
  63233. }
  63234. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  63235. /**
  63236. * Get/set the minimum yaw angle that the bone can look to.
  63237. */
  63238. get: function () {
  63239. return this._minYaw;
  63240. },
  63241. set: function (value) {
  63242. this._minYaw = value;
  63243. this._minYawSin = Math.sin(value);
  63244. this._minYawCos = Math.cos(value);
  63245. if (this._maxYaw != null) {
  63246. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  63247. this._yawRange = this._maxYaw - this._minYaw;
  63248. }
  63249. },
  63250. enumerable: true,
  63251. configurable: true
  63252. });
  63253. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  63254. /**
  63255. * Get/set the maximum yaw angle that the bone can look to.
  63256. */
  63257. get: function () {
  63258. return this._maxYaw;
  63259. },
  63260. set: function (value) {
  63261. this._maxYaw = value;
  63262. this._maxYawSin = Math.sin(value);
  63263. this._maxYawCos = Math.cos(value);
  63264. if (this._minYaw != null) {
  63265. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  63266. this._yawRange = this._maxYaw - this._minYaw;
  63267. }
  63268. },
  63269. enumerable: true,
  63270. configurable: true
  63271. });
  63272. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  63273. /**
  63274. * Get/set the minimum pitch angle that the bone can look to.
  63275. */
  63276. get: function () {
  63277. return this._minPitch;
  63278. },
  63279. set: function (value) {
  63280. this._minPitch = value;
  63281. this._minPitchTan = Math.tan(value);
  63282. },
  63283. enumerable: true,
  63284. configurable: true
  63285. });
  63286. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  63287. /**
  63288. * Get/set the maximum pitch angle that the bone can look to.
  63289. */
  63290. get: function () {
  63291. return this._maxPitch;
  63292. },
  63293. set: function (value) {
  63294. this._maxPitch = value;
  63295. this._maxPitchTan = Math.tan(value);
  63296. },
  63297. enumerable: true,
  63298. configurable: true
  63299. });
  63300. /**
  63301. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  63302. */
  63303. BoneLookController.prototype.update = function () {
  63304. //skip the first frame when slerping so that the mesh rotation is correct
  63305. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  63306. this._firstFrameSkipped = true;
  63307. return;
  63308. }
  63309. var bone = this.bone;
  63310. var bonePos = BoneLookController._tmpVecs[0];
  63311. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  63312. var target = this.target;
  63313. var _tmpMat1 = BoneLookController._tmpMats[0];
  63314. var _tmpMat2 = BoneLookController._tmpMats[1];
  63315. var mesh = this.mesh;
  63316. var parentBone = bone.getParent();
  63317. var upAxis = BoneLookController._tmpVecs[1];
  63318. upAxis.copyFrom(this.upAxis);
  63319. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  63320. if (this._transformYawPitch) {
  63321. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  63322. }
  63323. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  63324. }
  63325. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  63326. mesh.getDirectionToRef(upAxis, upAxis);
  63327. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  63328. upAxis.normalize();
  63329. }
  63330. }
  63331. var checkYaw = false;
  63332. var checkPitch = false;
  63333. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  63334. checkYaw = true;
  63335. }
  63336. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  63337. checkPitch = true;
  63338. }
  63339. if (checkYaw || checkPitch) {
  63340. var spaceMat = BoneLookController._tmpMats[2];
  63341. var spaceMatInv = BoneLookController._tmpMats[3];
  63342. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  63343. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  63344. }
  63345. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  63346. spaceMat.copyFrom(mesh.getWorldMatrix());
  63347. }
  63348. else {
  63349. var forwardAxis = BoneLookController._tmpVecs[2];
  63350. forwardAxis.copyFrom(this._fowardAxis);
  63351. if (this._transformYawPitch) {
  63352. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  63353. }
  63354. if (parentBone) {
  63355. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  63356. }
  63357. else {
  63358. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  63359. }
  63360. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  63361. rightAxis.normalize();
  63362. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  63363. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  63364. }
  63365. spaceMat.invertToRef(spaceMatInv);
  63366. var xzlen = null;
  63367. if (checkPitch) {
  63368. var localTarget = BoneLookController._tmpVecs[3];
  63369. target.subtractToRef(bonePos, localTarget);
  63370. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  63371. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  63372. var pitch = Math.atan2(localTarget.y, xzlen);
  63373. var newPitch = pitch;
  63374. if (pitch > this._maxPitch) {
  63375. localTarget.y = this._maxPitchTan * xzlen;
  63376. newPitch = this._maxPitch;
  63377. }
  63378. else if (pitch < this._minPitch) {
  63379. localTarget.y = this._minPitchTan * xzlen;
  63380. newPitch = this._minPitch;
  63381. }
  63382. if (pitch != newPitch) {
  63383. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  63384. localTarget.addInPlace(bonePos);
  63385. target = localTarget;
  63386. }
  63387. }
  63388. if (checkYaw) {
  63389. var localTarget = BoneLookController._tmpVecs[4];
  63390. target.subtractToRef(bonePos, localTarget);
  63391. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  63392. var yaw = Math.atan2(localTarget.x, localTarget.z);
  63393. var newYaw = yaw;
  63394. if (yaw > this._maxYaw || yaw < this._minYaw) {
  63395. if (xzlen == null) {
  63396. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  63397. }
  63398. if (this._yawRange > Math.PI) {
  63399. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  63400. localTarget.z = this._maxYawCos * xzlen;
  63401. localTarget.x = this._maxYawSin * xzlen;
  63402. newYaw = this._maxYaw;
  63403. }
  63404. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  63405. localTarget.z = this._minYawCos * xzlen;
  63406. localTarget.x = this._minYawSin * xzlen;
  63407. newYaw = this._minYaw;
  63408. }
  63409. }
  63410. else {
  63411. if (yaw > this._maxYaw) {
  63412. localTarget.z = this._maxYawCos * xzlen;
  63413. localTarget.x = this._maxYawSin * xzlen;
  63414. newYaw = this._maxYaw;
  63415. }
  63416. else if (yaw < this._minYaw) {
  63417. localTarget.z = this._minYawCos * xzlen;
  63418. localTarget.x = this._minYawSin * xzlen;
  63419. newYaw = this._minYaw;
  63420. }
  63421. }
  63422. }
  63423. if (this._slerping && this._yawRange > Math.PI) {
  63424. //are we going to be crossing into the min/max region?
  63425. var boneFwd = BoneLookController._tmpVecs[8];
  63426. boneFwd.copyFrom(BABYLON.Axis.Z);
  63427. if (this._transformYawPitch) {
  63428. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  63429. }
  63430. var boneRotMat = BoneLookController._tmpMats[4];
  63431. this._boneQuat.toRotationMatrix(boneRotMat);
  63432. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  63433. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  63434. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  63435. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  63436. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  63437. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  63438. if (angBtwTar > angBtwMidYaw) {
  63439. if (xzlen == null) {
  63440. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  63441. }
  63442. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  63443. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  63444. if (angBtwMin < angBtwMax) {
  63445. newYaw = boneYaw + Math.PI * .75;
  63446. localTarget.z = Math.cos(newYaw) * xzlen;
  63447. localTarget.x = Math.sin(newYaw) * xzlen;
  63448. }
  63449. else {
  63450. newYaw = boneYaw - Math.PI * .75;
  63451. localTarget.z = Math.cos(newYaw) * xzlen;
  63452. localTarget.x = Math.sin(newYaw) * xzlen;
  63453. }
  63454. }
  63455. }
  63456. if (yaw != newYaw) {
  63457. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  63458. localTarget.addInPlace(bonePos);
  63459. target = localTarget;
  63460. }
  63461. }
  63462. }
  63463. var zaxis = BoneLookController._tmpVecs[5];
  63464. var xaxis = BoneLookController._tmpVecs[6];
  63465. var yaxis = BoneLookController._tmpVecs[7];
  63466. var _tmpQuat = BoneLookController._tmpQuat;
  63467. target.subtractToRef(bonePos, zaxis);
  63468. zaxis.normalize();
  63469. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  63470. xaxis.normalize();
  63471. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  63472. yaxis.normalize();
  63473. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  63474. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  63475. return;
  63476. }
  63477. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  63478. return;
  63479. }
  63480. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  63481. return;
  63482. }
  63483. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  63484. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  63485. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  63486. }
  63487. if (this.slerpAmount < 1) {
  63488. if (!this._slerping) {
  63489. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  63490. }
  63491. if (this._transformYawPitch) {
  63492. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  63493. }
  63494. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  63495. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  63496. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  63497. this._slerping = true;
  63498. }
  63499. else {
  63500. if (this._transformYawPitch) {
  63501. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  63502. }
  63503. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  63504. this._slerping = false;
  63505. }
  63506. };
  63507. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  63508. var angDiff = ang2 - ang1;
  63509. angDiff %= Math.PI * 2;
  63510. if (angDiff > Math.PI) {
  63511. angDiff -= Math.PI * 2;
  63512. }
  63513. else if (angDiff < -Math.PI) {
  63514. angDiff += Math.PI * 2;
  63515. }
  63516. return angDiff;
  63517. };
  63518. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  63519. ang1 %= (2 * Math.PI);
  63520. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  63521. ang2 %= (2 * Math.PI);
  63522. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  63523. var ab = 0;
  63524. if (ang1 < ang2) {
  63525. ab = ang2 - ang1;
  63526. }
  63527. else {
  63528. ab = ang1 - ang2;
  63529. }
  63530. if (ab > Math.PI) {
  63531. ab = Math.PI * 2 - ab;
  63532. }
  63533. return ab;
  63534. };
  63535. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  63536. ang %= (2 * Math.PI);
  63537. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  63538. ang1 %= (2 * Math.PI);
  63539. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  63540. ang2 %= (2 * Math.PI);
  63541. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  63542. if (ang1 < ang2) {
  63543. if (ang > ang1 && ang < ang2) {
  63544. return true;
  63545. }
  63546. }
  63547. else {
  63548. if (ang > ang2 && ang < ang1) {
  63549. return true;
  63550. }
  63551. }
  63552. return false;
  63553. };
  63554. 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()];
  63555. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  63556. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  63557. return BoneLookController;
  63558. }());
  63559. BABYLON.BoneLookController = BoneLookController;
  63560. })(BABYLON || (BABYLON = {}));
  63561. //# sourceMappingURL=babylon.boneLookController.js.map
  63562. var BABYLON;
  63563. (function (BABYLON) {
  63564. var Skeleton = /** @class */ (function () {
  63565. function Skeleton(name, id, scene) {
  63566. this.name = name;
  63567. this.id = id;
  63568. this.bones = new Array();
  63569. this.needInitialSkinMatrix = false;
  63570. this._isDirty = true;
  63571. this._meshesWithPoseMatrix = new Array();
  63572. this._identity = BABYLON.Matrix.Identity();
  63573. this._ranges = {};
  63574. this._lastAbsoluteTransformsUpdateId = -1;
  63575. // Events
  63576. /**
  63577. * An event triggered before computing the skeleton's matrices
  63578. * @type {BABYLON.Observable}
  63579. */
  63580. this.onBeforeComputeObservable = new BABYLON.Observable();
  63581. this.bones = [];
  63582. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  63583. scene.skeletons.push(this);
  63584. //make sure it will recalculate the matrix next time prepare is called.
  63585. this._isDirty = true;
  63586. }
  63587. // Members
  63588. Skeleton.prototype.getTransformMatrices = function (mesh) {
  63589. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  63590. return mesh._bonesTransformMatrices;
  63591. }
  63592. if (!this._transformMatrices) {
  63593. this.prepare();
  63594. }
  63595. return this._transformMatrices;
  63596. };
  63597. Skeleton.prototype.getScene = function () {
  63598. return this._scene;
  63599. };
  63600. // Methods
  63601. /**
  63602. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  63603. */
  63604. Skeleton.prototype.toString = function (fullDetails) {
  63605. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  63606. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  63607. if (fullDetails) {
  63608. ret += ", Ranges: {";
  63609. var first = true;
  63610. for (var name_1 in this._ranges) {
  63611. if (first) {
  63612. ret += ", ";
  63613. first = false;
  63614. }
  63615. ret += name_1;
  63616. }
  63617. ret += "}";
  63618. }
  63619. return ret;
  63620. };
  63621. /**
  63622. * Get bone's index searching by name
  63623. * @param {string} name is bone's name to search for
  63624. * @return {number} Indice of the bone. Returns -1 if not found
  63625. */
  63626. Skeleton.prototype.getBoneIndexByName = function (name) {
  63627. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  63628. if (this.bones[boneIndex].name === name) {
  63629. return boneIndex;
  63630. }
  63631. }
  63632. return -1;
  63633. };
  63634. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  63635. // check name not already in use
  63636. if (!this._ranges[name]) {
  63637. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  63638. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  63639. if (this.bones[i].animations[0]) {
  63640. this.bones[i].animations[0].createRange(name, from, to);
  63641. }
  63642. }
  63643. }
  63644. };
  63645. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  63646. if (deleteFrames === void 0) { deleteFrames = true; }
  63647. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  63648. if (this.bones[i].animations[0]) {
  63649. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  63650. }
  63651. }
  63652. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  63653. };
  63654. Skeleton.prototype.getAnimationRange = function (name) {
  63655. return this._ranges[name];
  63656. };
  63657. /**
  63658. * Returns as an Array, all AnimationRanges defined on this skeleton
  63659. */
  63660. Skeleton.prototype.getAnimationRanges = function () {
  63661. var animationRanges = [];
  63662. var name;
  63663. var i = 0;
  63664. for (name in this._ranges) {
  63665. animationRanges[i] = this._ranges[name];
  63666. i++;
  63667. }
  63668. return animationRanges;
  63669. };
  63670. /**
  63671. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  63672. */
  63673. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  63674. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  63675. if (this._ranges[name] || !source.getAnimationRange(name)) {
  63676. return false;
  63677. }
  63678. var ret = true;
  63679. var frameOffset = this._getHighestAnimationFrame() + 1;
  63680. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  63681. var boneDict = {};
  63682. var sourceBones = source.bones;
  63683. var nBones;
  63684. var i;
  63685. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  63686. boneDict[sourceBones[i].name] = sourceBones[i];
  63687. }
  63688. if (this.bones.length !== sourceBones.length) {
  63689. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  63690. ret = false;
  63691. }
  63692. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  63693. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  63694. var boneName = this.bones[i].name;
  63695. var sourceBone = boneDict[boneName];
  63696. if (sourceBone) {
  63697. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  63698. }
  63699. else {
  63700. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  63701. ret = false;
  63702. }
  63703. }
  63704. // do not call createAnimationRange(), since it also is done to bones, which was already done
  63705. var range = source.getAnimationRange(name);
  63706. if (range) {
  63707. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  63708. }
  63709. return ret;
  63710. };
  63711. Skeleton.prototype.returnToRest = function () {
  63712. for (var index = 0; index < this.bones.length; index++) {
  63713. this.bones[index].returnToRest();
  63714. }
  63715. };
  63716. Skeleton.prototype._getHighestAnimationFrame = function () {
  63717. var ret = 0;
  63718. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  63719. if (this.bones[i].animations[0]) {
  63720. var highest = this.bones[i].animations[0].getHighestFrame();
  63721. if (ret < highest) {
  63722. ret = highest;
  63723. }
  63724. }
  63725. }
  63726. return ret;
  63727. };
  63728. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  63729. var range = this.getAnimationRange(name);
  63730. if (!range) {
  63731. return null;
  63732. }
  63733. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  63734. };
  63735. Skeleton.prototype._markAsDirty = function () {
  63736. this._isDirty = true;
  63737. };
  63738. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  63739. this._meshesWithPoseMatrix.push(mesh);
  63740. };
  63741. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  63742. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  63743. if (index > -1) {
  63744. this._meshesWithPoseMatrix.splice(index, 1);
  63745. }
  63746. };
  63747. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  63748. this.onBeforeComputeObservable.notifyObservers(this);
  63749. for (var index = 0; index < this.bones.length; index++) {
  63750. var bone = this.bones[index];
  63751. var parentBone = bone.getParent();
  63752. if (parentBone) {
  63753. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  63754. }
  63755. else {
  63756. if (initialSkinMatrix) {
  63757. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  63758. }
  63759. else {
  63760. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  63761. }
  63762. }
  63763. if (bone._index !== -1) {
  63764. var mappedIndex = bone._index === null ? index : bone._index;
  63765. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  63766. }
  63767. }
  63768. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  63769. };
  63770. Skeleton.prototype.prepare = function () {
  63771. if (!this._isDirty) {
  63772. return;
  63773. }
  63774. if (this.needInitialSkinMatrix) {
  63775. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  63776. var mesh = this._meshesWithPoseMatrix[index];
  63777. var poseMatrix = mesh.getPoseMatrix();
  63778. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  63779. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  63780. }
  63781. if (this._synchronizedWithMesh !== mesh) {
  63782. this._synchronizedWithMesh = mesh;
  63783. // Prepare bones
  63784. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  63785. var bone = this.bones[boneIndex];
  63786. if (!bone.getParent()) {
  63787. var matrix = bone.getBaseMatrix();
  63788. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  63789. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  63790. }
  63791. }
  63792. }
  63793. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  63794. }
  63795. }
  63796. else {
  63797. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  63798. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  63799. }
  63800. this._computeTransformMatrices(this._transformMatrices, null);
  63801. }
  63802. this._isDirty = false;
  63803. this._scene._activeBones.addCount(this.bones.length, false);
  63804. };
  63805. Skeleton.prototype.getAnimatables = function () {
  63806. if (!this._animatables || this._animatables.length !== this.bones.length) {
  63807. this._animatables = [];
  63808. for (var index = 0; index < this.bones.length; index++) {
  63809. this._animatables.push(this.bones[index]);
  63810. }
  63811. }
  63812. return this._animatables;
  63813. };
  63814. Skeleton.prototype.clone = function (name, id) {
  63815. var result = new Skeleton(name, id || name, this._scene);
  63816. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  63817. for (var index = 0; index < this.bones.length; index++) {
  63818. var source = this.bones[index];
  63819. var parentBone = null;
  63820. var parent_1 = source.getParent();
  63821. if (parent_1) {
  63822. var parentIndex = this.bones.indexOf(parent_1);
  63823. parentBone = result.bones[parentIndex];
  63824. }
  63825. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  63826. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  63827. }
  63828. if (this._ranges) {
  63829. result._ranges = {};
  63830. for (var rangeName in this._ranges) {
  63831. var range = this._ranges[rangeName];
  63832. if (range) {
  63833. result._ranges[rangeName] = range.clone();
  63834. }
  63835. }
  63836. }
  63837. this._isDirty = true;
  63838. return result;
  63839. };
  63840. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  63841. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  63842. this.bones.forEach(function (bone) {
  63843. bone.animations.forEach(function (animation) {
  63844. animation.enableBlending = true;
  63845. animation.blendingSpeed = blendingSpeed;
  63846. });
  63847. });
  63848. };
  63849. Skeleton.prototype.dispose = function () {
  63850. this._meshesWithPoseMatrix = [];
  63851. // Animations
  63852. this.getScene().stopAnimation(this);
  63853. // Remove from scene
  63854. this.getScene().removeSkeleton(this);
  63855. };
  63856. Skeleton.prototype.serialize = function () {
  63857. var serializationObject = {};
  63858. serializationObject.name = this.name;
  63859. serializationObject.id = this.id;
  63860. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  63861. serializationObject.bones = [];
  63862. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  63863. for (var index = 0; index < this.bones.length; index++) {
  63864. var bone = this.bones[index];
  63865. var parent_2 = bone.getParent();
  63866. var serializedBone = {
  63867. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  63868. name: bone.name,
  63869. matrix: bone.getBaseMatrix().toArray(),
  63870. rest: bone.getRestPose().toArray()
  63871. };
  63872. serializationObject.bones.push(serializedBone);
  63873. if (bone.length) {
  63874. serializedBone.length = bone.length;
  63875. }
  63876. if (bone.animations && bone.animations.length > 0) {
  63877. serializedBone.animation = bone.animations[0].serialize();
  63878. }
  63879. serializationObject.ranges = [];
  63880. for (var name in this._ranges) {
  63881. var source = this._ranges[name];
  63882. if (!source) {
  63883. continue;
  63884. }
  63885. var range = {};
  63886. range.name = name;
  63887. range.from = source.from;
  63888. range.to = source.to;
  63889. serializationObject.ranges.push(range);
  63890. }
  63891. }
  63892. return serializationObject;
  63893. };
  63894. Skeleton.Parse = function (parsedSkeleton, scene) {
  63895. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  63896. if (parsedSkeleton.dimensionsAtRest) {
  63897. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  63898. }
  63899. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  63900. var index;
  63901. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  63902. var parsedBone = parsedSkeleton.bones[index];
  63903. var parentBone = null;
  63904. if (parsedBone.parentBoneIndex > -1) {
  63905. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  63906. }
  63907. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  63908. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  63909. if (parsedBone.length) {
  63910. bone.length = parsedBone.length;
  63911. }
  63912. if (parsedBone.animation) {
  63913. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  63914. }
  63915. }
  63916. // placed after bones, so createAnimationRange can cascade down
  63917. if (parsedSkeleton.ranges) {
  63918. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  63919. var data = parsedSkeleton.ranges[index];
  63920. skeleton.createAnimationRange(data.name, data.from, data.to);
  63921. }
  63922. }
  63923. return skeleton;
  63924. };
  63925. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  63926. if (forceUpdate === void 0) { forceUpdate = false; }
  63927. var renderId = this._scene.getRenderId();
  63928. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  63929. this.bones[0].computeAbsoluteTransforms();
  63930. this._lastAbsoluteTransformsUpdateId = renderId;
  63931. }
  63932. };
  63933. Skeleton.prototype.getPoseMatrix = function () {
  63934. var poseMatrix = null;
  63935. if (this._meshesWithPoseMatrix.length > 0) {
  63936. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  63937. }
  63938. return poseMatrix;
  63939. };
  63940. Skeleton.prototype.sortBones = function () {
  63941. var bones = new Array();
  63942. var visited = new Array(this.bones.length);
  63943. for (var index = 0; index < this.bones.length; index++) {
  63944. this._sortBones(index, bones, visited);
  63945. }
  63946. this.bones = bones;
  63947. };
  63948. Skeleton.prototype._sortBones = function (index, bones, visited) {
  63949. if (visited[index]) {
  63950. return;
  63951. }
  63952. visited[index] = true;
  63953. var bone = this.bones[index];
  63954. if (bone._index === undefined) {
  63955. bone._index = index;
  63956. }
  63957. var parentBone = bone.getParent();
  63958. if (parentBone) {
  63959. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  63960. }
  63961. bones.push(bone);
  63962. };
  63963. return Skeleton;
  63964. }());
  63965. BABYLON.Skeleton = Skeleton;
  63966. })(BABYLON || (BABYLON = {}));
  63967. //# sourceMappingURL=babylon.skeleton.js.map
  63968. var BABYLON;
  63969. (function (BABYLON) {
  63970. var SphericalPolynomial = /** @class */ (function () {
  63971. function SphericalPolynomial() {
  63972. this.x = BABYLON.Vector3.Zero();
  63973. this.y = BABYLON.Vector3.Zero();
  63974. this.z = BABYLON.Vector3.Zero();
  63975. this.xx = BABYLON.Vector3.Zero();
  63976. this.yy = BABYLON.Vector3.Zero();
  63977. this.zz = BABYLON.Vector3.Zero();
  63978. this.xy = BABYLON.Vector3.Zero();
  63979. this.yz = BABYLON.Vector3.Zero();
  63980. this.zx = BABYLON.Vector3.Zero();
  63981. }
  63982. SphericalPolynomial.prototype.addAmbient = function (color) {
  63983. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  63984. this.xx = this.xx.add(colorVector);
  63985. this.yy = this.yy.add(colorVector);
  63986. this.zz = this.zz.add(colorVector);
  63987. };
  63988. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  63989. var result = new SphericalPolynomial();
  63990. result.x = harmonics.L11.scale(1.02333);
  63991. result.y = harmonics.L1_1.scale(1.02333);
  63992. result.z = harmonics.L10.scale(1.02333);
  63993. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  63994. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  63995. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  63996. result.yz = harmonics.L2_1.scale(0.858086);
  63997. result.zx = harmonics.L21.scale(0.858086);
  63998. result.xy = harmonics.L2_2.scale(0.858086);
  63999. result.scale(1.0 / Math.PI);
  64000. return result;
  64001. };
  64002. SphericalPolynomial.prototype.scale = function (scale) {
  64003. this.x = this.x.scale(scale);
  64004. this.y = this.y.scale(scale);
  64005. this.z = this.z.scale(scale);
  64006. this.xx = this.xx.scale(scale);
  64007. this.yy = this.yy.scale(scale);
  64008. this.zz = this.zz.scale(scale);
  64009. this.yz = this.yz.scale(scale);
  64010. this.zx = this.zx.scale(scale);
  64011. this.xy = this.xy.scale(scale);
  64012. };
  64013. return SphericalPolynomial;
  64014. }());
  64015. BABYLON.SphericalPolynomial = SphericalPolynomial;
  64016. var SphericalHarmonics = /** @class */ (function () {
  64017. function SphericalHarmonics() {
  64018. this.L00 = BABYLON.Vector3.Zero();
  64019. this.L1_1 = BABYLON.Vector3.Zero();
  64020. this.L10 = BABYLON.Vector3.Zero();
  64021. this.L11 = BABYLON.Vector3.Zero();
  64022. this.L2_2 = BABYLON.Vector3.Zero();
  64023. this.L2_1 = BABYLON.Vector3.Zero();
  64024. this.L20 = BABYLON.Vector3.Zero();
  64025. this.L21 = BABYLON.Vector3.Zero();
  64026. this.L22 = BABYLON.Vector3.Zero();
  64027. }
  64028. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  64029. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  64030. var c = colorVector.scale(deltaSolidAngle);
  64031. this.L00 = this.L00.add(c.scale(0.282095));
  64032. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  64033. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  64034. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  64035. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  64036. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  64037. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  64038. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  64039. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  64040. };
  64041. SphericalHarmonics.prototype.scale = function (scale) {
  64042. this.L00 = this.L00.scale(scale);
  64043. this.L1_1 = this.L1_1.scale(scale);
  64044. this.L10 = this.L10.scale(scale);
  64045. this.L11 = this.L11.scale(scale);
  64046. this.L2_2 = this.L2_2.scale(scale);
  64047. this.L2_1 = this.L2_1.scale(scale);
  64048. this.L20 = this.L20.scale(scale);
  64049. this.L21 = this.L21.scale(scale);
  64050. this.L22 = this.L22.scale(scale);
  64051. };
  64052. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  64053. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  64054. //
  64055. // E_lm = A_l * L_lm
  64056. //
  64057. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  64058. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  64059. // the scaling factors are given in equation 9.
  64060. // Constant (Band 0)
  64061. this.L00 = this.L00.scale(3.141593);
  64062. // Linear (Band 1)
  64063. this.L1_1 = this.L1_1.scale(2.094395);
  64064. this.L10 = this.L10.scale(2.094395);
  64065. this.L11 = this.L11.scale(2.094395);
  64066. // Quadratic (Band 2)
  64067. this.L2_2 = this.L2_2.scale(0.785398);
  64068. this.L2_1 = this.L2_1.scale(0.785398);
  64069. this.L20 = this.L20.scale(0.785398);
  64070. this.L21 = this.L21.scale(0.785398);
  64071. this.L22 = this.L22.scale(0.785398);
  64072. };
  64073. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  64074. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  64075. // L = (1/pi) * E * rho
  64076. //
  64077. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  64078. this.scale(1.0 / Math.PI);
  64079. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  64080. // (The pixel shader must apply albedo after texture fetches, etc).
  64081. };
  64082. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  64083. var result = new SphericalHarmonics();
  64084. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  64085. result.L1_1 = polynomial.y.scale(0.977204);
  64086. result.L10 = polynomial.z.scale(0.977204);
  64087. result.L11 = polynomial.x.scale(0.977204);
  64088. result.L2_2 = polynomial.xy.scale(1.16538);
  64089. result.L2_1 = polynomial.yz.scale(1.16538);
  64090. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  64091. result.L21 = polynomial.zx.scale(1.16538);
  64092. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  64093. result.scale(Math.PI);
  64094. return result;
  64095. };
  64096. return SphericalHarmonics;
  64097. }());
  64098. BABYLON.SphericalHarmonics = SphericalHarmonics;
  64099. })(BABYLON || (BABYLON = {}));
  64100. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  64101. var BABYLON;
  64102. (function (BABYLON) {
  64103. var Internals;
  64104. (function (Internals) {
  64105. var FileFaceOrientation = /** @class */ (function () {
  64106. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  64107. this.name = name;
  64108. this.worldAxisForNormal = worldAxisForNormal;
  64109. this.worldAxisForFileX = worldAxisForFileX;
  64110. this.worldAxisForFileY = worldAxisForFileY;
  64111. }
  64112. return FileFaceOrientation;
  64113. }());
  64114. ;
  64115. /**
  64116. * Helper class dealing with the extraction of spherical polynomial dataArray
  64117. * from a cube map.
  64118. */
  64119. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  64120. function CubeMapToSphericalPolynomialTools() {
  64121. }
  64122. /**
  64123. * Converts a texture to the according Spherical Polynomial data.
  64124. * This extracts the first 3 orders only as they are the only one used in the lighting.
  64125. *
  64126. * @param texture The texture to extract the information from.
  64127. * @return The Spherical Polynomial data.
  64128. */
  64129. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  64130. if (!texture.isCube) {
  64131. // Only supports cube Textures currently.
  64132. return null;
  64133. }
  64134. var size = texture.getSize().width;
  64135. var right = texture.readPixels(0);
  64136. var left = texture.readPixels(1);
  64137. var up;
  64138. var down;
  64139. if (texture.isRenderTarget) {
  64140. up = texture.readPixels(3);
  64141. down = texture.readPixels(2);
  64142. }
  64143. else {
  64144. up = texture.readPixels(2);
  64145. down = texture.readPixels(3);
  64146. }
  64147. var front = texture.readPixels(4);
  64148. var back = texture.readPixels(5);
  64149. var gammaSpace = texture.gammaSpace;
  64150. // Always read as RGBA.
  64151. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  64152. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  64153. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  64154. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  64155. }
  64156. var cubeInfo = {
  64157. size: size,
  64158. right: right,
  64159. left: left,
  64160. up: up,
  64161. down: down,
  64162. front: front,
  64163. back: back,
  64164. format: format,
  64165. type: type,
  64166. gammaSpace: gammaSpace,
  64167. };
  64168. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  64169. };
  64170. /**
  64171. * Converts a cubemap to the according Spherical Polynomial data.
  64172. * This extracts the first 3 orders only as they are the only one used in the lighting.
  64173. *
  64174. * @param cubeInfo The Cube map to extract the information from.
  64175. * @return The Spherical Polynomial data.
  64176. */
  64177. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  64178. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  64179. var totalSolidAngle = 0.0;
  64180. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  64181. var du = 2.0 / cubeInfo.size;
  64182. var dv = du;
  64183. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  64184. var minUV = du * 0.5 - 1.0;
  64185. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  64186. var fileFace = this.FileFaces[faceIndex];
  64187. var dataArray = cubeInfo[fileFace.name];
  64188. var v = minUV;
  64189. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  64190. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  64191. // Because SP is still linear, so summation is fine in that basis.
  64192. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  64193. for (var y = 0; y < cubeInfo.size; y++) {
  64194. var u = minUV;
  64195. for (var x = 0; x < cubeInfo.size; x++) {
  64196. // World direction (not normalised)
  64197. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  64198. worldDirection.normalize();
  64199. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  64200. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  64201. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  64202. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  64203. // Handle Integer types.
  64204. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  64205. r /= 255;
  64206. g /= 255;
  64207. b /= 255;
  64208. }
  64209. // Handle Gamma space textures.
  64210. if (cubeInfo.gammaSpace) {
  64211. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  64212. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  64213. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  64214. }
  64215. var color = new BABYLON.Color3(r, g, b);
  64216. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  64217. totalSolidAngle += deltaSolidAngle;
  64218. u += du;
  64219. }
  64220. v += dv;
  64221. }
  64222. }
  64223. // Solid angle for entire sphere is 4*pi
  64224. var sphereSolidAngle = 4.0 * Math.PI;
  64225. // Adjust the solid angle to allow for how many faces we processed.
  64226. var facesProcessed = 6.0;
  64227. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  64228. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  64229. // This is needed because the numerical integration over the cube uses a
  64230. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  64231. // and also to compensate for accumulative error due to float precision in the summation.
  64232. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  64233. sphericalHarmonics.scale(correctionFactor);
  64234. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  64235. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  64236. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  64237. };
  64238. CubeMapToSphericalPolynomialTools.FileFaces = [
  64239. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  64240. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  64241. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  64242. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  64243. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  64244. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  64245. ];
  64246. return CubeMapToSphericalPolynomialTools;
  64247. }());
  64248. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  64249. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  64250. })(BABYLON || (BABYLON = {}));
  64251. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  64252. var BABYLON;
  64253. (function (BABYLON) {
  64254. var Internals;
  64255. (function (Internals) {
  64256. /**
  64257. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  64258. */
  64259. var PanoramaToCubeMapTools = /** @class */ (function () {
  64260. function PanoramaToCubeMapTools() {
  64261. }
  64262. /**
  64263. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  64264. *
  64265. * @param float32Array The source data.
  64266. * @param inputWidth The width of the input panorama.
  64267. * @param inputhHeight The height of the input panorama.
  64268. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  64269. * @return The cubemap data
  64270. */
  64271. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  64272. if (!float32Array) {
  64273. throw "ConvertPanoramaToCubemap: input cannot be null";
  64274. }
  64275. if (float32Array.length != inputWidth * inputHeight * 3) {
  64276. throw "ConvertPanoramaToCubemap: input size is wrong";
  64277. }
  64278. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  64279. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  64280. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  64281. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  64282. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  64283. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  64284. return {
  64285. front: textureFront,
  64286. back: textureBack,
  64287. left: textureLeft,
  64288. right: textureRight,
  64289. up: textureUp,
  64290. down: textureDown,
  64291. size: size,
  64292. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  64293. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  64294. gammaSpace: false,
  64295. };
  64296. };
  64297. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  64298. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  64299. var textureArray = new Float32Array(buffer);
  64300. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  64301. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  64302. var dy = 1 / texSize;
  64303. var fy = 0;
  64304. for (var y = 0; y < texSize; y++) {
  64305. var xv1 = faceData[0];
  64306. var xv2 = faceData[2];
  64307. for (var x = 0; x < texSize; x++) {
  64308. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  64309. v.normalize();
  64310. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  64311. // 3 channels per pixels
  64312. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  64313. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  64314. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  64315. xv1 = xv1.add(rotDX1);
  64316. xv2 = xv2.add(rotDX2);
  64317. }
  64318. fy += dy;
  64319. }
  64320. return textureArray;
  64321. };
  64322. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  64323. var theta = Math.atan2(vDir.z, vDir.x);
  64324. var phi = Math.acos(vDir.y);
  64325. while (theta < -Math.PI)
  64326. theta += 2 * Math.PI;
  64327. while (theta > Math.PI)
  64328. theta -= 2 * Math.PI;
  64329. var dx = theta / Math.PI;
  64330. var dy = phi / Math.PI;
  64331. // recenter.
  64332. dx = dx * 0.5 + 0.5;
  64333. var px = Math.round(dx * inputWidth);
  64334. if (px < 0)
  64335. px = 0;
  64336. else if (px >= inputWidth)
  64337. px = inputWidth - 1;
  64338. var py = Math.round(dy * inputHeight);
  64339. if (py < 0)
  64340. py = 0;
  64341. else if (py >= inputHeight)
  64342. py = inputHeight - 1;
  64343. var inputY = (inputHeight - py - 1);
  64344. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  64345. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  64346. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  64347. return {
  64348. r: r,
  64349. g: g,
  64350. b: b
  64351. };
  64352. };
  64353. PanoramaToCubeMapTools.FACE_FRONT = [
  64354. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  64355. new BABYLON.Vector3(1.0, -1.0, -1.0),
  64356. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  64357. new BABYLON.Vector3(1.0, 1.0, -1.0)
  64358. ];
  64359. PanoramaToCubeMapTools.FACE_BACK = [
  64360. new BABYLON.Vector3(1.0, -1.0, 1.0),
  64361. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  64362. new BABYLON.Vector3(1.0, 1.0, 1.0),
  64363. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  64364. ];
  64365. PanoramaToCubeMapTools.FACE_RIGHT = [
  64366. new BABYLON.Vector3(1.0, -1.0, -1.0),
  64367. new BABYLON.Vector3(1.0, -1.0, 1.0),
  64368. new BABYLON.Vector3(1.0, 1.0, -1.0),
  64369. new BABYLON.Vector3(1.0, 1.0, 1.0)
  64370. ];
  64371. PanoramaToCubeMapTools.FACE_LEFT = [
  64372. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  64373. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  64374. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  64375. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  64376. ];
  64377. PanoramaToCubeMapTools.FACE_DOWN = [
  64378. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  64379. new BABYLON.Vector3(1.0, 1.0, -1.0),
  64380. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  64381. new BABYLON.Vector3(1.0, 1.0, 1.0)
  64382. ];
  64383. PanoramaToCubeMapTools.FACE_UP = [
  64384. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  64385. new BABYLON.Vector3(1.0, -1.0, 1.0),
  64386. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  64387. new BABYLON.Vector3(1.0, -1.0, -1.0)
  64388. ];
  64389. return PanoramaToCubeMapTools;
  64390. }());
  64391. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  64392. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  64393. })(BABYLON || (BABYLON = {}));
  64394. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  64395. var BABYLON;
  64396. (function (BABYLON) {
  64397. var Internals;
  64398. (function (Internals) {
  64399. ;
  64400. /**
  64401. * This groups tools to convert HDR texture to native colors array.
  64402. */
  64403. var HDRTools = /** @class */ (function () {
  64404. function HDRTools() {
  64405. }
  64406. HDRTools.Ldexp = function (mantissa, exponent) {
  64407. if (exponent > 1023) {
  64408. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  64409. }
  64410. if (exponent < -1074) {
  64411. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  64412. }
  64413. return mantissa * Math.pow(2, exponent);
  64414. };
  64415. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  64416. if (exponent > 0) {
  64417. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  64418. float32array[index + 0] = red * exponent;
  64419. float32array[index + 1] = green * exponent;
  64420. float32array[index + 2] = blue * exponent;
  64421. }
  64422. else {
  64423. float32array[index + 0] = 0;
  64424. float32array[index + 1] = 0;
  64425. float32array[index + 2] = 0;
  64426. }
  64427. };
  64428. HDRTools.readStringLine = function (uint8array, startIndex) {
  64429. var line = "";
  64430. var character = "";
  64431. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  64432. character = String.fromCharCode(uint8array[i]);
  64433. if (character == "\n") {
  64434. break;
  64435. }
  64436. line += character;
  64437. }
  64438. return line;
  64439. };
  64440. /**
  64441. * Reads header information from an RGBE texture stored in a native array.
  64442. * More information on this format are available here:
  64443. * https://en.wikipedia.org/wiki/RGBE_image_format
  64444. *
  64445. * @param uint8array The binary file stored in native array.
  64446. * @return The header information.
  64447. */
  64448. HDRTools.RGBE_ReadHeader = function (uint8array) {
  64449. var height = 0;
  64450. var width = 0;
  64451. var line = this.readStringLine(uint8array, 0);
  64452. if (line[0] != '#' || line[1] != '?') {
  64453. throw "Bad HDR Format.";
  64454. }
  64455. var endOfHeader = false;
  64456. var findFormat = false;
  64457. var lineIndex = 0;
  64458. do {
  64459. lineIndex += (line.length + 1);
  64460. line = this.readStringLine(uint8array, lineIndex);
  64461. if (line == "FORMAT=32-bit_rle_rgbe") {
  64462. findFormat = true;
  64463. }
  64464. else if (line.length == 0) {
  64465. endOfHeader = true;
  64466. }
  64467. } while (!endOfHeader);
  64468. if (!findFormat) {
  64469. throw "HDR Bad header format, unsupported FORMAT";
  64470. }
  64471. lineIndex += (line.length + 1);
  64472. line = this.readStringLine(uint8array, lineIndex);
  64473. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  64474. var match = sizeRegexp.exec(line);
  64475. // TODO. Support +Y and -X if needed.
  64476. if (!match || match.length < 3) {
  64477. throw "HDR Bad header format, no size";
  64478. }
  64479. width = parseInt(match[2]);
  64480. height = parseInt(match[1]);
  64481. if (width < 8 || width > 0x7fff) {
  64482. throw "HDR Bad header format, unsupported size";
  64483. }
  64484. lineIndex += (line.length + 1);
  64485. return {
  64486. height: height,
  64487. width: width,
  64488. dataPosition: lineIndex
  64489. };
  64490. };
  64491. /**
  64492. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  64493. * This RGBE texture needs to store the information as a panorama.
  64494. *
  64495. * More information on this format are available here:
  64496. * https://en.wikipedia.org/wiki/RGBE_image_format
  64497. *
  64498. * @param buffer The binary file stored in an array buffer.
  64499. * @param size The expected size of the extracted cubemap.
  64500. * @return The Cube Map information.
  64501. */
  64502. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  64503. var uint8array = new Uint8Array(buffer);
  64504. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  64505. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  64506. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  64507. return cubeMapData;
  64508. };
  64509. /**
  64510. * Returns the pixels data extracted from an RGBE texture.
  64511. * This pixels will be stored left to right up to down in the R G B order in one array.
  64512. *
  64513. * More information on this format are available here:
  64514. * https://en.wikipedia.org/wiki/RGBE_image_format
  64515. *
  64516. * @param uint8array The binary file stored in an array buffer.
  64517. * @param hdrInfo The header information of the file.
  64518. * @return The pixels data in RGB right to left up to down order.
  64519. */
  64520. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  64521. // Keep for multi format supports.
  64522. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  64523. };
  64524. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  64525. var num_scanlines = hdrInfo.height;
  64526. var scanline_width = hdrInfo.width;
  64527. var a, b, c, d, count;
  64528. var dataIndex = hdrInfo.dataPosition;
  64529. var index = 0, endIndex = 0, i = 0;
  64530. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  64531. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  64532. // 3 channels of 4 bytes per pixel in float.
  64533. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  64534. var resultArray = new Float32Array(resultBuffer);
  64535. // read in each successive scanline
  64536. while (num_scanlines > 0) {
  64537. a = uint8array[dataIndex++];
  64538. b = uint8array[dataIndex++];
  64539. c = uint8array[dataIndex++];
  64540. d = uint8array[dataIndex++];
  64541. if (a != 2 || b != 2 || (c & 0x80)) {
  64542. // this file is not run length encoded
  64543. throw "HDR Bad header format, not RLE";
  64544. }
  64545. if (((c << 8) | d) != scanline_width) {
  64546. throw "HDR Bad header format, wrong scan line width";
  64547. }
  64548. index = 0;
  64549. // read each of the four channels for the scanline into the buffer
  64550. for (i = 0; i < 4; i++) {
  64551. endIndex = (i + 1) * scanline_width;
  64552. while (index < endIndex) {
  64553. a = uint8array[dataIndex++];
  64554. b = uint8array[dataIndex++];
  64555. if (a > 128) {
  64556. // a run of the same value
  64557. count = a - 128;
  64558. if ((count == 0) || (count > endIndex - index)) {
  64559. throw "HDR Bad Format, bad scanline data (run)";
  64560. }
  64561. while (count-- > 0) {
  64562. scanLineArray[index++] = b;
  64563. }
  64564. }
  64565. else {
  64566. // a non-run
  64567. count = a;
  64568. if ((count == 0) || (count > endIndex - index)) {
  64569. throw "HDR Bad Format, bad scanline data (non-run)";
  64570. }
  64571. scanLineArray[index++] = b;
  64572. if (--count > 0) {
  64573. for (var j = 0; j < count; j++) {
  64574. scanLineArray[index++] = uint8array[dataIndex++];
  64575. }
  64576. }
  64577. }
  64578. }
  64579. }
  64580. // now convert data from buffer into floats
  64581. for (i = 0; i < scanline_width; i++) {
  64582. a = scanLineArray[i];
  64583. b = scanLineArray[i + scanline_width];
  64584. c = scanLineArray[i + 2 * scanline_width];
  64585. d = scanLineArray[i + 3 * scanline_width];
  64586. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  64587. }
  64588. num_scanlines--;
  64589. }
  64590. return resultArray;
  64591. };
  64592. return HDRTools;
  64593. }());
  64594. Internals.HDRTools = HDRTools;
  64595. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  64596. })(BABYLON || (BABYLON = {}));
  64597. //# sourceMappingURL=babylon.hdr.js.map
  64598. var BABYLON;
  64599. (function (BABYLON) {
  64600. /**
  64601. * This represents a texture coming from an HDR input.
  64602. *
  64603. * The only supported format is currently panorama picture stored in RGBE format.
  64604. * Example of such files can be found on HDRLib: http://hdrlib.com/
  64605. */
  64606. var HDRCubeTexture = /** @class */ (function (_super) {
  64607. __extends(HDRCubeTexture, _super);
  64608. /**
  64609. * Instantiates an HDRTexture from the following parameters.
  64610. *
  64611. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  64612. * @param scene The scene the texture will be used in
  64613. * @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.
  64614. * @param noMipmap Forces to not generate the mipmap if true
  64615. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  64616. * @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)
  64617. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  64618. */
  64619. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  64620. if (noMipmap === void 0) { noMipmap = false; }
  64621. if (generateHarmonics === void 0) { generateHarmonics = true; }
  64622. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  64623. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  64624. if (onLoad === void 0) { onLoad = null; }
  64625. if (onError === void 0) { onError = null; }
  64626. var _this = _super.call(this, scene) || this;
  64627. _this._useInGammaSpace = false;
  64628. _this._generateHarmonics = true;
  64629. _this._isBABYLONPreprocessed = false;
  64630. _this._onLoad = null;
  64631. _this._onError = null;
  64632. /**
  64633. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  64634. */
  64635. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  64636. /**
  64637. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  64638. * This is usefull at run time to apply the good shader.
  64639. */
  64640. _this.isPMREM = false;
  64641. _this._isBlocking = true;
  64642. if (!url) {
  64643. return _this;
  64644. }
  64645. _this.name = url;
  64646. _this.url = url;
  64647. _this.hasAlpha = false;
  64648. _this.isCube = true;
  64649. _this._textureMatrix = BABYLON.Matrix.Identity();
  64650. _this._onLoad = onLoad;
  64651. _this._onError = onError;
  64652. _this.gammaSpace = false;
  64653. var caps = scene.getEngine().getCaps();
  64654. if (size) {
  64655. _this._isBABYLONPreprocessed = false;
  64656. _this._noMipmap = noMipmap;
  64657. _this._size = size;
  64658. _this._useInGammaSpace = useInGammaSpace;
  64659. _this._usePMREMGenerator = usePMREMGenerator &&
  64660. caps.textureLOD &&
  64661. caps.textureFloat &&
  64662. !_this._useInGammaSpace;
  64663. }
  64664. else {
  64665. _this._isBABYLONPreprocessed = true;
  64666. _this._noMipmap = false;
  64667. _this._useInGammaSpace = false;
  64668. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  64669. !_this._useInGammaSpace;
  64670. }
  64671. _this.isPMREM = _this._usePMREMGenerator;
  64672. _this._texture = _this._getFromCache(url, _this._noMipmap);
  64673. if (!_this._texture) {
  64674. if (!scene.useDelayedTextureLoading) {
  64675. _this.loadTexture();
  64676. }
  64677. else {
  64678. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  64679. }
  64680. }
  64681. return _this;
  64682. }
  64683. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  64684. /**
  64685. * Gets wether or not the texture is blocking during loading.
  64686. */
  64687. get: function () {
  64688. return this._isBlocking;
  64689. },
  64690. /**
  64691. * Sets wether or not the texture is blocking during loading.
  64692. */
  64693. set: function (value) {
  64694. this._isBlocking = value;
  64695. },
  64696. enumerable: true,
  64697. configurable: true
  64698. });
  64699. /**
  64700. * Occurs when the file is a preprocessed .babylon.hdr file.
  64701. */
  64702. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  64703. var _this = this;
  64704. var mipLevels = 0;
  64705. var floatArrayView = null;
  64706. var scene = this.getScene();
  64707. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  64708. var mips = new Array();
  64709. if (!floatArrayView) {
  64710. return mips;
  64711. }
  64712. var startIndex = 30;
  64713. for (var level = 0; level < mipLevels; level++) {
  64714. mips.push([]);
  64715. // Fill each pixel of the mip level.
  64716. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  64717. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  64718. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  64719. mips[level].push(faceData);
  64720. startIndex += faceSize;
  64721. }
  64722. }
  64723. return mips;
  64724. } : null;
  64725. var callback = function (buffer) {
  64726. var scene = _this.getScene();
  64727. if (!scene) {
  64728. return null;
  64729. }
  64730. // Create Native Array Views
  64731. var intArrayView = new Int32Array(buffer);
  64732. floatArrayView = new Float32Array(buffer);
  64733. // Fill header.
  64734. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  64735. _this._size = intArrayView[1]; // CubeMap max mip face size.
  64736. // Update Texture Information.
  64737. if (!_this._texture) {
  64738. return null;
  64739. }
  64740. _this._texture.updateSize(_this._size, _this._size);
  64741. // Fill polynomial information.
  64742. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  64743. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  64744. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  64745. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  64746. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  64747. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  64748. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  64749. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  64750. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  64751. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  64752. _this.sphericalPolynomial = sphericalPolynomial;
  64753. // Fill pixel data.
  64754. mipLevels = intArrayView[29]; // Number of mip levels.
  64755. var startIndex = 30;
  64756. var data = [];
  64757. var faceSize = Math.pow(_this._size, 2) * 3;
  64758. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  64759. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  64760. startIndex += faceSize;
  64761. }
  64762. var results = [];
  64763. var byteArray = null;
  64764. // Push each faces.
  64765. for (var k = 0; k < 6; k++) {
  64766. var dataFace = null;
  64767. // To be deprecated.
  64768. if (version === 1) {
  64769. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  64770. dataFace = data[j];
  64771. }
  64772. // If special cases.
  64773. if (!mipmapGenerator && dataFace) {
  64774. if (!scene.getEngine().getCaps().textureFloat) {
  64775. // 3 channels of 1 bytes per pixel in bytes.
  64776. var byteBuffer = new ArrayBuffer(faceSize);
  64777. byteArray = new Uint8Array(byteBuffer);
  64778. }
  64779. for (var i = 0; i < _this._size * _this._size; i++) {
  64780. // Put in gamma space if requested.
  64781. if (_this._useInGammaSpace) {
  64782. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  64783. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  64784. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  64785. }
  64786. // Convert to int texture for fallback.
  64787. if (byteArray) {
  64788. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  64789. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  64790. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  64791. // May use luminance instead if the result is not accurate.
  64792. var max = Math.max(Math.max(r, g), b);
  64793. if (max > 255) {
  64794. var scale = 255 / max;
  64795. r *= scale;
  64796. g *= scale;
  64797. b *= scale;
  64798. }
  64799. byteArray[(i * 3) + 0] = r;
  64800. byteArray[(i * 3) + 1] = g;
  64801. byteArray[(i * 3) + 2] = b;
  64802. }
  64803. }
  64804. }
  64805. // Fill the array accordingly.
  64806. if (byteArray) {
  64807. results.push(byteArray);
  64808. }
  64809. else {
  64810. results.push(dataFace);
  64811. }
  64812. }
  64813. return results;
  64814. };
  64815. if (scene) {
  64816. 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);
  64817. }
  64818. };
  64819. /**
  64820. * Occurs when the file is raw .hdr file.
  64821. */
  64822. HDRCubeTexture.prototype.loadHDRTexture = function () {
  64823. var _this = this;
  64824. var callback = function (buffer) {
  64825. var scene = _this.getScene();
  64826. if (!scene) {
  64827. return null;
  64828. }
  64829. // Extract the raw linear data.
  64830. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  64831. // Generate harmonics if needed.
  64832. if (_this._generateHarmonics) {
  64833. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  64834. _this.sphericalPolynomial = sphericalPolynomial;
  64835. }
  64836. var results = [];
  64837. var byteArray = null;
  64838. // Push each faces.
  64839. for (var j = 0; j < 6; j++) {
  64840. // Create uintarray fallback.
  64841. if (!scene.getEngine().getCaps().textureFloat) {
  64842. // 3 channels of 1 bytes per pixel in bytes.
  64843. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  64844. byteArray = new Uint8Array(byteBuffer);
  64845. }
  64846. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  64847. // If special cases.
  64848. if (_this._useInGammaSpace || byteArray) {
  64849. for (var i = 0; i < _this._size * _this._size; i++) {
  64850. // Put in gamma space if requested.
  64851. if (_this._useInGammaSpace) {
  64852. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  64853. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  64854. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  64855. }
  64856. // Convert to int texture for fallback.
  64857. if (byteArray) {
  64858. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  64859. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  64860. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  64861. // May use luminance instead if the result is not accurate.
  64862. var max = Math.max(Math.max(r, g), b);
  64863. if (max > 255) {
  64864. var scale = 255 / max;
  64865. r *= scale;
  64866. g *= scale;
  64867. b *= scale;
  64868. }
  64869. byteArray[(i * 3) + 0] = r;
  64870. byteArray[(i * 3) + 1] = g;
  64871. byteArray[(i * 3) + 2] = b;
  64872. }
  64873. }
  64874. }
  64875. if (byteArray) {
  64876. results.push(byteArray);
  64877. }
  64878. else {
  64879. results.push(dataFace);
  64880. }
  64881. }
  64882. return results;
  64883. };
  64884. var mipmapGenerator = null;
  64885. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  64886. // if (!this._noMipmap &&
  64887. // this._usePMREMGenerator) {
  64888. // mipmapGenerator = (data: ArrayBufferView[]) => {
  64889. // // Custom setup of the generator matching with the PBR shader values.
  64890. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  64891. // this._size,
  64892. // this._size,
  64893. // 0,
  64894. // 3,
  64895. // this.getScene().getEngine().getCaps().textureFloat,
  64896. // 2048,
  64897. // 0.25,
  64898. // false,
  64899. // true);
  64900. // return generator.filterCubeMap();
  64901. // };
  64902. // }
  64903. var scene = this.getScene();
  64904. if (scene) {
  64905. 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);
  64906. }
  64907. };
  64908. /**
  64909. * Starts the loading process of the texture.
  64910. */
  64911. HDRCubeTexture.prototype.loadTexture = function () {
  64912. if (this._isBABYLONPreprocessed) {
  64913. this.loadBabylonTexture();
  64914. }
  64915. else {
  64916. this.loadHDRTexture();
  64917. }
  64918. };
  64919. HDRCubeTexture.prototype.clone = function () {
  64920. var scene = this.getScene();
  64921. if (!scene) {
  64922. return this;
  64923. }
  64924. var size = (this._isBABYLONPreprocessed ? null : this._size);
  64925. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  64926. // Base texture
  64927. newTexture.level = this.level;
  64928. newTexture.wrapU = this.wrapU;
  64929. newTexture.wrapV = this.wrapV;
  64930. newTexture.coordinatesIndex = this.coordinatesIndex;
  64931. newTexture.coordinatesMode = this.coordinatesMode;
  64932. return newTexture;
  64933. };
  64934. // Methods
  64935. HDRCubeTexture.prototype.delayLoad = function () {
  64936. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  64937. return;
  64938. }
  64939. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  64940. this._texture = this._getFromCache(this.url, this._noMipmap);
  64941. if (!this._texture) {
  64942. this.loadTexture();
  64943. }
  64944. };
  64945. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  64946. return this._textureMatrix;
  64947. };
  64948. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  64949. this._textureMatrix = value;
  64950. };
  64951. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  64952. var texture = null;
  64953. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  64954. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  64955. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  64956. texture.name = parsedTexture.name;
  64957. texture.hasAlpha = parsedTexture.hasAlpha;
  64958. texture.level = parsedTexture.level;
  64959. texture.coordinatesMode = parsedTexture.coordinatesMode;
  64960. texture.isBlocking = parsedTexture.isBlocking;
  64961. }
  64962. return texture;
  64963. };
  64964. HDRCubeTexture.prototype.serialize = function () {
  64965. if (!this.name) {
  64966. return null;
  64967. }
  64968. var serializationObject = {};
  64969. serializationObject.name = this.name;
  64970. serializationObject.hasAlpha = this.hasAlpha;
  64971. serializationObject.isCube = true;
  64972. serializationObject.level = this.level;
  64973. serializationObject.size = this._size;
  64974. serializationObject.coordinatesMode = this.coordinatesMode;
  64975. serializationObject.useInGammaSpace = this._useInGammaSpace;
  64976. serializationObject.generateHarmonics = this._generateHarmonics;
  64977. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  64978. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  64979. serializationObject.customType = "BABYLON.HDRCubeTexture";
  64980. serializationObject.noMipmap = this._noMipmap;
  64981. serializationObject.isBlocking = this._isBlocking;
  64982. return serializationObject;
  64983. };
  64984. /**
  64985. * Saves as a file the data contained in the texture in a binary format.
  64986. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  64987. * as the spherical used in the lighting.
  64988. * @param url The HDR file url.
  64989. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  64990. * @param onError Method called if any error happens during download.
  64991. * @return The packed binary data.
  64992. */
  64993. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  64994. if (onError === void 0) { onError = null; }
  64995. var callback = function (buffer) {
  64996. var data = new Blob([buffer], { type: 'application/octet-stream' });
  64997. // Returns a URL you can use as a href.
  64998. var objUrl = window.URL.createObjectURL(data);
  64999. // Simulates a link to it and click to dowload.
  65000. var a = document.createElement("a");
  65001. document.body.appendChild(a);
  65002. a.style.display = "none";
  65003. a.href = objUrl;
  65004. a.download = "envmap.babylon.hdr";
  65005. a.click();
  65006. };
  65007. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  65008. };
  65009. /**
  65010. * Serializes the data contained in the texture in a binary format.
  65011. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  65012. * as the spherical used in the lighting.
  65013. * @param url The HDR file url.
  65014. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  65015. * @param onError Method called if any error happens during download.
  65016. * @return The packed binary data.
  65017. */
  65018. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  65019. if (onError === void 0) { onError = null; }
  65020. // Needs the url tho create the texture.
  65021. if (!url) {
  65022. return;
  65023. }
  65024. // Check Power of two size.
  65025. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  65026. return;
  65027. }
  65028. // Coming Back in 3.x.
  65029. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  65030. };
  65031. HDRCubeTexture._facesMapping = [
  65032. "right",
  65033. "left",
  65034. "up",
  65035. "down",
  65036. "front",
  65037. "back"
  65038. ];
  65039. return HDRCubeTexture;
  65040. }(BABYLON.BaseTexture));
  65041. BABYLON.HDRCubeTexture = HDRCubeTexture;
  65042. })(BABYLON || (BABYLON = {}));
  65043. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  65044. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  65045. // Huge respect for a such great lib.
  65046. // Earcut license:
  65047. // Copyright (c) 2016, Mapbox
  65048. //
  65049. // Permission to use, copy, modify, and/or distribute this software for any purpose
  65050. // with or without fee is hereby granted, provided that the above copyright notice
  65051. // and this permission notice appear in all copies.
  65052. //
  65053. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  65054. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  65055. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  65056. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  65057. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  65058. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  65059. // THIS SOFTWARE.
  65060. var Earcut;
  65061. (function (Earcut) {
  65062. /**
  65063. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  65064. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  65065. * @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).
  65066. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  65067. */
  65068. function earcut(data, holeIndices, dim) {
  65069. dim = dim || 2;
  65070. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  65071. if (!outerNode)
  65072. return triangles;
  65073. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  65074. if (hasHoles)
  65075. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  65076. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  65077. if (data.length > 80 * dim) {
  65078. minX = maxX = data[0];
  65079. minY = maxY = data[1];
  65080. for (var i = dim; i < outerLen; i += dim) {
  65081. x = data[i];
  65082. y = data[i + 1];
  65083. if (x < minX)
  65084. minX = x;
  65085. if (y < minY)
  65086. minY = y;
  65087. if (x > maxX)
  65088. maxX = x;
  65089. if (y > maxY)
  65090. maxY = y;
  65091. }
  65092. // minX, minY and size are later used to transform coords into integers for z-order calculation
  65093. size = Math.max(maxX - minX, maxY - minY);
  65094. }
  65095. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  65096. return triangles;
  65097. }
  65098. Earcut.earcut = earcut;
  65099. var Node = /** @class */ (function () {
  65100. function Node(i, x, y) {
  65101. this.i = i;
  65102. this.x = x;
  65103. this.y = y;
  65104. this.prev = null;
  65105. this.next = null;
  65106. this.z = null;
  65107. this.prevZ = null;
  65108. this.nextZ = null;
  65109. this.steiner = false;
  65110. }
  65111. return Node;
  65112. }());
  65113. // create a circular doubly linked list from polygon points in the specified winding order
  65114. function linkedList(data, start, end, dim, clockwise) {
  65115. var i, last = null;
  65116. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  65117. for (i = start; i < end; i += dim)
  65118. last = insertNode(i, data[i], data[i + 1], last);
  65119. }
  65120. else {
  65121. for (i = end - dim; i >= start; i -= dim)
  65122. last = insertNode(i, data[i], data[i + 1], last);
  65123. }
  65124. if (last && equals(last, last.next)) {
  65125. removeNode(last);
  65126. last = last.next;
  65127. }
  65128. return last;
  65129. }
  65130. // eliminate colinear or duplicate points
  65131. function filterPoints(start, end) {
  65132. if (!start)
  65133. return start;
  65134. if (!end)
  65135. end = start;
  65136. var p = start, again;
  65137. do {
  65138. again = false;
  65139. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  65140. removeNode(p);
  65141. p = end = p.prev;
  65142. if (p === p.next)
  65143. return undefined;
  65144. again = true;
  65145. }
  65146. else {
  65147. p = p.next;
  65148. }
  65149. } while (again || p !== end);
  65150. return end;
  65151. }
  65152. // main ear slicing loop which triangulates a polygon (given as a linked list)
  65153. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  65154. if (!ear)
  65155. return;
  65156. // interlink polygon nodes in z-order
  65157. if (!pass && size)
  65158. indexCurve(ear, minX, minY, size);
  65159. var stop = ear, prev, next;
  65160. // iterate through ears, slicing them one by one
  65161. while (ear.prev !== ear.next) {
  65162. prev = ear.prev;
  65163. next = ear.next;
  65164. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  65165. // cut off the triangle
  65166. triangles.push(prev.i / dim);
  65167. triangles.push(ear.i / dim);
  65168. triangles.push(next.i / dim);
  65169. removeNode(ear);
  65170. // skipping the next vertice leads to less sliver triangles
  65171. ear = next.next;
  65172. stop = next.next;
  65173. continue;
  65174. }
  65175. ear = next;
  65176. // if we looped through the whole remaining polygon and can't find any more ears
  65177. if (ear === stop) {
  65178. // try filtering points and slicing again
  65179. if (!pass) {
  65180. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  65181. // if this didn't work, try curing all small self-intersections locally
  65182. }
  65183. else if (pass === 1) {
  65184. ear = cureLocalIntersections(ear, triangles, dim);
  65185. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  65186. // as a last resort, try splitting the remaining polygon into two
  65187. }
  65188. else if (pass === 2) {
  65189. splitEarcut(ear, triangles, dim, minX, minY, size);
  65190. }
  65191. break;
  65192. }
  65193. }
  65194. }
  65195. // check whether a polygon node forms a valid ear with adjacent nodes
  65196. function isEar(ear) {
  65197. var a = ear.prev, b = ear, c = ear.next;
  65198. if (area(a, b, c) >= 0)
  65199. return false; // reflex, can't be an ear
  65200. // now make sure we don't have other points inside the potential ear
  65201. var p = ear.next.next;
  65202. while (p !== ear.prev) {
  65203. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  65204. area(p.prev, p, p.next) >= 0)
  65205. return false;
  65206. p = p.next;
  65207. }
  65208. return true;
  65209. }
  65210. function isEarHashed(ear, minX, minY, size) {
  65211. var a = ear.prev, b = ear, c = ear.next;
  65212. if (area(a, b, c) >= 0)
  65213. return false; // reflex, can't be an ear
  65214. // triangle bbox; min & max are calculated like this for speed
  65215. 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);
  65216. // z-order range for the current triangle bbox;
  65217. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  65218. // first look for points inside the triangle in increasing z-order
  65219. var p = ear.nextZ;
  65220. while (p && p.z <= maxZ) {
  65221. if (p !== ear.prev &&
  65222. p !== ear.next &&
  65223. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  65224. area(p.prev, p, p.next) >= 0)
  65225. return false;
  65226. p = p.nextZ;
  65227. }
  65228. // then look for points in decreasing z-order
  65229. p = ear.prevZ;
  65230. while (p && p.z >= minZ) {
  65231. if (p !== ear.prev &&
  65232. p !== ear.next &&
  65233. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  65234. area(p.prev, p, p.next) >= 0)
  65235. return false;
  65236. p = p.prevZ;
  65237. }
  65238. return true;
  65239. }
  65240. // go through all polygon nodes and cure small local self-intersections
  65241. function cureLocalIntersections(start, triangles, dim) {
  65242. var p = start;
  65243. do {
  65244. var a = p.prev, b = p.next.next;
  65245. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  65246. triangles.push(a.i / dim);
  65247. triangles.push(p.i / dim);
  65248. triangles.push(b.i / dim);
  65249. // remove two nodes involved
  65250. removeNode(p);
  65251. removeNode(p.next);
  65252. p = start = b;
  65253. }
  65254. p = p.next;
  65255. } while (p !== start);
  65256. return p;
  65257. }
  65258. // try splitting polygon into two and triangulate them independently
  65259. function splitEarcut(start, triangles, dim, minX, minY, size) {
  65260. // look for a valid diagonal that divides the polygon into two
  65261. var a = start;
  65262. do {
  65263. var b = a.next.next;
  65264. while (b !== a.prev) {
  65265. if (a.i !== b.i && isValidDiagonal(a, b)) {
  65266. // split the polygon in two by the diagonal
  65267. var c = splitPolygon(a, b);
  65268. // filter colinear points around the cuts
  65269. a = filterPoints(a, a.next);
  65270. c = filterPoints(c, c.next);
  65271. // run earcut on each half
  65272. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  65273. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  65274. return;
  65275. }
  65276. b = b.next;
  65277. }
  65278. a = a.next;
  65279. } while (a !== start);
  65280. }
  65281. // link every hole into the outer loop, producing a single-ring polygon without holes
  65282. function eliminateHoles(data, holeIndices, outerNode, dim) {
  65283. var queue = [], i, len, start, end, list;
  65284. for (i = 0, len = holeIndices.length; i < len; i++) {
  65285. start = holeIndices[i] * dim;
  65286. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  65287. list = linkedList(data, start, end, dim, false);
  65288. if (list === list.next)
  65289. list.steiner = true;
  65290. queue.push(getLeftmost(list));
  65291. }
  65292. queue.sort(compareX);
  65293. // process holes from left to right
  65294. for (i = 0; i < queue.length; i++) {
  65295. eliminateHole(queue[i], outerNode);
  65296. outerNode = filterPoints(outerNode, outerNode.next);
  65297. }
  65298. return outerNode;
  65299. }
  65300. function compareX(a, b) {
  65301. return a.x - b.x;
  65302. }
  65303. // find a bridge between vertices that connects hole with an outer ring and and link it
  65304. function eliminateHole(hole, outerNode) {
  65305. outerNode = findHoleBridge(hole, outerNode);
  65306. if (outerNode) {
  65307. var b = splitPolygon(outerNode, hole);
  65308. filterPoints(b, b.next);
  65309. }
  65310. }
  65311. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  65312. function findHoleBridge(hole, outerNode) {
  65313. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  65314. // find a segment intersected by a ray from the hole's leftmost point to the left;
  65315. // segment's endpoint with lesser x will be potential connection point
  65316. do {
  65317. if (hy <= p.y && hy >= p.next.y) {
  65318. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  65319. if (x <= hx && x > qx) {
  65320. qx = x;
  65321. if (x === hx) {
  65322. if (hy === p.y)
  65323. return p;
  65324. if (hy === p.next.y)
  65325. return p.next;
  65326. }
  65327. m = p.x < p.next.x ? p : p.next;
  65328. }
  65329. }
  65330. p = p.next;
  65331. } while (p !== outerNode);
  65332. if (!m)
  65333. return null;
  65334. if (hx === qx)
  65335. return m.prev; // hole touches outer segment; pick lower endpoint
  65336. // look for points inside the triangle of hole point, segment intersection and endpoint;
  65337. // if there are no points found, we have a valid connection;
  65338. // otherwise choose the point of the minimum angle with the ray as connection point
  65339. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  65340. p = m.next;
  65341. while (p !== stop) {
  65342. if (hx >= p.x &&
  65343. p.x >= mx &&
  65344. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  65345. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  65346. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  65347. m = p;
  65348. tanMin = tan;
  65349. }
  65350. }
  65351. p = p.next;
  65352. }
  65353. return m;
  65354. }
  65355. // interlink polygon nodes in z-order
  65356. function indexCurve(start, minX, minY, size) {
  65357. var p = start;
  65358. do {
  65359. if (p.z === null)
  65360. p.z = zOrder(p.x, p.y, minX, minY, size);
  65361. p.prevZ = p.prev;
  65362. p.nextZ = p.next;
  65363. p = p.next;
  65364. } while (p !== start);
  65365. p.prevZ.nextZ = null;
  65366. p.prevZ = null;
  65367. sortLinked(p);
  65368. }
  65369. // Simon Tatham's linked list merge sort algorithm
  65370. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  65371. function sortLinked(list) {
  65372. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  65373. do {
  65374. p = list;
  65375. list = null;
  65376. tail = null;
  65377. numMerges = 0;
  65378. while (p) {
  65379. numMerges++;
  65380. q = p;
  65381. pSize = 0;
  65382. for (i = 0; i < inSize; i++) {
  65383. pSize++;
  65384. q = q.nextZ;
  65385. if (!q)
  65386. break;
  65387. }
  65388. qSize = inSize;
  65389. while (pSize > 0 || (qSize > 0 && q)) {
  65390. if (pSize === 0) {
  65391. e = q;
  65392. q = q.nextZ;
  65393. qSize--;
  65394. }
  65395. else if (qSize === 0 || !q) {
  65396. e = p;
  65397. p = p.nextZ;
  65398. pSize--;
  65399. }
  65400. else if (p.z <= q.z) {
  65401. e = p;
  65402. p = p.nextZ;
  65403. pSize--;
  65404. }
  65405. else {
  65406. e = q;
  65407. q = q.nextZ;
  65408. qSize--;
  65409. }
  65410. if (tail)
  65411. tail.nextZ = e;
  65412. else
  65413. list = e;
  65414. e.prevZ = tail;
  65415. tail = e;
  65416. }
  65417. p = q;
  65418. }
  65419. tail.nextZ = null;
  65420. inSize *= 2;
  65421. } while (numMerges > 1);
  65422. return list;
  65423. }
  65424. // z-order of a point given coords and size of the data bounding box
  65425. function zOrder(x, y, minX, minY, size) {
  65426. // coords are transformed into non-negative 15-bit integer range
  65427. x = 32767 * (x - minX) / size;
  65428. y = 32767 * (y - minY) / size;
  65429. x = (x | (x << 8)) & 0x00FF00FF;
  65430. x = (x | (x << 4)) & 0x0F0F0F0F;
  65431. x = (x | (x << 2)) & 0x33333333;
  65432. x = (x | (x << 1)) & 0x55555555;
  65433. y = (y | (y << 8)) & 0x00FF00FF;
  65434. y = (y | (y << 4)) & 0x0F0F0F0F;
  65435. y = (y | (y << 2)) & 0x33333333;
  65436. y = (y | (y << 1)) & 0x55555555;
  65437. return x | (y << 1);
  65438. }
  65439. // find the leftmost node of a polygon ring
  65440. function getLeftmost(start) {
  65441. var p = start, leftmost = start;
  65442. do {
  65443. if (p.x < leftmost.x)
  65444. leftmost = p;
  65445. p = p.next;
  65446. } while (p !== start);
  65447. return leftmost;
  65448. }
  65449. // check if a point lies within a convex triangle
  65450. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  65451. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  65452. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  65453. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  65454. }
  65455. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  65456. function isValidDiagonal(a, b) {
  65457. return a.next.i !== b.i &&
  65458. a.prev.i !== b.i &&
  65459. !intersectsPolygon(a, b) &&
  65460. locallyInside(a, b) &&
  65461. locallyInside(b, a) &&
  65462. middleInside(a, b);
  65463. }
  65464. // signed area of a triangle
  65465. function area(p, q, r) {
  65466. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  65467. }
  65468. // check if two points are equal
  65469. function equals(p1, p2) {
  65470. return p1.x === p2.x && p1.y === p2.y;
  65471. }
  65472. // check if two segments intersect
  65473. function intersects(p1, q1, p2, q2) {
  65474. if ((equals(p1, q1) && equals(p2, q2)) ||
  65475. (equals(p1, q2) && equals(p2, q1)))
  65476. return true;
  65477. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  65478. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  65479. }
  65480. // check if a polygon diagonal intersects any polygon segments
  65481. function intersectsPolygon(a, b) {
  65482. var p = a;
  65483. do {
  65484. if (p.i !== a.i &&
  65485. p.next.i !== a.i &&
  65486. p.i !== b.i &&
  65487. p.next.i !== b.i &&
  65488. intersects(p, p.next, a, b))
  65489. return true;
  65490. p = p.next;
  65491. } while (p !== a);
  65492. return false;
  65493. }
  65494. // check if a polygon diagonal is locally inside the polygon
  65495. function locallyInside(a, b) {
  65496. return area(a.prev, a, a.next) < 0
  65497. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  65498. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  65499. }
  65500. // check if the middle point of a polygon diagonal is inside the polygon
  65501. function middleInside(a, b) {
  65502. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  65503. do {
  65504. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  65505. inside = !inside;
  65506. p = p.next;
  65507. } while (p !== a);
  65508. return inside;
  65509. }
  65510. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  65511. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  65512. function splitPolygon(a, b) {
  65513. 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;
  65514. a.next = b;
  65515. b.prev = a;
  65516. a2.next = an;
  65517. an.prev = a2;
  65518. b2.next = a2;
  65519. a2.prev = b2;
  65520. bp.next = b2;
  65521. b2.prev = bp;
  65522. return b2;
  65523. }
  65524. // create a node and optionally link it with previous one (in a circular doubly linked list)
  65525. function insertNode(i, x, y, last) {
  65526. var p = new Node(i, x, y);
  65527. if (!last) {
  65528. p.prev = p;
  65529. p.next = p;
  65530. }
  65531. else {
  65532. p.next = last.next;
  65533. p.prev = last;
  65534. last.next.prev = p;
  65535. last.next = p;
  65536. }
  65537. return p;
  65538. }
  65539. function removeNode(p) {
  65540. p.next.prev = p.prev;
  65541. p.prev.next = p.next;
  65542. if (p.prevZ)
  65543. p.prevZ.nextZ = p.nextZ;
  65544. if (p.nextZ)
  65545. p.nextZ.prevZ = p.prevZ;
  65546. }
  65547. /**
  65548. * return a percentage difference between the polygon area and its triangulation area;
  65549. * used to verify correctness of triangulation
  65550. */
  65551. function deviation(data, holeIndices, dim, triangles) {
  65552. var hasHoles = holeIndices && holeIndices.length;
  65553. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  65554. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  65555. if (hasHoles) {
  65556. for (var i = 0, len = holeIndices.length; i < len; i++) {
  65557. var start = holeIndices[i] * dim;
  65558. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  65559. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  65560. }
  65561. }
  65562. var trianglesArea = 0;
  65563. for (i = 0; i < triangles.length; i += 3) {
  65564. var a = triangles[i] * dim;
  65565. var b = triangles[i + 1] * dim;
  65566. var c = triangles[i + 2] * dim;
  65567. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  65568. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  65569. }
  65570. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  65571. }
  65572. Earcut.deviation = deviation;
  65573. ;
  65574. function signedArea(data, start, end, dim) {
  65575. var sum = 0;
  65576. for (var i = start, j = end - dim; i < end; i += dim) {
  65577. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  65578. j = i;
  65579. }
  65580. return sum;
  65581. }
  65582. /**
  65583. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  65584. */
  65585. function flatten(data) {
  65586. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  65587. for (var i = 0; i < data.length; i++) {
  65588. for (var j = 0; j < data[i].length; j++) {
  65589. for (var d = 0; d < dim; d++)
  65590. result.vertices.push(data[i][j][d]);
  65591. }
  65592. if (i > 0) {
  65593. holeIndex += data[i - 1].length;
  65594. result.holes.push(holeIndex);
  65595. }
  65596. }
  65597. return result;
  65598. }
  65599. Earcut.flatten = flatten;
  65600. ;
  65601. })(Earcut || (Earcut = {}));
  65602. //# sourceMappingURL=babylon.earcut.js.map
  65603. var BABYLON;
  65604. (function (BABYLON) {
  65605. var IndexedVector2 = /** @class */ (function (_super) {
  65606. __extends(IndexedVector2, _super);
  65607. function IndexedVector2(original, index) {
  65608. var _this = _super.call(this, original.x, original.y) || this;
  65609. _this.index = index;
  65610. return _this;
  65611. }
  65612. return IndexedVector2;
  65613. }(BABYLON.Vector2));
  65614. var PolygonPoints = /** @class */ (function () {
  65615. function PolygonPoints() {
  65616. this.elements = new Array();
  65617. }
  65618. PolygonPoints.prototype.add = function (originalPoints) {
  65619. var _this = this;
  65620. var result = new Array();
  65621. originalPoints.forEach(function (point) {
  65622. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  65623. var newPoint = new IndexedVector2(point, _this.elements.length);
  65624. result.push(newPoint);
  65625. _this.elements.push(newPoint);
  65626. }
  65627. });
  65628. return result;
  65629. };
  65630. PolygonPoints.prototype.computeBounds = function () {
  65631. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  65632. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  65633. this.elements.forEach(function (point) {
  65634. // x
  65635. if (point.x < lmin.x) {
  65636. lmin.x = point.x;
  65637. }
  65638. else if (point.x > lmax.x) {
  65639. lmax.x = point.x;
  65640. }
  65641. // y
  65642. if (point.y < lmin.y) {
  65643. lmin.y = point.y;
  65644. }
  65645. else if (point.y > lmax.y) {
  65646. lmax.y = point.y;
  65647. }
  65648. });
  65649. return {
  65650. min: lmin,
  65651. max: lmax,
  65652. width: lmax.x - lmin.x,
  65653. height: lmax.y - lmin.y
  65654. };
  65655. };
  65656. return PolygonPoints;
  65657. }());
  65658. var Polygon = /** @class */ (function () {
  65659. function Polygon() {
  65660. }
  65661. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  65662. return [
  65663. new BABYLON.Vector2(xmin, ymin),
  65664. new BABYLON.Vector2(xmax, ymin),
  65665. new BABYLON.Vector2(xmax, ymax),
  65666. new BABYLON.Vector2(xmin, ymax)
  65667. ];
  65668. };
  65669. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  65670. if (cx === void 0) { cx = 0; }
  65671. if (cy === void 0) { cy = 0; }
  65672. if (numberOfSides === void 0) { numberOfSides = 32; }
  65673. var result = new Array();
  65674. var angle = 0;
  65675. var increment = (Math.PI * 2) / numberOfSides;
  65676. for (var i = 0; i < numberOfSides; i++) {
  65677. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  65678. angle -= increment;
  65679. }
  65680. return result;
  65681. };
  65682. Polygon.Parse = function (input) {
  65683. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  65684. var i, result = [];
  65685. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  65686. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  65687. }
  65688. return result;
  65689. };
  65690. Polygon.StartingAt = function (x, y) {
  65691. return BABYLON.Path2.StartingAt(x, y);
  65692. };
  65693. return Polygon;
  65694. }());
  65695. BABYLON.Polygon = Polygon;
  65696. var PolygonMeshBuilder = /** @class */ (function () {
  65697. function PolygonMeshBuilder(name, contours, scene) {
  65698. this._points = new PolygonPoints();
  65699. this._outlinepoints = new PolygonPoints();
  65700. this._holes = new Array();
  65701. this._epoints = new Array();
  65702. this._eholes = new Array();
  65703. this._name = name;
  65704. this._scene = scene;
  65705. var points;
  65706. if (contours instanceof BABYLON.Path2) {
  65707. points = contours.getPoints();
  65708. }
  65709. else {
  65710. points = contours;
  65711. }
  65712. this._addToepoint(points);
  65713. this._points.add(points);
  65714. this._outlinepoints.add(points);
  65715. }
  65716. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  65717. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  65718. var p = points_1[_i];
  65719. this._epoints.push(p.x, p.y);
  65720. }
  65721. };
  65722. PolygonMeshBuilder.prototype.addHole = function (hole) {
  65723. this._points.add(hole);
  65724. var holepoints = new PolygonPoints();
  65725. holepoints.add(hole);
  65726. this._holes.push(holepoints);
  65727. this._eholes.push(this._epoints.length / 2);
  65728. this._addToepoint(hole);
  65729. return this;
  65730. };
  65731. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  65732. var _this = this;
  65733. if (updatable === void 0) { updatable = false; }
  65734. if (depth === void 0) { depth = 0; }
  65735. var result = new BABYLON.Mesh(this._name, this._scene);
  65736. var normals = new Array();
  65737. var positions = new Array();
  65738. var uvs = new Array();
  65739. var bounds = this._points.computeBounds();
  65740. this._points.elements.forEach(function (p) {
  65741. normals.push(0, 1.0, 0);
  65742. positions.push(p.x, 0, p.y);
  65743. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  65744. });
  65745. var indices = new Array();
  65746. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  65747. for (var i = 0; i < res.length; i++) {
  65748. indices.push(res[i]);
  65749. }
  65750. if (depth > 0) {
  65751. var positionscount = (positions.length / 3); //get the current pointcount
  65752. this._points.elements.forEach(function (p) {
  65753. normals.push(0, -1.0, 0);
  65754. positions.push(p.x, -depth, p.y);
  65755. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  65756. });
  65757. var totalCount = indices.length;
  65758. for (var i = 0; i < totalCount; i += 3) {
  65759. var i0 = indices[i + 0];
  65760. var i1 = indices[i + 1];
  65761. var i2 = indices[i + 2];
  65762. indices.push(i2 + positionscount);
  65763. indices.push(i1 + positionscount);
  65764. indices.push(i0 + positionscount);
  65765. }
  65766. //Add the sides
  65767. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  65768. this._holes.forEach(function (hole) {
  65769. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  65770. });
  65771. }
  65772. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  65773. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  65774. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  65775. result.setIndices(indices);
  65776. return result;
  65777. };
  65778. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  65779. var StartIndex = positions.length / 3;
  65780. var ulength = 0;
  65781. for (var i = 0; i < points.elements.length; i++) {
  65782. var p = points.elements[i];
  65783. var p1;
  65784. if ((i + 1) > points.elements.length - 1) {
  65785. p1 = points.elements[0];
  65786. }
  65787. else {
  65788. p1 = points.elements[i + 1];
  65789. }
  65790. positions.push(p.x, 0, p.y);
  65791. positions.push(p.x, -depth, p.y);
  65792. positions.push(p1.x, 0, p1.y);
  65793. positions.push(p1.x, -depth, p1.y);
  65794. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  65795. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  65796. var v3 = v2.subtract(v1);
  65797. var v4 = new BABYLON.Vector3(0, 1, 0);
  65798. var vn = BABYLON.Vector3.Cross(v3, v4);
  65799. vn = vn.normalize();
  65800. uvs.push(ulength / bounds.width, 0);
  65801. uvs.push(ulength / bounds.width, 1);
  65802. ulength += v3.length();
  65803. uvs.push((ulength / bounds.width), 0);
  65804. uvs.push((ulength / bounds.width), 1);
  65805. if (!flip) {
  65806. normals.push(-vn.x, -vn.y, -vn.z);
  65807. normals.push(-vn.x, -vn.y, -vn.z);
  65808. normals.push(-vn.x, -vn.y, -vn.z);
  65809. normals.push(-vn.x, -vn.y, -vn.z);
  65810. indices.push(StartIndex);
  65811. indices.push(StartIndex + 1);
  65812. indices.push(StartIndex + 2);
  65813. indices.push(StartIndex + 1);
  65814. indices.push(StartIndex + 3);
  65815. indices.push(StartIndex + 2);
  65816. }
  65817. else {
  65818. normals.push(vn.x, vn.y, vn.z);
  65819. normals.push(vn.x, vn.y, vn.z);
  65820. normals.push(vn.x, vn.y, vn.z);
  65821. normals.push(vn.x, vn.y, vn.z);
  65822. indices.push(StartIndex);
  65823. indices.push(StartIndex + 2);
  65824. indices.push(StartIndex + 1);
  65825. indices.push(StartIndex + 1);
  65826. indices.push(StartIndex + 2);
  65827. indices.push(StartIndex + 3);
  65828. }
  65829. StartIndex += 4;
  65830. }
  65831. ;
  65832. };
  65833. return PolygonMeshBuilder;
  65834. }());
  65835. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  65836. })(BABYLON || (BABYLON = {}));
  65837. //# sourceMappingURL=babylon.polygonMesh.js.map
  65838. var BABYLON;
  65839. (function (BABYLON) {
  65840. // Unique ID when we import meshes from Babylon to CSG
  65841. var currentCSGMeshId = 0;
  65842. // # class Vertex
  65843. // Represents a vertex of a polygon. Use your own vertex class instead of this
  65844. // one to provide additional features like texture coordinates and vertex
  65845. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  65846. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  65847. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  65848. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  65849. // is not used anywhere else.
  65850. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  65851. var Vertex = /** @class */ (function () {
  65852. function Vertex(pos, normal, uv) {
  65853. this.pos = pos;
  65854. this.normal = normal;
  65855. this.uv = uv;
  65856. }
  65857. Vertex.prototype.clone = function () {
  65858. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  65859. };
  65860. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  65861. // orientation of a polygon is flipped.
  65862. Vertex.prototype.flip = function () {
  65863. this.normal = this.normal.scale(-1);
  65864. };
  65865. // Create a new vertex between this vertex and `other` by linearly
  65866. // interpolating all properties using a parameter of `t`. Subclasses should
  65867. // override this to interpolate additional properties.
  65868. Vertex.prototype.interpolate = function (other, t) {
  65869. 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));
  65870. };
  65871. return Vertex;
  65872. }());
  65873. // # class Plane
  65874. // Represents a plane in 3D space.
  65875. var Plane = /** @class */ (function () {
  65876. function Plane(normal, w) {
  65877. this.normal = normal;
  65878. this.w = w;
  65879. }
  65880. Plane.FromPoints = function (a, b, c) {
  65881. var v0 = c.subtract(a);
  65882. var v1 = b.subtract(a);
  65883. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  65884. return null;
  65885. }
  65886. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  65887. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  65888. };
  65889. Plane.prototype.clone = function () {
  65890. return new Plane(this.normal.clone(), this.w);
  65891. };
  65892. Plane.prototype.flip = function () {
  65893. this.normal.scaleInPlace(-1);
  65894. this.w = -this.w;
  65895. };
  65896. // Split `polygon` by this plane if needed, then put the polygon or polygon
  65897. // fragments in the appropriate lists. Coplanar polygons go into either
  65898. // `coplanarFront` or `coplanarBack` depending on their orientation with
  65899. // respect to this plane. Polygons in front or in back of this plane go into
  65900. // either `front` or `back`.
  65901. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  65902. var COPLANAR = 0;
  65903. var FRONT = 1;
  65904. var BACK = 2;
  65905. var SPANNING = 3;
  65906. // Classify each point as well as the entire polygon into one of the above
  65907. // four classes.
  65908. var polygonType = 0;
  65909. var types = [];
  65910. var i;
  65911. var t;
  65912. for (i = 0; i < polygon.vertices.length; i++) {
  65913. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  65914. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  65915. polygonType |= type;
  65916. types.push(type);
  65917. }
  65918. // Put the polygon in the correct list, splitting it when necessary.
  65919. switch (polygonType) {
  65920. case COPLANAR:
  65921. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  65922. break;
  65923. case FRONT:
  65924. front.push(polygon);
  65925. break;
  65926. case BACK:
  65927. back.push(polygon);
  65928. break;
  65929. case SPANNING:
  65930. var f = [], b = [];
  65931. for (i = 0; i < polygon.vertices.length; i++) {
  65932. var j = (i + 1) % polygon.vertices.length;
  65933. var ti = types[i], tj = types[j];
  65934. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  65935. if (ti !== BACK)
  65936. f.push(vi);
  65937. if (ti !== FRONT)
  65938. b.push(ti !== BACK ? vi.clone() : vi);
  65939. if ((ti | tj) === SPANNING) {
  65940. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  65941. var v = vi.interpolate(vj, t);
  65942. f.push(v);
  65943. b.push(v.clone());
  65944. }
  65945. }
  65946. var poly;
  65947. if (f.length >= 3) {
  65948. poly = new Polygon(f, polygon.shared);
  65949. if (poly.plane)
  65950. front.push(poly);
  65951. }
  65952. if (b.length >= 3) {
  65953. poly = new Polygon(b, polygon.shared);
  65954. if (poly.plane)
  65955. back.push(poly);
  65956. }
  65957. break;
  65958. }
  65959. };
  65960. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  65961. // point is on the plane.
  65962. Plane.EPSILON = 1e-5;
  65963. return Plane;
  65964. }());
  65965. // # class Polygon
  65966. // Represents a convex polygon. The vertices used to initialize a polygon must
  65967. // be coplanar and form a convex loop.
  65968. //
  65969. // Each convex polygon has a `shared` property, which is shared between all
  65970. // polygons that are clones of each other or were split from the same polygon.
  65971. // This can be used to define per-polygon properties (such as surface color).
  65972. var Polygon = /** @class */ (function () {
  65973. function Polygon(vertices, shared) {
  65974. this.vertices = vertices;
  65975. this.shared = shared;
  65976. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  65977. }
  65978. Polygon.prototype.clone = function () {
  65979. var vertices = this.vertices.map(function (v) { return v.clone(); });
  65980. return new Polygon(vertices, this.shared);
  65981. };
  65982. Polygon.prototype.flip = function () {
  65983. this.vertices.reverse().map(function (v) { v.flip(); });
  65984. this.plane.flip();
  65985. };
  65986. return Polygon;
  65987. }());
  65988. // # class Node
  65989. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  65990. // by picking a polygon to split along. That polygon (and all other coplanar
  65991. // polygons) are added directly to that node and the other polygons are added to
  65992. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  65993. // no distinction between internal and leaf nodes.
  65994. var Node = /** @class */ (function () {
  65995. function Node(polygons) {
  65996. this.plane = null;
  65997. this.front = null;
  65998. this.back = null;
  65999. this.polygons = new Array();
  66000. if (polygons) {
  66001. this.build(polygons);
  66002. }
  66003. }
  66004. Node.prototype.clone = function () {
  66005. var node = new Node();
  66006. node.plane = this.plane && this.plane.clone();
  66007. node.front = this.front && this.front.clone();
  66008. node.back = this.back && this.back.clone();
  66009. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  66010. return node;
  66011. };
  66012. // Convert solid space to empty space and empty space to solid space.
  66013. Node.prototype.invert = function () {
  66014. for (var i = 0; i < this.polygons.length; i++) {
  66015. this.polygons[i].flip();
  66016. }
  66017. if (this.plane) {
  66018. this.plane.flip();
  66019. }
  66020. if (this.front) {
  66021. this.front.invert();
  66022. }
  66023. if (this.back) {
  66024. this.back.invert();
  66025. }
  66026. var temp = this.front;
  66027. this.front = this.back;
  66028. this.back = temp;
  66029. };
  66030. // Recursively remove all polygons in `polygons` that are inside this BSP
  66031. // tree.
  66032. Node.prototype.clipPolygons = function (polygons) {
  66033. if (!this.plane)
  66034. return polygons.slice();
  66035. var front = new Array(), back = new Array();
  66036. for (var i = 0; i < polygons.length; i++) {
  66037. this.plane.splitPolygon(polygons[i], front, back, front, back);
  66038. }
  66039. if (this.front) {
  66040. front = this.front.clipPolygons(front);
  66041. }
  66042. if (this.back) {
  66043. back = this.back.clipPolygons(back);
  66044. }
  66045. else {
  66046. back = [];
  66047. }
  66048. return front.concat(back);
  66049. };
  66050. // Remove all polygons in this BSP tree that are inside the other BSP tree
  66051. // `bsp`.
  66052. Node.prototype.clipTo = function (bsp) {
  66053. this.polygons = bsp.clipPolygons(this.polygons);
  66054. if (this.front)
  66055. this.front.clipTo(bsp);
  66056. if (this.back)
  66057. this.back.clipTo(bsp);
  66058. };
  66059. // Return a list of all polygons in this BSP tree.
  66060. Node.prototype.allPolygons = function () {
  66061. var polygons = this.polygons.slice();
  66062. if (this.front)
  66063. polygons = polygons.concat(this.front.allPolygons());
  66064. if (this.back)
  66065. polygons = polygons.concat(this.back.allPolygons());
  66066. return polygons;
  66067. };
  66068. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  66069. // new polygons are filtered down to the bottom of the tree and become new
  66070. // nodes there. Each set of polygons is partitioned using the first polygon
  66071. // (no heuristic is used to pick a good split).
  66072. Node.prototype.build = function (polygons) {
  66073. if (!polygons.length)
  66074. return;
  66075. if (!this.plane)
  66076. this.plane = polygons[0].plane.clone();
  66077. var front = new Array(), back = new Array();
  66078. for (var i = 0; i < polygons.length; i++) {
  66079. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  66080. }
  66081. if (front.length) {
  66082. if (!this.front)
  66083. this.front = new Node();
  66084. this.front.build(front);
  66085. }
  66086. if (back.length) {
  66087. if (!this.back)
  66088. this.back = new Node();
  66089. this.back.build(back);
  66090. }
  66091. };
  66092. return Node;
  66093. }());
  66094. var CSG = /** @class */ (function () {
  66095. function CSG() {
  66096. this.polygons = new Array();
  66097. }
  66098. // Convert BABYLON.Mesh to BABYLON.CSG
  66099. CSG.FromMesh = function (mesh) {
  66100. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  66101. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  66102. if (mesh instanceof BABYLON.Mesh) {
  66103. mesh.computeWorldMatrix(true);
  66104. matrix = mesh.getWorldMatrix();
  66105. meshPosition = mesh.position.clone();
  66106. meshRotation = mesh.rotation.clone();
  66107. if (mesh.rotationQuaternion) {
  66108. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  66109. }
  66110. meshScaling = mesh.scaling.clone();
  66111. }
  66112. else {
  66113. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  66114. }
  66115. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  66116. var subMeshes = mesh.subMeshes;
  66117. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  66118. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  66119. vertices = [];
  66120. for (var j = 0; j < 3; j++) {
  66121. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  66122. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  66123. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  66124. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  66125. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  66126. vertex = new Vertex(position, normal, uv);
  66127. vertices.push(vertex);
  66128. }
  66129. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  66130. // To handle the case of degenerated triangle
  66131. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  66132. if (polygon.plane)
  66133. polygons.push(polygon);
  66134. }
  66135. }
  66136. var csg = CSG.FromPolygons(polygons);
  66137. csg.matrix = matrix;
  66138. csg.position = meshPosition;
  66139. csg.rotation = meshRotation;
  66140. csg.scaling = meshScaling;
  66141. csg.rotationQuaternion = meshRotationQuaternion;
  66142. currentCSGMeshId++;
  66143. return csg;
  66144. };
  66145. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  66146. CSG.FromPolygons = function (polygons) {
  66147. var csg = new CSG();
  66148. csg.polygons = polygons;
  66149. return csg;
  66150. };
  66151. CSG.prototype.clone = function () {
  66152. var csg = new CSG();
  66153. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  66154. csg.copyTransformAttributes(this);
  66155. return csg;
  66156. };
  66157. CSG.prototype.union = function (csg) {
  66158. var a = new Node(this.clone().polygons);
  66159. var b = new Node(csg.clone().polygons);
  66160. a.clipTo(b);
  66161. b.clipTo(a);
  66162. b.invert();
  66163. b.clipTo(a);
  66164. b.invert();
  66165. a.build(b.allPolygons());
  66166. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  66167. };
  66168. CSG.prototype.unionInPlace = function (csg) {
  66169. var a = new Node(this.polygons);
  66170. var b = new Node(csg.polygons);
  66171. a.clipTo(b);
  66172. b.clipTo(a);
  66173. b.invert();
  66174. b.clipTo(a);
  66175. b.invert();
  66176. a.build(b.allPolygons());
  66177. this.polygons = a.allPolygons();
  66178. };
  66179. CSG.prototype.subtract = function (csg) {
  66180. var a = new Node(this.clone().polygons);
  66181. var b = new Node(csg.clone().polygons);
  66182. a.invert();
  66183. a.clipTo(b);
  66184. b.clipTo(a);
  66185. b.invert();
  66186. b.clipTo(a);
  66187. b.invert();
  66188. a.build(b.allPolygons());
  66189. a.invert();
  66190. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  66191. };
  66192. CSG.prototype.subtractInPlace = function (csg) {
  66193. var a = new Node(this.polygons);
  66194. var b = new Node(csg.polygons);
  66195. a.invert();
  66196. a.clipTo(b);
  66197. b.clipTo(a);
  66198. b.invert();
  66199. b.clipTo(a);
  66200. b.invert();
  66201. a.build(b.allPolygons());
  66202. a.invert();
  66203. this.polygons = a.allPolygons();
  66204. };
  66205. CSG.prototype.intersect = function (csg) {
  66206. var a = new Node(this.clone().polygons);
  66207. var b = new Node(csg.clone().polygons);
  66208. a.invert();
  66209. b.clipTo(a);
  66210. b.invert();
  66211. a.clipTo(b);
  66212. b.clipTo(a);
  66213. a.build(b.allPolygons());
  66214. a.invert();
  66215. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  66216. };
  66217. CSG.prototype.intersectInPlace = function (csg) {
  66218. var a = new Node(this.polygons);
  66219. var b = new Node(csg.polygons);
  66220. a.invert();
  66221. b.clipTo(a);
  66222. b.invert();
  66223. a.clipTo(b);
  66224. b.clipTo(a);
  66225. a.build(b.allPolygons());
  66226. a.invert();
  66227. this.polygons = a.allPolygons();
  66228. };
  66229. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  66230. // not modified.
  66231. CSG.prototype.inverse = function () {
  66232. var csg = this.clone();
  66233. csg.inverseInPlace();
  66234. return csg;
  66235. };
  66236. CSG.prototype.inverseInPlace = function () {
  66237. this.polygons.map(function (p) { p.flip(); });
  66238. };
  66239. // This is used to keep meshes transformations so they can be restored
  66240. // when we build back a Babylon Mesh
  66241. // NB : All CSG operations are performed in world coordinates
  66242. CSG.prototype.copyTransformAttributes = function (csg) {
  66243. this.matrix = csg.matrix;
  66244. this.position = csg.position;
  66245. this.rotation = csg.rotation;
  66246. this.scaling = csg.scaling;
  66247. this.rotationQuaternion = csg.rotationQuaternion;
  66248. return this;
  66249. };
  66250. // Build Raw mesh from CSG
  66251. // Coordinates here are in world space
  66252. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  66253. var matrix = this.matrix.clone();
  66254. matrix.invert();
  66255. 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;
  66256. if (keepSubMeshes) {
  66257. // Sort Polygons, since subMeshes are indices range
  66258. polygons.sort(function (a, b) {
  66259. if (a.shared.meshId === b.shared.meshId) {
  66260. return a.shared.subMeshId - b.shared.subMeshId;
  66261. }
  66262. else {
  66263. return a.shared.meshId - b.shared.meshId;
  66264. }
  66265. });
  66266. }
  66267. for (var i = 0, il = polygons.length; i < il; i++) {
  66268. polygon = polygons[i];
  66269. // Building SubMeshes
  66270. if (!subMesh_dict[polygon.shared.meshId]) {
  66271. subMesh_dict[polygon.shared.meshId] = {};
  66272. }
  66273. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  66274. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  66275. indexStart: +Infinity,
  66276. indexEnd: -Infinity,
  66277. materialIndex: polygon.shared.materialIndex
  66278. };
  66279. }
  66280. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  66281. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  66282. polygonIndices[0] = 0;
  66283. polygonIndices[1] = j - 1;
  66284. polygonIndices[2] = j;
  66285. for (var k = 0; k < 3; k++) {
  66286. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  66287. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  66288. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  66289. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  66290. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  66291. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  66292. // Check if 2 points can be merged
  66293. if (!(typeof vertex_idx !== 'undefined' &&
  66294. normals[vertex_idx * 3] === localNormal.x &&
  66295. normals[vertex_idx * 3 + 1] === localNormal.y &&
  66296. normals[vertex_idx * 3 + 2] === localNormal.z &&
  66297. uvs[vertex_idx * 2] === uv.x &&
  66298. uvs[vertex_idx * 2 + 1] === uv.y)) {
  66299. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  66300. uvs.push(uv.x, uv.y);
  66301. normals.push(normal.x, normal.y, normal.z);
  66302. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  66303. }
  66304. indices.push(vertex_idx);
  66305. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  66306. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  66307. currentIndex++;
  66308. }
  66309. }
  66310. }
  66311. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  66312. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  66313. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  66314. mesh.setIndices(indices, null);
  66315. if (keepSubMeshes) {
  66316. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  66317. var materialIndexOffset = 0, materialMaxIndex;
  66318. mesh.subMeshes = new Array();
  66319. for (var m in subMesh_dict) {
  66320. materialMaxIndex = -1;
  66321. for (var sm in subMesh_dict[m]) {
  66322. subMesh_obj = subMesh_dict[m][sm];
  66323. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  66324. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  66325. }
  66326. materialIndexOffset += ++materialMaxIndex;
  66327. }
  66328. }
  66329. return mesh;
  66330. };
  66331. // Build Mesh from CSG taking material and transforms into account
  66332. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  66333. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  66334. mesh.material = material;
  66335. mesh.position.copyFrom(this.position);
  66336. mesh.rotation.copyFrom(this.rotation);
  66337. if (this.rotationQuaternion) {
  66338. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  66339. }
  66340. mesh.scaling.copyFrom(this.scaling);
  66341. mesh.computeWorldMatrix(true);
  66342. return mesh;
  66343. };
  66344. return CSG;
  66345. }());
  66346. BABYLON.CSG = CSG;
  66347. })(BABYLON || (BABYLON = {}));
  66348. //# sourceMappingURL=babylon.csg.js.map
  66349. var BABYLON;
  66350. (function (BABYLON) {
  66351. var LensFlare = /** @class */ (function () {
  66352. function LensFlare(size, position, color, imgUrl, system) {
  66353. this.size = size;
  66354. this.position = position;
  66355. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  66356. this.color = color || new BABYLON.Color3(1, 1, 1);
  66357. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  66358. this._system = system;
  66359. system.lensFlares.push(this);
  66360. }
  66361. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  66362. return new LensFlare(size, position, color, imgUrl, system);
  66363. };
  66364. LensFlare.prototype.dispose = function () {
  66365. if (this.texture) {
  66366. this.texture.dispose();
  66367. }
  66368. // Remove from scene
  66369. var index = this._system.lensFlares.indexOf(this);
  66370. this._system.lensFlares.splice(index, 1);
  66371. };
  66372. ;
  66373. return LensFlare;
  66374. }());
  66375. BABYLON.LensFlare = LensFlare;
  66376. })(BABYLON || (BABYLON = {}));
  66377. //# sourceMappingURL=babylon.lensFlare.js.map
  66378. var BABYLON;
  66379. (function (BABYLON) {
  66380. var LensFlareSystem = /** @class */ (function () {
  66381. function LensFlareSystem(name, emitter, scene) {
  66382. this.name = name;
  66383. this.lensFlares = new Array();
  66384. this.borderLimit = 300;
  66385. this.viewportBorder = 0;
  66386. this.layerMask = 0x0FFFFFFF;
  66387. this._vertexBuffers = {};
  66388. this._isEnabled = true;
  66389. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  66390. this._emitter = emitter;
  66391. this.id = name;
  66392. scene.lensFlareSystems.push(this);
  66393. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  66394. var engine = scene.getEngine();
  66395. // VBO
  66396. var vertices = [];
  66397. vertices.push(1, 1);
  66398. vertices.push(-1, 1);
  66399. vertices.push(-1, -1);
  66400. vertices.push(1, -1);
  66401. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  66402. // Indices
  66403. var indices = [];
  66404. indices.push(0);
  66405. indices.push(1);
  66406. indices.push(2);
  66407. indices.push(0);
  66408. indices.push(2);
  66409. indices.push(3);
  66410. this._indexBuffer = engine.createIndexBuffer(indices);
  66411. // Effects
  66412. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  66413. }
  66414. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  66415. get: function () {
  66416. return this._isEnabled;
  66417. },
  66418. set: function (value) {
  66419. this._isEnabled = value;
  66420. },
  66421. enumerable: true,
  66422. configurable: true
  66423. });
  66424. LensFlareSystem.prototype.getScene = function () {
  66425. return this._scene;
  66426. };
  66427. LensFlareSystem.prototype.getEmitter = function () {
  66428. return this._emitter;
  66429. };
  66430. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  66431. this._emitter = newEmitter;
  66432. };
  66433. LensFlareSystem.prototype.getEmitterPosition = function () {
  66434. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  66435. };
  66436. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  66437. var position = this.getEmitterPosition();
  66438. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  66439. this._positionX = position.x;
  66440. this._positionY = position.y;
  66441. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  66442. if (this.viewportBorder > 0) {
  66443. globalViewport.x -= this.viewportBorder;
  66444. globalViewport.y -= this.viewportBorder;
  66445. globalViewport.width += this.viewportBorder * 2;
  66446. globalViewport.height += this.viewportBorder * 2;
  66447. position.x += this.viewportBorder;
  66448. position.y += this.viewportBorder;
  66449. this._positionX += this.viewportBorder;
  66450. this._positionY += this.viewportBorder;
  66451. }
  66452. if (position.z > 0) {
  66453. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  66454. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  66455. return true;
  66456. }
  66457. return true;
  66458. }
  66459. return false;
  66460. };
  66461. LensFlareSystem.prototype._isVisible = function () {
  66462. if (!this._isEnabled || !this._scene.activeCamera) {
  66463. return false;
  66464. }
  66465. var emitterPosition = this.getEmitterPosition();
  66466. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  66467. var distance = direction.length();
  66468. direction.normalize();
  66469. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  66470. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  66471. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  66472. };
  66473. LensFlareSystem.prototype.render = function () {
  66474. if (!this._effect.isReady() || !this._scene.activeCamera)
  66475. return false;
  66476. var engine = this._scene.getEngine();
  66477. var viewport = this._scene.activeCamera.viewport;
  66478. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  66479. // Position
  66480. if (!this.computeEffectivePosition(globalViewport)) {
  66481. return false;
  66482. }
  66483. // Visibility
  66484. if (!this._isVisible()) {
  66485. return false;
  66486. }
  66487. // Intensity
  66488. var awayX;
  66489. var awayY;
  66490. if (this._positionX < this.borderLimit + globalViewport.x) {
  66491. awayX = this.borderLimit + globalViewport.x - this._positionX;
  66492. }
  66493. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  66494. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  66495. }
  66496. else {
  66497. awayX = 0;
  66498. }
  66499. if (this._positionY < this.borderLimit + globalViewport.y) {
  66500. awayY = this.borderLimit + globalViewport.y - this._positionY;
  66501. }
  66502. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  66503. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  66504. }
  66505. else {
  66506. awayY = 0;
  66507. }
  66508. var away = (awayX > awayY) ? awayX : awayY;
  66509. away -= this.viewportBorder;
  66510. if (away > this.borderLimit) {
  66511. away = this.borderLimit;
  66512. }
  66513. var intensity = 1.0 - (away / this.borderLimit);
  66514. if (intensity < 0) {
  66515. return false;
  66516. }
  66517. if (intensity > 1.0) {
  66518. intensity = 1.0;
  66519. }
  66520. if (this.viewportBorder > 0) {
  66521. globalViewport.x += this.viewportBorder;
  66522. globalViewport.y += this.viewportBorder;
  66523. globalViewport.width -= this.viewportBorder * 2;
  66524. globalViewport.height -= this.viewportBorder * 2;
  66525. this._positionX -= this.viewportBorder;
  66526. this._positionY -= this.viewportBorder;
  66527. }
  66528. // Position
  66529. var centerX = globalViewport.x + globalViewport.width / 2;
  66530. var centerY = globalViewport.y + globalViewport.height / 2;
  66531. var distX = centerX - this._positionX;
  66532. var distY = centerY - this._positionY;
  66533. // Effects
  66534. engine.enableEffect(this._effect);
  66535. engine.setState(false);
  66536. engine.setDepthBuffer(false);
  66537. // VBOs
  66538. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  66539. // Flares
  66540. for (var index = 0; index < this.lensFlares.length; index++) {
  66541. var flare = this.lensFlares[index];
  66542. engine.setAlphaMode(flare.alphaMode);
  66543. var x = centerX - (distX * flare.position);
  66544. var y = centerY - (distY * flare.position);
  66545. var cw = flare.size;
  66546. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  66547. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  66548. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  66549. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  66550. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  66551. // Texture
  66552. this._effect.setTexture("textureSampler", flare.texture);
  66553. // Color
  66554. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  66555. // Draw order
  66556. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  66557. }
  66558. engine.setDepthBuffer(true);
  66559. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  66560. return true;
  66561. };
  66562. LensFlareSystem.prototype.dispose = function () {
  66563. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66564. if (vertexBuffer) {
  66565. vertexBuffer.dispose();
  66566. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  66567. }
  66568. if (this._indexBuffer) {
  66569. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  66570. this._indexBuffer = null;
  66571. }
  66572. while (this.lensFlares.length) {
  66573. this.lensFlares[0].dispose();
  66574. }
  66575. // Remove from scene
  66576. var index = this._scene.lensFlareSystems.indexOf(this);
  66577. this._scene.lensFlareSystems.splice(index, 1);
  66578. };
  66579. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  66580. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  66581. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  66582. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  66583. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  66584. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  66585. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  66586. var parsedFlare = parsedLensFlareSystem.flares[index];
  66587. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  66588. }
  66589. return lensFlareSystem;
  66590. };
  66591. LensFlareSystem.prototype.serialize = function () {
  66592. var serializationObject = {};
  66593. serializationObject.id = this.id;
  66594. serializationObject.name = this.name;
  66595. serializationObject.emitterId = this.getEmitter().id;
  66596. serializationObject.borderLimit = this.borderLimit;
  66597. serializationObject.flares = [];
  66598. for (var index = 0; index < this.lensFlares.length; index++) {
  66599. var flare = this.lensFlares[index];
  66600. serializationObject.flares.push({
  66601. size: flare.size,
  66602. position: flare.position,
  66603. color: flare.color.asArray(),
  66604. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  66605. });
  66606. }
  66607. return serializationObject;
  66608. };
  66609. return LensFlareSystem;
  66610. }());
  66611. BABYLON.LensFlareSystem = LensFlareSystem;
  66612. })(BABYLON || (BABYLON = {}));
  66613. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  66614. var BABYLON;
  66615. (function (BABYLON) {
  66616. /**
  66617. * This is a holder class for the physics joint created by the physics plugin.
  66618. * It holds a set of functions to control the underlying joint.
  66619. */
  66620. var PhysicsJoint = /** @class */ (function () {
  66621. function PhysicsJoint(type, jointData) {
  66622. this.type = type;
  66623. this.jointData = jointData;
  66624. jointData.nativeParams = jointData.nativeParams || {};
  66625. }
  66626. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  66627. get: function () {
  66628. return this._physicsJoint;
  66629. },
  66630. set: function (newJoint) {
  66631. if (this._physicsJoint) {
  66632. //remove from the wolrd
  66633. }
  66634. this._physicsJoint = newJoint;
  66635. },
  66636. enumerable: true,
  66637. configurable: true
  66638. });
  66639. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  66640. set: function (physicsPlugin) {
  66641. this._physicsPlugin = physicsPlugin;
  66642. },
  66643. enumerable: true,
  66644. configurable: true
  66645. });
  66646. /**
  66647. * Execute a function that is physics-plugin specific.
  66648. * @param {Function} func the function that will be executed.
  66649. * It accepts two parameters: the physics world and the physics joint.
  66650. */
  66651. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  66652. func(this._physicsPlugin.world, this._physicsJoint);
  66653. };
  66654. //TODO check if the native joints are the same
  66655. //Joint Types
  66656. PhysicsJoint.DistanceJoint = 0;
  66657. PhysicsJoint.HingeJoint = 1;
  66658. PhysicsJoint.BallAndSocketJoint = 2;
  66659. PhysicsJoint.WheelJoint = 3;
  66660. PhysicsJoint.SliderJoint = 4;
  66661. //OIMO
  66662. PhysicsJoint.PrismaticJoint = 5;
  66663. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  66664. PhysicsJoint.UniversalJoint = 6;
  66665. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  66666. //Cannon
  66667. //Similar to a Ball-Joint. Different in params
  66668. PhysicsJoint.PointToPointJoint = 8;
  66669. //Cannon only at the moment
  66670. PhysicsJoint.SpringJoint = 9;
  66671. PhysicsJoint.LockJoint = 10;
  66672. return PhysicsJoint;
  66673. }());
  66674. BABYLON.PhysicsJoint = PhysicsJoint;
  66675. /**
  66676. * A class representing a physics distance joint.
  66677. */
  66678. var DistanceJoint = /** @class */ (function (_super) {
  66679. __extends(DistanceJoint, _super);
  66680. function DistanceJoint(jointData) {
  66681. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  66682. }
  66683. /**
  66684. * Update the predefined distance.
  66685. */
  66686. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  66687. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  66688. };
  66689. return DistanceJoint;
  66690. }(PhysicsJoint));
  66691. BABYLON.DistanceJoint = DistanceJoint;
  66692. var MotorEnabledJoint = /** @class */ (function (_super) {
  66693. __extends(MotorEnabledJoint, _super);
  66694. function MotorEnabledJoint(type, jointData) {
  66695. return _super.call(this, type, jointData) || this;
  66696. }
  66697. /**
  66698. * Set the motor values.
  66699. * Attention, this function is plugin specific. Engines won't react 100% the same.
  66700. * @param {number} force the force to apply
  66701. * @param {number} maxForce max force for this motor.
  66702. */
  66703. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  66704. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  66705. };
  66706. /**
  66707. * Set the motor's limits.
  66708. * Attention, this function is plugin specific. Engines won't react 100% the same.
  66709. */
  66710. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  66711. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  66712. };
  66713. return MotorEnabledJoint;
  66714. }(PhysicsJoint));
  66715. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  66716. /**
  66717. * This class represents a single hinge physics joint
  66718. */
  66719. var HingeJoint = /** @class */ (function (_super) {
  66720. __extends(HingeJoint, _super);
  66721. function HingeJoint(jointData) {
  66722. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  66723. }
  66724. /**
  66725. * Set the motor values.
  66726. * Attention, this function is plugin specific. Engines won't react 100% the same.
  66727. * @param {number} force the force to apply
  66728. * @param {number} maxForce max force for this motor.
  66729. */
  66730. HingeJoint.prototype.setMotor = function (force, maxForce) {
  66731. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  66732. };
  66733. /**
  66734. * Set the motor's limits.
  66735. * Attention, this function is plugin specific. Engines won't react 100% the same.
  66736. */
  66737. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  66738. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  66739. };
  66740. return HingeJoint;
  66741. }(MotorEnabledJoint));
  66742. BABYLON.HingeJoint = HingeJoint;
  66743. /**
  66744. * This class represents a dual hinge physics joint (same as wheel joint)
  66745. */
  66746. var Hinge2Joint = /** @class */ (function (_super) {
  66747. __extends(Hinge2Joint, _super);
  66748. function Hinge2Joint(jointData) {
  66749. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  66750. }
  66751. /**
  66752. * Set the motor values.
  66753. * Attention, this function is plugin specific. Engines won't react 100% the same.
  66754. * @param {number} force the force to apply
  66755. * @param {number} maxForce max force for this motor.
  66756. * @param {motorIndex} the motor's index, 0 or 1.
  66757. */
  66758. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  66759. if (motorIndex === void 0) { motorIndex = 0; }
  66760. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  66761. };
  66762. /**
  66763. * Set the motor limits.
  66764. * Attention, this function is plugin specific. Engines won't react 100% the same.
  66765. * @param {number} upperLimit the upper limit
  66766. * @param {number} lowerLimit lower limit
  66767. * @param {motorIndex} the motor's index, 0 or 1.
  66768. */
  66769. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  66770. if (motorIndex === void 0) { motorIndex = 0; }
  66771. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  66772. };
  66773. return Hinge2Joint;
  66774. }(MotorEnabledJoint));
  66775. BABYLON.Hinge2Joint = Hinge2Joint;
  66776. })(BABYLON || (BABYLON = {}));
  66777. //# sourceMappingURL=babylon.physicsJoint.js.map
  66778. var BABYLON;
  66779. (function (BABYLON) {
  66780. var PhysicsImpostor = /** @class */ (function () {
  66781. function PhysicsImpostor(object, type, _options, _scene) {
  66782. if (_options === void 0) { _options = { mass: 0 }; }
  66783. var _this = this;
  66784. this.object = object;
  66785. this.type = type;
  66786. this._options = _options;
  66787. this._scene = _scene;
  66788. this._bodyUpdateRequired = false;
  66789. this._onBeforePhysicsStepCallbacks = new Array();
  66790. this._onAfterPhysicsStepCallbacks = new Array();
  66791. this._onPhysicsCollideCallbacks = [];
  66792. this._deltaPosition = BABYLON.Vector3.Zero();
  66793. this._isDisposed = false;
  66794. //temp variables for parent rotation calculations
  66795. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  66796. this._tmpQuat = new BABYLON.Quaternion();
  66797. this._tmpQuat2 = new BABYLON.Quaternion();
  66798. /**
  66799. * this function is executed by the physics engine.
  66800. */
  66801. this.beforeStep = function () {
  66802. if (!_this._physicsEngine) {
  66803. return;
  66804. }
  66805. _this.object.translate(_this._deltaPosition, -1);
  66806. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  66807. _this.object.computeWorldMatrix(false);
  66808. if (_this.object.parent && _this.object.rotationQuaternion) {
  66809. _this.getParentsRotation();
  66810. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  66811. }
  66812. else {
  66813. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  66814. }
  66815. if (!_this._options.disableBidirectionalTransformation) {
  66816. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  66817. }
  66818. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  66819. func(_this);
  66820. });
  66821. };
  66822. /**
  66823. * this function is executed by the physics engine.
  66824. */
  66825. this.afterStep = function () {
  66826. if (!_this._physicsEngine) {
  66827. return;
  66828. }
  66829. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  66830. func(_this);
  66831. });
  66832. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  66833. // object has now its world rotation. needs to be converted to local.
  66834. if (_this.object.parent && _this.object.rotationQuaternion) {
  66835. _this.getParentsRotation();
  66836. _this._tmpQuat.conjugateInPlace();
  66837. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  66838. }
  66839. // take the position set and make it the absolute position of this object.
  66840. _this.object.setAbsolutePosition(_this.object.position);
  66841. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  66842. _this.object.translate(_this._deltaPosition, 1);
  66843. };
  66844. /**
  66845. * Legacy collision detection event support
  66846. */
  66847. this.onCollideEvent = null;
  66848. //event and body object due to cannon's event-based architecture.
  66849. this.onCollide = function (e) {
  66850. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  66851. return;
  66852. }
  66853. if (!_this._physicsEngine) {
  66854. return;
  66855. }
  66856. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  66857. if (otherImpostor) {
  66858. // Legacy collision detection event support
  66859. if (_this.onCollideEvent) {
  66860. _this.onCollideEvent(_this, otherImpostor);
  66861. }
  66862. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  66863. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  66864. }).forEach(function (obj) {
  66865. obj.callback(_this, otherImpostor);
  66866. });
  66867. }
  66868. };
  66869. //sanity check!
  66870. if (!this.object) {
  66871. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  66872. return;
  66873. }
  66874. //legacy support for old syntax.
  66875. if (!this._scene && object.getScene) {
  66876. this._scene = object.getScene();
  66877. }
  66878. if (!this._scene) {
  66879. return;
  66880. }
  66881. this._physicsEngine = this._scene.getPhysicsEngine();
  66882. if (!this._physicsEngine) {
  66883. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  66884. }
  66885. else {
  66886. //set the object's quaternion, if not set
  66887. if (!this.object.rotationQuaternion) {
  66888. if (this.object.rotation) {
  66889. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  66890. }
  66891. else {
  66892. this.object.rotationQuaternion = new BABYLON.Quaternion();
  66893. }
  66894. }
  66895. //default options params
  66896. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  66897. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  66898. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  66899. this._joints = [];
  66900. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  66901. if (!this.object.parent || this._options.ignoreParent) {
  66902. this._init();
  66903. }
  66904. else if (this.object.parent.physicsImpostor) {
  66905. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  66906. }
  66907. }
  66908. }
  66909. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  66910. get: function () {
  66911. return this._isDisposed;
  66912. },
  66913. enumerable: true,
  66914. configurable: true
  66915. });
  66916. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  66917. get: function () {
  66918. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  66919. },
  66920. set: function (value) {
  66921. this.setMass(value);
  66922. },
  66923. enumerable: true,
  66924. configurable: true
  66925. });
  66926. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  66927. get: function () {
  66928. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  66929. },
  66930. set: function (value) {
  66931. if (!this._physicsEngine) {
  66932. return;
  66933. }
  66934. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  66935. },
  66936. enumerable: true,
  66937. configurable: true
  66938. });
  66939. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  66940. get: function () {
  66941. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  66942. },
  66943. set: function (value) {
  66944. if (!this._physicsEngine) {
  66945. return;
  66946. }
  66947. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  66948. },
  66949. enumerable: true,
  66950. configurable: true
  66951. });
  66952. /**
  66953. * This function will completly initialize this impostor.
  66954. * It will create a new body - but only if this mesh has no parent.
  66955. * If it has, this impostor will not be used other than to define the impostor
  66956. * of the child mesh.
  66957. */
  66958. PhysicsImpostor.prototype._init = function () {
  66959. if (!this._physicsEngine) {
  66960. return;
  66961. }
  66962. this._physicsEngine.removeImpostor(this);
  66963. this.physicsBody = null;
  66964. this._parent = this._parent || this._getPhysicsParent();
  66965. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  66966. this._physicsEngine.addImpostor(this);
  66967. }
  66968. };
  66969. PhysicsImpostor.prototype._getPhysicsParent = function () {
  66970. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  66971. var parentMesh = this.object.parent;
  66972. return parentMesh.physicsImpostor;
  66973. }
  66974. return null;
  66975. };
  66976. /**
  66977. * Should a new body be generated.
  66978. */
  66979. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  66980. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  66981. };
  66982. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  66983. this.forceUpdate();
  66984. };
  66985. /**
  66986. * Force a regeneration of this or the parent's impostor's body.
  66987. * Use under cautious - This will remove all joints already implemented.
  66988. */
  66989. PhysicsImpostor.prototype.forceUpdate = function () {
  66990. this._init();
  66991. if (this.parent && !this._options.ignoreParent) {
  66992. this.parent.forceUpdate();
  66993. }
  66994. };
  66995. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  66996. /*public get mesh(): AbstractMesh {
  66997. return this._mesh;
  66998. }*/
  66999. /**
  67000. * Gets the body that holds this impostor. Either its own, or its parent.
  67001. */
  67002. get: function () {
  67003. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  67004. },
  67005. /**
  67006. * Set the physics body. Used mainly by the physics engine/plugin
  67007. */
  67008. set: function (physicsBody) {
  67009. if (this._physicsBody && this._physicsEngine) {
  67010. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  67011. }
  67012. this._physicsBody = physicsBody;
  67013. this.resetUpdateFlags();
  67014. },
  67015. enumerable: true,
  67016. configurable: true
  67017. });
  67018. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  67019. get: function () {
  67020. return !this._options.ignoreParent && this._parent ? this._parent : null;
  67021. },
  67022. set: function (value) {
  67023. this._parent = value;
  67024. },
  67025. enumerable: true,
  67026. configurable: true
  67027. });
  67028. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  67029. this._bodyUpdateRequired = false;
  67030. };
  67031. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  67032. if (this.object.getBoundingInfo) {
  67033. var q = this.object.rotationQuaternion;
  67034. //reset rotation
  67035. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  67036. //calculate the world matrix with no rotation
  67037. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  67038. var boundingInfo = this.object.getBoundingInfo();
  67039. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  67040. //bring back the rotation
  67041. this.object.rotationQuaternion = q;
  67042. //calculate the world matrix with the new rotation
  67043. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  67044. return size;
  67045. }
  67046. else {
  67047. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  67048. }
  67049. };
  67050. PhysicsImpostor.prototype.getObjectCenter = function () {
  67051. if (this.object.getBoundingInfo) {
  67052. var boundingInfo = this.object.getBoundingInfo();
  67053. return boundingInfo.boundingBox.centerWorld;
  67054. }
  67055. else {
  67056. return this.object.position;
  67057. }
  67058. };
  67059. /**
  67060. * Get a specific parametes from the options parameter.
  67061. */
  67062. PhysicsImpostor.prototype.getParam = function (paramName) {
  67063. return this._options[paramName];
  67064. };
  67065. /**
  67066. * Sets a specific parameter in the options given to the physics plugin
  67067. */
  67068. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  67069. this._options[paramName] = value;
  67070. this._bodyUpdateRequired = true;
  67071. };
  67072. /**
  67073. * Specifically change the body's mass option. Won't recreate the physics body object
  67074. */
  67075. PhysicsImpostor.prototype.setMass = function (mass) {
  67076. if (this.getParam("mass") !== mass) {
  67077. this.setParam("mass", mass);
  67078. }
  67079. if (this._physicsEngine) {
  67080. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  67081. }
  67082. };
  67083. PhysicsImpostor.prototype.getLinearVelocity = function () {
  67084. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  67085. };
  67086. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  67087. if (this._physicsEngine) {
  67088. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  67089. }
  67090. };
  67091. PhysicsImpostor.prototype.getAngularVelocity = function () {
  67092. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  67093. };
  67094. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  67095. if (this._physicsEngine) {
  67096. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  67097. }
  67098. };
  67099. /**
  67100. * Execute a function with the physics plugin native code.
  67101. * Provide a function the will have two variables - the world object and the physics body object.
  67102. */
  67103. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  67104. if (this._physicsEngine) {
  67105. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  67106. }
  67107. };
  67108. /**
  67109. * Register a function that will be executed before the physics world is stepping forward.
  67110. */
  67111. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  67112. this._onBeforePhysicsStepCallbacks.push(func);
  67113. };
  67114. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  67115. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  67116. if (index > -1) {
  67117. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  67118. }
  67119. else {
  67120. BABYLON.Tools.Warn("Function to remove was not found");
  67121. }
  67122. };
  67123. /**
  67124. * Register a function that will be executed after the physics step
  67125. */
  67126. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  67127. this._onAfterPhysicsStepCallbacks.push(func);
  67128. };
  67129. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  67130. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  67131. if (index > -1) {
  67132. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  67133. }
  67134. else {
  67135. BABYLON.Tools.Warn("Function to remove was not found");
  67136. }
  67137. };
  67138. /**
  67139. * register a function that will be executed when this impostor collides against a different body.
  67140. */
  67141. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  67142. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  67143. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  67144. };
  67145. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  67146. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  67147. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  67148. if (index > -1) {
  67149. this._onPhysicsCollideCallbacks.splice(index, 1);
  67150. }
  67151. else {
  67152. BABYLON.Tools.Warn("Function to remove was not found");
  67153. }
  67154. };
  67155. PhysicsImpostor.prototype.getParentsRotation = function () {
  67156. var parent = this.object.parent;
  67157. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  67158. while (parent) {
  67159. if (parent.rotationQuaternion) {
  67160. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  67161. }
  67162. else {
  67163. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  67164. }
  67165. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  67166. parent = parent.parent;
  67167. }
  67168. return this._tmpQuat;
  67169. };
  67170. /**
  67171. * Apply a force
  67172. */
  67173. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  67174. if (this._physicsEngine) {
  67175. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  67176. }
  67177. return this;
  67178. };
  67179. /**
  67180. * Apply an impulse
  67181. */
  67182. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  67183. if (this._physicsEngine) {
  67184. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  67185. }
  67186. return this;
  67187. };
  67188. /**
  67189. * A help function to create a joint.
  67190. */
  67191. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  67192. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  67193. this.addJoint(otherImpostor, joint);
  67194. return this;
  67195. };
  67196. /**
  67197. * Add a joint to this impostor with a different impostor.
  67198. */
  67199. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  67200. this._joints.push({
  67201. otherImpostor: otherImpostor,
  67202. joint: joint
  67203. });
  67204. if (this._physicsEngine) {
  67205. this._physicsEngine.addJoint(this, otherImpostor, joint);
  67206. }
  67207. return this;
  67208. };
  67209. /**
  67210. * Will keep this body still, in a sleep mode.
  67211. */
  67212. PhysicsImpostor.prototype.sleep = function () {
  67213. if (this._physicsEngine) {
  67214. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  67215. }
  67216. return this;
  67217. };
  67218. /**
  67219. * Wake the body up.
  67220. */
  67221. PhysicsImpostor.prototype.wakeUp = function () {
  67222. if (this._physicsEngine) {
  67223. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  67224. }
  67225. return this;
  67226. };
  67227. PhysicsImpostor.prototype.clone = function (newObject) {
  67228. if (!newObject)
  67229. return null;
  67230. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  67231. };
  67232. PhysicsImpostor.prototype.dispose = function () {
  67233. var _this = this;
  67234. //no dispose if no physics engine is available.
  67235. if (!this._physicsEngine) {
  67236. return;
  67237. }
  67238. this._joints.forEach(function (j) {
  67239. if (_this._physicsEngine) {
  67240. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  67241. }
  67242. });
  67243. //dispose the physics body
  67244. this._physicsEngine.removeImpostor(this);
  67245. if (this.parent) {
  67246. this.parent.forceUpdate();
  67247. }
  67248. else {
  67249. /*this._object.getChildMeshes().forEach(function(mesh) {
  67250. if (mesh.physicsImpostor) {
  67251. if (disposeChildren) {
  67252. mesh.physicsImpostor.dispose();
  67253. mesh.physicsImpostor = null;
  67254. }
  67255. }
  67256. })*/
  67257. }
  67258. this._isDisposed = true;
  67259. };
  67260. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  67261. this._deltaPosition.copyFrom(position);
  67262. };
  67263. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  67264. if (!this._deltaRotation) {
  67265. this._deltaRotation = new BABYLON.Quaternion();
  67266. }
  67267. this._deltaRotation.copyFrom(rotation);
  67268. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  67269. };
  67270. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  67271. if (this._physicsEngine) {
  67272. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  67273. }
  67274. return this;
  67275. };
  67276. PhysicsImpostor.prototype.getRadius = function () {
  67277. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  67278. };
  67279. /**
  67280. * Sync a bone with this impostor
  67281. * @param bone The bone to sync to the impostor.
  67282. * @param boneMesh The mesh that the bone is influencing.
  67283. * @param jointPivot The pivot of the joint / bone in local space.
  67284. * @param distToJoint Optional distance from the impostor to the joint.
  67285. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  67286. */
  67287. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  67288. var tempVec = PhysicsImpostor._tmpVecs[0];
  67289. var mesh = this.object;
  67290. if (mesh.rotationQuaternion) {
  67291. if (adjustRotation) {
  67292. var tempQuat = PhysicsImpostor._tmpQuat;
  67293. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  67294. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  67295. }
  67296. else {
  67297. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  67298. }
  67299. }
  67300. tempVec.x = 0;
  67301. tempVec.y = 0;
  67302. tempVec.z = 0;
  67303. if (jointPivot) {
  67304. tempVec.x = jointPivot.x;
  67305. tempVec.y = jointPivot.y;
  67306. tempVec.z = jointPivot.z;
  67307. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  67308. if (distToJoint === undefined || distToJoint === null) {
  67309. distToJoint = jointPivot.length();
  67310. }
  67311. tempVec.x *= distToJoint;
  67312. tempVec.y *= distToJoint;
  67313. tempVec.z *= distToJoint;
  67314. }
  67315. if (bone.getParent()) {
  67316. tempVec.addInPlace(mesh.getAbsolutePosition());
  67317. bone.setAbsolutePosition(tempVec, boneMesh);
  67318. }
  67319. else {
  67320. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  67321. boneMesh.position.x -= tempVec.x;
  67322. boneMesh.position.y -= tempVec.y;
  67323. boneMesh.position.z -= tempVec.z;
  67324. }
  67325. };
  67326. /**
  67327. * Sync impostor to a bone
  67328. * @param bone The bone that the impostor will be synced to.
  67329. * @param boneMesh The mesh that the bone is influencing.
  67330. * @param jointPivot The pivot of the joint / bone in local space.
  67331. * @param distToJoint Optional distance from the impostor to the joint.
  67332. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  67333. * @param boneAxis Optional vector3 axis the bone is aligned with
  67334. */
  67335. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  67336. var mesh = this.object;
  67337. if (mesh.rotationQuaternion) {
  67338. if (adjustRotation) {
  67339. var tempQuat = PhysicsImpostor._tmpQuat;
  67340. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  67341. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  67342. }
  67343. else {
  67344. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  67345. }
  67346. }
  67347. var pos = PhysicsImpostor._tmpVecs[0];
  67348. var boneDir = PhysicsImpostor._tmpVecs[1];
  67349. if (!boneAxis) {
  67350. boneAxis = PhysicsImpostor._tmpVecs[2];
  67351. boneAxis.x = 0;
  67352. boneAxis.y = 1;
  67353. boneAxis.z = 0;
  67354. }
  67355. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  67356. bone.getAbsolutePositionToRef(boneMesh, pos);
  67357. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  67358. distToJoint = jointPivot.length();
  67359. }
  67360. if (distToJoint !== undefined && distToJoint !== null) {
  67361. pos.x += boneDir.x * distToJoint;
  67362. pos.y += boneDir.y * distToJoint;
  67363. pos.z += boneDir.z * distToJoint;
  67364. }
  67365. mesh.setAbsolutePosition(pos);
  67366. };
  67367. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  67368. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  67369. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67370. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  67371. //Impostor types
  67372. PhysicsImpostor.NoImpostor = 0;
  67373. PhysicsImpostor.SphereImpostor = 1;
  67374. PhysicsImpostor.BoxImpostor = 2;
  67375. PhysicsImpostor.PlaneImpostor = 3;
  67376. PhysicsImpostor.MeshImpostor = 4;
  67377. PhysicsImpostor.CylinderImpostor = 7;
  67378. PhysicsImpostor.ParticleImpostor = 8;
  67379. PhysicsImpostor.HeightmapImpostor = 9;
  67380. return PhysicsImpostor;
  67381. }());
  67382. BABYLON.PhysicsImpostor = PhysicsImpostor;
  67383. })(BABYLON || (BABYLON = {}));
  67384. //# sourceMappingURL=babylon.physicsImpostor.js.map
  67385. var BABYLON;
  67386. (function (BABYLON) {
  67387. var PhysicsEngine = /** @class */ (function () {
  67388. function PhysicsEngine(gravity, _physicsPlugin) {
  67389. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  67390. this._physicsPlugin = _physicsPlugin;
  67391. //new methods and parameters
  67392. this._impostors = [];
  67393. this._joints = [];
  67394. if (!this._physicsPlugin.isSupported()) {
  67395. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  67396. + "Please make sure it is included.");
  67397. }
  67398. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  67399. this.setGravity(gravity);
  67400. this.setTimeStep();
  67401. }
  67402. PhysicsEngine.prototype.setGravity = function (gravity) {
  67403. this.gravity = gravity;
  67404. this._physicsPlugin.setGravity(this.gravity);
  67405. };
  67406. /**
  67407. * Set the time step of the physics engine.
  67408. * default is 1/60.
  67409. * To slow it down, enter 1/600 for example.
  67410. * To speed it up, 1/30
  67411. * @param {number} newTimeStep the new timestep to apply to this world.
  67412. */
  67413. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  67414. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  67415. this._physicsPlugin.setTimeStep(newTimeStep);
  67416. };
  67417. /**
  67418. * Get the time step of the physics engine.
  67419. */
  67420. PhysicsEngine.prototype.getTimeStep = function () {
  67421. return this._physicsPlugin.getTimeStep();
  67422. };
  67423. PhysicsEngine.prototype.dispose = function () {
  67424. this._impostors.forEach(function (impostor) {
  67425. impostor.dispose();
  67426. });
  67427. this._physicsPlugin.dispose();
  67428. };
  67429. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  67430. return this._physicsPlugin.name;
  67431. };
  67432. /**
  67433. * Adding a new impostor for the impostor tracking.
  67434. * This will be done by the impostor itself.
  67435. * @param {PhysicsImpostor} impostor the impostor to add
  67436. */
  67437. PhysicsEngine.prototype.addImpostor = function (impostor) {
  67438. impostor.uniqueId = this._impostors.push(impostor);
  67439. //if no parent, generate the body
  67440. if (!impostor.parent) {
  67441. this._physicsPlugin.generatePhysicsBody(impostor);
  67442. }
  67443. };
  67444. /**
  67445. * Remove an impostor from the engine.
  67446. * This impostor and its mesh will not longer be updated by the physics engine.
  67447. * @param {PhysicsImpostor} impostor the impostor to remove
  67448. */
  67449. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  67450. var index = this._impostors.indexOf(impostor);
  67451. if (index > -1) {
  67452. var removed = this._impostors.splice(index, 1);
  67453. //Is it needed?
  67454. if (removed.length) {
  67455. //this will also remove it from the world.
  67456. removed[0].physicsBody = null;
  67457. }
  67458. }
  67459. };
  67460. /**
  67461. * Add a joint to the physics engine
  67462. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  67463. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  67464. * @param {PhysicsJoint} the joint that will connect both impostors.
  67465. */
  67466. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  67467. var impostorJoint = {
  67468. mainImpostor: mainImpostor,
  67469. connectedImpostor: connectedImpostor,
  67470. joint: joint
  67471. };
  67472. joint.physicsPlugin = this._physicsPlugin;
  67473. this._joints.push(impostorJoint);
  67474. this._physicsPlugin.generateJoint(impostorJoint);
  67475. };
  67476. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  67477. var matchingJoints = this._joints.filter(function (impostorJoint) {
  67478. return (impostorJoint.connectedImpostor === connectedImpostor
  67479. && impostorJoint.joint === joint
  67480. && impostorJoint.mainImpostor === mainImpostor);
  67481. });
  67482. if (matchingJoints.length) {
  67483. this._physicsPlugin.removeJoint(matchingJoints[0]);
  67484. //TODO remove it from the list as well
  67485. }
  67486. };
  67487. /**
  67488. * Called by the scene. no need to call it.
  67489. */
  67490. PhysicsEngine.prototype._step = function (delta) {
  67491. var _this = this;
  67492. //check if any mesh has no body / requires an update
  67493. this._impostors.forEach(function (impostor) {
  67494. if (impostor.isBodyInitRequired()) {
  67495. _this._physicsPlugin.generatePhysicsBody(impostor);
  67496. }
  67497. });
  67498. if (delta > 0.1) {
  67499. delta = 0.1;
  67500. }
  67501. else if (delta <= 0) {
  67502. delta = 1.0 / 60.0;
  67503. }
  67504. this._physicsPlugin.executeStep(delta, this._impostors);
  67505. };
  67506. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  67507. return this._physicsPlugin;
  67508. };
  67509. PhysicsEngine.prototype.getImpostors = function () {
  67510. return this._impostors;
  67511. };
  67512. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  67513. for (var i = 0; i < this._impostors.length; ++i) {
  67514. if (this._impostors[i].object === object) {
  67515. return this._impostors[i];
  67516. }
  67517. }
  67518. return null;
  67519. };
  67520. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  67521. for (var i = 0; i < this._impostors.length; ++i) {
  67522. if (this._impostors[i].physicsBody === body) {
  67523. return this._impostors[i];
  67524. }
  67525. }
  67526. return null;
  67527. };
  67528. // Statics
  67529. PhysicsEngine.Epsilon = 0.001;
  67530. return PhysicsEngine;
  67531. }());
  67532. BABYLON.PhysicsEngine = PhysicsEngine;
  67533. })(BABYLON || (BABYLON = {}));
  67534. //# sourceMappingURL=babylon.physicsEngine.js.map
  67535. var BABYLON;
  67536. (function (BABYLON) {
  67537. var PhysicsHelper = /** @class */ (function () {
  67538. function PhysicsHelper(scene) {
  67539. this._scene = scene;
  67540. this._physicsEngine = this._scene.getPhysicsEngine();
  67541. if (!this._physicsEngine) {
  67542. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  67543. }
  67544. }
  67545. /**
  67546. * @param {Vector3} origin the origin of the explosion
  67547. * @param {number} radius the explosion radius
  67548. * @param {number} strength the explosion strength
  67549. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  67550. */
  67551. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  67552. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  67553. if (!this._physicsEngine) {
  67554. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  67555. return null;
  67556. }
  67557. var impostors = this._physicsEngine.getImpostors();
  67558. if (impostors.length === 0) {
  67559. return null;
  67560. }
  67561. var event = new PhysicsRadialExplosionEvent(this._scene);
  67562. impostors.forEach(function (impostor) {
  67563. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  67564. if (!impostorForceAndContactPoint) {
  67565. return;
  67566. }
  67567. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  67568. });
  67569. event.dispose(false);
  67570. return event;
  67571. };
  67572. /**
  67573. * @param {Vector3} origin the origin of the explosion
  67574. * @param {number} radius the explosion radius
  67575. * @param {number} strength the explosion strength
  67576. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  67577. */
  67578. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  67579. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  67580. if (!this._physicsEngine) {
  67581. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  67582. return null;
  67583. }
  67584. var impostors = this._physicsEngine.getImpostors();
  67585. if (impostors.length === 0) {
  67586. return null;
  67587. }
  67588. var event = new PhysicsRadialExplosionEvent(this._scene);
  67589. impostors.forEach(function (impostor) {
  67590. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  67591. if (!impostorForceAndContactPoint) {
  67592. return;
  67593. }
  67594. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  67595. });
  67596. event.dispose(false);
  67597. return event;
  67598. };
  67599. /**
  67600. * @param {Vector3} origin the origin of the explosion
  67601. * @param {number} radius the explosion radius
  67602. * @param {number} strength the explosion strength
  67603. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  67604. */
  67605. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  67606. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  67607. if (!this._physicsEngine) {
  67608. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  67609. return null;
  67610. }
  67611. var impostors = this._physicsEngine.getImpostors();
  67612. if (impostors.length === 0) {
  67613. return null;
  67614. }
  67615. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  67616. event.dispose(false);
  67617. return event;
  67618. };
  67619. /**
  67620. * @param {Vector3} origin the origin of the updraft
  67621. * @param {number} radius the radius of the updraft
  67622. * @param {number} strength the strength of the updraft
  67623. * @param {number} height the height of the updraft
  67624. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  67625. */
  67626. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  67627. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  67628. if (!this._physicsEngine) {
  67629. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  67630. return null;
  67631. }
  67632. if (this._physicsEngine.getImpostors().length === 0) {
  67633. return null;
  67634. }
  67635. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  67636. event.dispose(false);
  67637. return event;
  67638. };
  67639. /**
  67640. * @param {Vector3} origin the of the vortex
  67641. * @param {number} radius the radius of the vortex
  67642. * @param {number} strength the strength of the vortex
  67643. * @param {number} height the height of the vortex
  67644. */
  67645. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  67646. if (!this._physicsEngine) {
  67647. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  67648. return null;
  67649. }
  67650. if (this._physicsEngine.getImpostors().length === 0) {
  67651. return null;
  67652. }
  67653. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  67654. event.dispose(false);
  67655. return event;
  67656. };
  67657. return PhysicsHelper;
  67658. }());
  67659. BABYLON.PhysicsHelper = PhysicsHelper;
  67660. /***** Radial explosion *****/
  67661. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  67662. function PhysicsRadialExplosionEvent(scene) {
  67663. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  67664. this._rays = [];
  67665. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  67666. this._scene = scene;
  67667. }
  67668. /**
  67669. * Returns the data related to the radial explosion event (sphere & rays).
  67670. * @returns {PhysicsRadialExplosionEventData}
  67671. */
  67672. PhysicsRadialExplosionEvent.prototype.getData = function () {
  67673. this._dataFetched = true;
  67674. return {
  67675. sphere: this._sphere,
  67676. rays: this._rays,
  67677. };
  67678. };
  67679. /**
  67680. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  67681. * @param impostor
  67682. * @param {Vector3} origin the origin of the explosion
  67683. * @param {number} radius the explosion radius
  67684. * @param {number} strength the explosion strength
  67685. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  67686. * @returns {Nullable<PhysicsForceAndContactPoint>}
  67687. */
  67688. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  67689. if (impostor.mass === 0) {
  67690. return null;
  67691. }
  67692. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  67693. return null;
  67694. }
  67695. if (impostor.object.getClassName() !== 'Mesh') {
  67696. return null;
  67697. }
  67698. var impostorObject = impostor.object;
  67699. var impostorObjectCenter = impostor.getObjectCenter();
  67700. var direction = impostorObjectCenter.subtract(origin);
  67701. var ray = new BABYLON.Ray(origin, direction, radius);
  67702. this._rays.push(ray);
  67703. var hit = ray.intersectsMesh(impostorObject);
  67704. var contactPoint = hit.pickedPoint;
  67705. if (!contactPoint) {
  67706. return null;
  67707. }
  67708. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  67709. if (distanceFromOrigin > radius) {
  67710. return null;
  67711. }
  67712. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  67713. ? strength
  67714. : strength * (1 - (distanceFromOrigin / radius));
  67715. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  67716. return { force: force, contactPoint: contactPoint };
  67717. };
  67718. /**
  67719. * Disposes the sphere.
  67720. * @param {bolean} force
  67721. */
  67722. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  67723. var _this = this;
  67724. if (force === void 0) { force = true; }
  67725. if (force) {
  67726. this._sphere.dispose();
  67727. }
  67728. else {
  67729. setTimeout(function () {
  67730. if (!_this._dataFetched) {
  67731. _this._sphere.dispose();
  67732. }
  67733. }, 0);
  67734. }
  67735. };
  67736. /*** Helpers ***/
  67737. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  67738. if (!this._sphere) {
  67739. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  67740. this._sphere.isVisible = false;
  67741. }
  67742. };
  67743. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  67744. var impostorObject = impostor.object;
  67745. this._prepareSphere();
  67746. this._sphere.position = origin;
  67747. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  67748. this._sphere._updateBoundingInfo();
  67749. this._sphere.computeWorldMatrix(true);
  67750. return this._sphere.intersectsMesh(impostorObject, true);
  67751. };
  67752. return PhysicsRadialExplosionEvent;
  67753. }());
  67754. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  67755. /***** Gravitational Field *****/
  67756. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  67757. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  67758. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  67759. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  67760. this._physicsHelper = physicsHelper;
  67761. this._scene = scene;
  67762. this._origin = origin;
  67763. this._radius = radius;
  67764. this._strength = strength;
  67765. this._falloff = falloff;
  67766. this._tickCallback = this._tick.bind(this);
  67767. }
  67768. /**
  67769. * Returns the data related to the gravitational field event (sphere).
  67770. * @returns {PhysicsGravitationalFieldEventData}
  67771. */
  67772. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  67773. this._dataFetched = true;
  67774. return {
  67775. sphere: this._sphere,
  67776. };
  67777. };
  67778. /**
  67779. * Enables the gravitational field.
  67780. */
  67781. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  67782. this._tickCallback.call(this);
  67783. this._scene.registerBeforeRender(this._tickCallback);
  67784. };
  67785. /**
  67786. * Disables the gravitational field.
  67787. */
  67788. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  67789. this._scene.unregisterBeforeRender(this._tickCallback);
  67790. };
  67791. /**
  67792. * Disposes the sphere.
  67793. * @param {bolean} force
  67794. */
  67795. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  67796. var _this = this;
  67797. if (force === void 0) { force = true; }
  67798. if (force) {
  67799. this._sphere.dispose();
  67800. }
  67801. else {
  67802. setTimeout(function () {
  67803. if (!_this._dataFetched) {
  67804. _this._sphere.dispose();
  67805. }
  67806. }, 0);
  67807. }
  67808. };
  67809. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  67810. // Since the params won't change, we fetch the event only once
  67811. if (this._sphere) {
  67812. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  67813. }
  67814. else {
  67815. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  67816. if (radialExplosionEvent) {
  67817. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  67818. }
  67819. }
  67820. };
  67821. return PhysicsGravitationalFieldEvent;
  67822. }());
  67823. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  67824. /***** Updraft *****/
  67825. var PhysicsUpdraftEvent = /** @class */ (function () {
  67826. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  67827. this._scene = _scene;
  67828. this._origin = _origin;
  67829. this._radius = _radius;
  67830. this._strength = _strength;
  67831. this._height = _height;
  67832. this._updraftMode = _updraftMode;
  67833. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  67834. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  67835. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  67836. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  67837. this._physicsEngine = this._scene.getPhysicsEngine();
  67838. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  67839. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  67840. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  67841. this._originDirection = this._origin.subtract(this._originTop).normalize();
  67842. }
  67843. this._tickCallback = this._tick.bind(this);
  67844. }
  67845. /**
  67846. * Returns the data related to the updraft event (cylinder).
  67847. * @returns {PhysicsUpdraftEventData}
  67848. */
  67849. PhysicsUpdraftEvent.prototype.getData = function () {
  67850. this._dataFetched = true;
  67851. return {
  67852. cylinder: this._cylinder,
  67853. };
  67854. };
  67855. /**
  67856. * Enables the updraft.
  67857. */
  67858. PhysicsUpdraftEvent.prototype.enable = function () {
  67859. this._tickCallback.call(this);
  67860. this._scene.registerBeforeRender(this._tickCallback);
  67861. };
  67862. /**
  67863. * Disables the cortex.
  67864. */
  67865. PhysicsUpdraftEvent.prototype.disable = function () {
  67866. this._scene.unregisterBeforeRender(this._tickCallback);
  67867. };
  67868. /**
  67869. * Disposes the sphere.
  67870. * @param {bolean} force
  67871. */
  67872. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  67873. var _this = this;
  67874. if (force === void 0) { force = true; }
  67875. if (force) {
  67876. this._cylinder.dispose();
  67877. }
  67878. else {
  67879. setTimeout(function () {
  67880. if (!_this._dataFetched) {
  67881. _this._cylinder.dispose();
  67882. }
  67883. }, 0);
  67884. }
  67885. };
  67886. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  67887. if (impostor.mass === 0) {
  67888. return null;
  67889. }
  67890. if (!this._intersectsWithCylinder(impostor)) {
  67891. return null;
  67892. }
  67893. var impostorObjectCenter = impostor.getObjectCenter();
  67894. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  67895. var direction = this._originDirection;
  67896. }
  67897. else {
  67898. var direction = impostorObjectCenter.subtract(this._originTop);
  67899. }
  67900. var multiplier = this._strength * -1;
  67901. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  67902. return { force: force, contactPoint: impostorObjectCenter };
  67903. };
  67904. PhysicsUpdraftEvent.prototype._tick = function () {
  67905. var _this = this;
  67906. this._physicsEngine.getImpostors().forEach(function (impostor) {
  67907. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  67908. if (!impostorForceAndContactPoint) {
  67909. return;
  67910. }
  67911. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  67912. });
  67913. };
  67914. /*** Helpers ***/
  67915. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  67916. if (!this._cylinder) {
  67917. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  67918. height: this._height,
  67919. diameter: this._radius * 2,
  67920. }, this._scene);
  67921. this._cylinder.isVisible = false;
  67922. }
  67923. };
  67924. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  67925. var impostorObject = impostor.object;
  67926. this._prepareCylinder();
  67927. this._cylinder.position = this._cylinderPosition;
  67928. return this._cylinder.intersectsMesh(impostorObject, true);
  67929. };
  67930. return PhysicsUpdraftEvent;
  67931. }());
  67932. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  67933. /***** Vortex *****/
  67934. var PhysicsVortexEvent = /** @class */ (function () {
  67935. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  67936. this._scene = _scene;
  67937. this._origin = _origin;
  67938. this._radius = _radius;
  67939. this._strength = _strength;
  67940. this._height = _height;
  67941. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  67942. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  67943. this._updraftMultiplier = 0.02;
  67944. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  67945. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  67946. this._physicsEngine = this._scene.getPhysicsEngine();
  67947. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  67948. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  67949. this._tickCallback = this._tick.bind(this);
  67950. }
  67951. /**
  67952. * Returns the data related to the vortex event (cylinder).
  67953. * @returns {PhysicsVortexEventData}
  67954. */
  67955. PhysicsVortexEvent.prototype.getData = function () {
  67956. this._dataFetched = true;
  67957. return {
  67958. cylinder: this._cylinder,
  67959. };
  67960. };
  67961. /**
  67962. * Enables the vortex.
  67963. */
  67964. PhysicsVortexEvent.prototype.enable = function () {
  67965. this._tickCallback.call(this);
  67966. this._scene.registerBeforeRender(this._tickCallback);
  67967. };
  67968. /**
  67969. * Disables the cortex.
  67970. */
  67971. PhysicsVortexEvent.prototype.disable = function () {
  67972. this._scene.unregisterBeforeRender(this._tickCallback);
  67973. };
  67974. /**
  67975. * Disposes the sphere.
  67976. * @param {bolean} force
  67977. */
  67978. PhysicsVortexEvent.prototype.dispose = function (force) {
  67979. var _this = this;
  67980. if (force === void 0) { force = true; }
  67981. if (force) {
  67982. this._cylinder.dispose();
  67983. }
  67984. else {
  67985. setTimeout(function () {
  67986. if (!_this._dataFetched) {
  67987. _this._cylinder.dispose();
  67988. }
  67989. }, 0);
  67990. }
  67991. };
  67992. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  67993. if (impostor.mass === 0) {
  67994. return null;
  67995. }
  67996. if (!this._intersectsWithCylinder(impostor)) {
  67997. return null;
  67998. }
  67999. if (impostor.object.getClassName() !== 'Mesh') {
  68000. return null;
  68001. }
  68002. var impostorObject = impostor.object;
  68003. var impostorObjectCenter = impostor.getObjectCenter();
  68004. 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)
  68005. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  68006. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  68007. var hit = ray.intersectsMesh(impostorObject);
  68008. var contactPoint = hit.pickedPoint;
  68009. if (!contactPoint) {
  68010. return null;
  68011. }
  68012. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  68013. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  68014. var directionToOrigin = contactPoint.normalize();
  68015. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  68016. directionToOrigin = directionToOrigin.negate();
  68017. }
  68018. // TODO: find a more physically based solution
  68019. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  68020. var forceX = directionToOrigin.x * this._strength / 8;
  68021. var forceY = directionToOrigin.y * this._updraftMultiplier;
  68022. var forceZ = directionToOrigin.z * this._strength / 8;
  68023. }
  68024. else {
  68025. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  68026. var forceY = this._originTop.y * this._updraftMultiplier;
  68027. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  68028. }
  68029. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  68030. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  68031. return { force: force, contactPoint: impostorObjectCenter };
  68032. };
  68033. PhysicsVortexEvent.prototype._tick = function () {
  68034. var _this = this;
  68035. this._physicsEngine.getImpostors().forEach(function (impostor) {
  68036. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  68037. if (!impostorForceAndContactPoint) {
  68038. return;
  68039. }
  68040. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  68041. });
  68042. };
  68043. /*** Helpers ***/
  68044. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  68045. if (!this._cylinder) {
  68046. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  68047. height: this._height,
  68048. diameter: this._radius * 2,
  68049. }, this._scene);
  68050. this._cylinder.isVisible = false;
  68051. }
  68052. };
  68053. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  68054. var impostorObject = impostor.object;
  68055. this._prepareCylinder();
  68056. this._cylinder.position = this._cylinderPosition;
  68057. return this._cylinder.intersectsMesh(impostorObject, true);
  68058. };
  68059. return PhysicsVortexEvent;
  68060. }());
  68061. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  68062. /***** Enums *****/
  68063. /**
  68064. * The strenght of the force in correspondence to the distance of the affected object
  68065. */
  68066. var PhysicsRadialImpulseFalloff;
  68067. (function (PhysicsRadialImpulseFalloff) {
  68068. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  68069. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  68070. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  68071. /**
  68072. * The strenght of the force in correspondence to the distance of the affected object
  68073. */
  68074. var PhysicsUpdraftMode;
  68075. (function (PhysicsUpdraftMode) {
  68076. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  68077. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  68078. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  68079. })(BABYLON || (BABYLON = {}));
  68080. //# sourceMappingURL=babylon.physicsHelper.js.map
  68081. var BABYLON;
  68082. (function (BABYLON) {
  68083. var CannonJSPlugin = /** @class */ (function () {
  68084. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  68085. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  68086. if (iterations === void 0) { iterations = 10; }
  68087. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  68088. this.name = "CannonJSPlugin";
  68089. this._physicsMaterials = new Array();
  68090. this._fixedTimeStep = 1 / 60;
  68091. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  68092. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  68093. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  68094. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  68095. this._tmpPosition = BABYLON.Vector3.Zero();
  68096. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  68097. this._tmpUnityRotation = new BABYLON.Quaternion();
  68098. if (!this.isSupported()) {
  68099. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  68100. return;
  68101. }
  68102. this._extendNamespace();
  68103. this.world = new this.BJSCANNON.World();
  68104. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  68105. this.world.solver.iterations = iterations;
  68106. }
  68107. CannonJSPlugin.prototype.setGravity = function (gravity) {
  68108. this.world.gravity.copy(gravity);
  68109. };
  68110. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  68111. this._fixedTimeStep = timeStep;
  68112. };
  68113. CannonJSPlugin.prototype.getTimeStep = function () {
  68114. return this._fixedTimeStep;
  68115. };
  68116. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  68117. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  68118. };
  68119. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  68120. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  68121. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  68122. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  68123. };
  68124. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  68125. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  68126. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  68127. impostor.physicsBody.applyForce(impulse, worldPoint);
  68128. };
  68129. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  68130. //parent-child relationship. Does this impostor has a parent impostor?
  68131. if (impostor.parent) {
  68132. if (impostor.physicsBody) {
  68133. this.removePhysicsBody(impostor);
  68134. //TODO is that needed?
  68135. impostor.forceUpdate();
  68136. }
  68137. return;
  68138. }
  68139. //should a new body be created for this impostor?
  68140. if (impostor.isBodyInitRequired()) {
  68141. var shape = this._createShape(impostor);
  68142. //unregister events, if body is being changed
  68143. var oldBody = impostor.physicsBody;
  68144. if (oldBody) {
  68145. this.removePhysicsBody(impostor);
  68146. }
  68147. //create the body and material
  68148. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  68149. var bodyCreationObject = {
  68150. mass: impostor.getParam("mass"),
  68151. material: material
  68152. };
  68153. // A simple extend, in case native options were used.
  68154. var nativeOptions = impostor.getParam("nativeOptions");
  68155. for (var key in nativeOptions) {
  68156. if (nativeOptions.hasOwnProperty(key)) {
  68157. bodyCreationObject[key] = nativeOptions[key];
  68158. }
  68159. }
  68160. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  68161. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  68162. this.world.addEventListener("preStep", impostor.beforeStep);
  68163. this.world.addEventListener("postStep", impostor.afterStep);
  68164. impostor.physicsBody.addShape(shape);
  68165. this.world.add(impostor.physicsBody);
  68166. //try to keep the body moving in the right direction by taking old properties.
  68167. //Should be tested!
  68168. if (oldBody) {
  68169. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  68170. impostor.physicsBody[param].copy(oldBody[param]);
  68171. });
  68172. }
  68173. this._processChildMeshes(impostor);
  68174. }
  68175. //now update the body's transformation
  68176. this._updatePhysicsBodyTransformation(impostor);
  68177. };
  68178. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  68179. var _this = this;
  68180. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  68181. var currentRotation = mainImpostor.object.rotationQuaternion;
  68182. if (meshChildren.length) {
  68183. var processMesh = function (localPosition, mesh) {
  68184. if (!currentRotation || !mesh.rotationQuaternion) {
  68185. return;
  68186. }
  68187. var childImpostor = mesh.getPhysicsImpostor();
  68188. if (childImpostor) {
  68189. var parent = childImpostor.parent;
  68190. if (parent !== mainImpostor) {
  68191. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  68192. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  68193. if (childImpostor.physicsBody) {
  68194. _this.removePhysicsBody(childImpostor);
  68195. childImpostor.physicsBody = null;
  68196. }
  68197. childImpostor.parent = mainImpostor;
  68198. childImpostor.resetUpdateFlags();
  68199. 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));
  68200. //Add the mass of the children.
  68201. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  68202. }
  68203. }
  68204. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  68205. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  68206. };
  68207. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  68208. }
  68209. };
  68210. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  68211. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  68212. this.world.removeEventListener("preStep", impostor.beforeStep);
  68213. this.world.removeEventListener("postStep", impostor.afterStep);
  68214. this.world.remove(impostor.physicsBody);
  68215. };
  68216. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  68217. var mainBody = impostorJoint.mainImpostor.physicsBody;
  68218. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  68219. if (!mainBody || !connectedBody) {
  68220. return;
  68221. }
  68222. var constraint;
  68223. var jointData = impostorJoint.joint.jointData;
  68224. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  68225. var constraintData = {
  68226. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  68227. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  68228. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  68229. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  68230. maxForce: jointData.nativeParams.maxForce,
  68231. collideConnected: !!jointData.collision
  68232. };
  68233. switch (impostorJoint.joint.type) {
  68234. case BABYLON.PhysicsJoint.HingeJoint:
  68235. case BABYLON.PhysicsJoint.Hinge2Joint:
  68236. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  68237. break;
  68238. case BABYLON.PhysicsJoint.DistanceJoint:
  68239. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  68240. break;
  68241. case BABYLON.PhysicsJoint.SpringJoint:
  68242. var springData = jointData;
  68243. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  68244. restLength: springData.length,
  68245. stiffness: springData.stiffness,
  68246. damping: springData.damping,
  68247. localAnchorA: constraintData.pivotA,
  68248. localAnchorB: constraintData.pivotB
  68249. });
  68250. break;
  68251. case BABYLON.PhysicsJoint.LockJoint:
  68252. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  68253. break;
  68254. case BABYLON.PhysicsJoint.PointToPointJoint:
  68255. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  68256. default:
  68257. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  68258. break;
  68259. }
  68260. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  68261. constraint.collideConnected = !!jointData.collision;
  68262. impostorJoint.joint.physicsJoint = constraint;
  68263. //don't add spring as constraint, as it is not one.
  68264. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  68265. this.world.addConstraint(constraint);
  68266. }
  68267. else {
  68268. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  68269. constraint.applyForce();
  68270. });
  68271. }
  68272. };
  68273. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  68274. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  68275. };
  68276. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  68277. var index;
  68278. var mat;
  68279. for (index = 0; index < this._physicsMaterials.length; index++) {
  68280. mat = this._physicsMaterials[index];
  68281. if (mat.friction === friction && mat.restitution === restitution) {
  68282. return mat;
  68283. }
  68284. }
  68285. var currentMat = new this.BJSCANNON.Material(name);
  68286. currentMat.friction = friction;
  68287. currentMat.restitution = restitution;
  68288. this._physicsMaterials.push(currentMat);
  68289. return currentMat;
  68290. };
  68291. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  68292. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  68293. };
  68294. CannonJSPlugin.prototype._createShape = function (impostor) {
  68295. var object = impostor.object;
  68296. var returnValue;
  68297. var extendSize = impostor.getObjectExtendSize();
  68298. switch (impostor.type) {
  68299. case BABYLON.PhysicsImpostor.SphereImpostor:
  68300. var radiusX = extendSize.x;
  68301. var radiusY = extendSize.y;
  68302. var radiusZ = extendSize.z;
  68303. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  68304. break;
  68305. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  68306. case BABYLON.PhysicsImpostor.CylinderImpostor:
  68307. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  68308. break;
  68309. case BABYLON.PhysicsImpostor.BoxImpostor:
  68310. var box = extendSize.scale(0.5);
  68311. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  68312. break;
  68313. case BABYLON.PhysicsImpostor.PlaneImpostor:
  68314. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  68315. returnValue = new this.BJSCANNON.Plane();
  68316. break;
  68317. case BABYLON.PhysicsImpostor.MeshImpostor:
  68318. // should transform the vertex data to world coordinates!!
  68319. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  68320. var rawFaces = object.getIndices ? object.getIndices() : [];
  68321. if (!rawVerts)
  68322. return;
  68323. // get only scale! so the object could transform correctly.
  68324. var oldPosition = object.position.clone();
  68325. var oldRotation = object.rotation && object.rotation.clone();
  68326. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  68327. object.position.copyFromFloats(0, 0, 0);
  68328. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  68329. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  68330. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  68331. var transform = object.computeWorldMatrix(true);
  68332. // convert rawVerts to object space
  68333. var temp = new Array();
  68334. var index;
  68335. for (index = 0; index < rawVerts.length; index += 3) {
  68336. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  68337. }
  68338. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  68339. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  68340. //now set back the transformation!
  68341. object.position.copyFrom(oldPosition);
  68342. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  68343. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  68344. break;
  68345. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  68346. var oldPosition2 = object.position.clone();
  68347. var oldRotation2 = object.rotation && object.rotation.clone();
  68348. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  68349. object.position.copyFromFloats(0, 0, 0);
  68350. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  68351. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  68352. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  68353. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  68354. returnValue = this._createHeightmap(object);
  68355. object.position.copyFrom(oldPosition2);
  68356. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  68357. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  68358. object.computeWorldMatrix(true);
  68359. break;
  68360. case BABYLON.PhysicsImpostor.ParticleImpostor:
  68361. returnValue = new this.BJSCANNON.Particle();
  68362. break;
  68363. }
  68364. return returnValue;
  68365. };
  68366. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  68367. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  68368. var transform = object.computeWorldMatrix(true);
  68369. // convert rawVerts to object space
  68370. var temp = new Array();
  68371. var index;
  68372. for (index = 0; index < pos.length; index += 3) {
  68373. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  68374. }
  68375. pos = temp;
  68376. var matrix = new Array();
  68377. //For now pointDepth will not be used and will be automatically calculated.
  68378. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  68379. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  68380. var boundingInfo = object.getBoundingInfo();
  68381. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  68382. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  68383. var elementSize = dim * 2 / arraySize;
  68384. for (var i = 0; i < pos.length; i = i + 3) {
  68385. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  68386. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  68387. var y = -pos[i + 2] + minY;
  68388. if (!matrix[x]) {
  68389. matrix[x] = [];
  68390. }
  68391. if (!matrix[x][z]) {
  68392. matrix[x][z] = y;
  68393. }
  68394. matrix[x][z] = Math.max(y, matrix[x][z]);
  68395. }
  68396. for (var x = 0; x <= arraySize; ++x) {
  68397. if (!matrix[x]) {
  68398. var loc = 1;
  68399. while (!matrix[(x + loc) % arraySize]) {
  68400. loc++;
  68401. }
  68402. matrix[x] = matrix[(x + loc) % arraySize].slice();
  68403. //console.log("missing x", x);
  68404. }
  68405. for (var z = 0; z <= arraySize; ++z) {
  68406. if (!matrix[x][z]) {
  68407. var loc = 1;
  68408. var newValue;
  68409. while (newValue === undefined) {
  68410. newValue = matrix[x][(z + loc++) % arraySize];
  68411. }
  68412. matrix[x][z] = newValue;
  68413. }
  68414. }
  68415. }
  68416. var shape = new this.BJSCANNON.Heightfield(matrix, {
  68417. elementSize: elementSize
  68418. });
  68419. //For future reference, needed for body transformation
  68420. shape.minY = minY;
  68421. return shape;
  68422. };
  68423. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  68424. var object = impostor.object;
  68425. //make sure it is updated...
  68426. object.computeWorldMatrix && object.computeWorldMatrix(true);
  68427. // The delta between the mesh position and the mesh bounding box center
  68428. var bInfo = object.getBoundingInfo();
  68429. if (!bInfo)
  68430. return;
  68431. var center = impostor.getObjectCenter();
  68432. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  68433. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  68434. this._tmpPosition.copyFrom(center);
  68435. var quaternion = object.rotationQuaternion;
  68436. if (!quaternion) {
  68437. return;
  68438. }
  68439. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  68440. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  68441. //-90 DEG in X, precalculated
  68442. quaternion = quaternion.multiply(this._minus90X);
  68443. //Invert! (Precalculated, 90 deg in X)
  68444. //No need to clone. this will never change.
  68445. impostor.setDeltaRotation(this._plus90X);
  68446. }
  68447. //If it is a heightfield, if should be centered.
  68448. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  68449. var mesh = object;
  68450. var boundingInfo = mesh.getBoundingInfo();
  68451. //calculate the correct body position:
  68452. var rotationQuaternion = mesh.rotationQuaternion;
  68453. mesh.rotationQuaternion = this._tmpUnityRotation;
  68454. mesh.computeWorldMatrix(true);
  68455. //get original center with no rotation
  68456. var c = center.clone();
  68457. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  68458. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  68459. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  68460. mesh.setPivotMatrix(p);
  68461. mesh.computeWorldMatrix(true);
  68462. //calculate the translation
  68463. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  68464. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  68465. //add it inverted to the delta
  68466. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  68467. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  68468. //rotation is back
  68469. mesh.rotationQuaternion = rotationQuaternion;
  68470. mesh.setPivotMatrix(oldPivot);
  68471. mesh.computeWorldMatrix(true);
  68472. }
  68473. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  68474. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  68475. //this._tmpPosition.copyFrom(object.position);
  68476. }
  68477. impostor.setDeltaPosition(this._tmpDeltaPosition);
  68478. //Now update the impostor object
  68479. impostor.physicsBody.position.copy(this._tmpPosition);
  68480. impostor.physicsBody.quaternion.copy(quaternion);
  68481. };
  68482. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  68483. impostor.object.position.copyFrom(impostor.physicsBody.position);
  68484. if (impostor.object.rotationQuaternion) {
  68485. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  68486. }
  68487. };
  68488. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  68489. impostor.physicsBody.position.copy(newPosition);
  68490. impostor.physicsBody.quaternion.copy(newRotation);
  68491. };
  68492. CannonJSPlugin.prototype.isSupported = function () {
  68493. return this.BJSCANNON !== undefined;
  68494. };
  68495. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  68496. impostor.physicsBody.velocity.copy(velocity);
  68497. };
  68498. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  68499. impostor.physicsBody.angularVelocity.copy(velocity);
  68500. };
  68501. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  68502. var v = impostor.physicsBody.velocity;
  68503. if (!v) {
  68504. return null;
  68505. }
  68506. return new BABYLON.Vector3(v.x, v.y, v.z);
  68507. };
  68508. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  68509. var v = impostor.physicsBody.angularVelocity;
  68510. if (!v) {
  68511. return null;
  68512. }
  68513. return new BABYLON.Vector3(v.x, v.y, v.z);
  68514. };
  68515. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  68516. impostor.physicsBody.mass = mass;
  68517. impostor.physicsBody.updateMassProperties();
  68518. };
  68519. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  68520. return impostor.physicsBody.mass;
  68521. };
  68522. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  68523. return impostor.physicsBody.material.friction;
  68524. };
  68525. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  68526. impostor.physicsBody.material.friction = friction;
  68527. };
  68528. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  68529. return impostor.physicsBody.material.restitution;
  68530. };
  68531. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  68532. impostor.physicsBody.material.restitution = restitution;
  68533. };
  68534. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  68535. impostor.physicsBody.sleep();
  68536. };
  68537. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  68538. impostor.physicsBody.wakeUp();
  68539. };
  68540. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  68541. joint.physicsJoint.distance = maxDistance;
  68542. };
  68543. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  68544. // if (!motorIndex) {
  68545. // joint.physicsJoint.enableMotor();
  68546. // }
  68547. // }
  68548. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  68549. // if (!motorIndex) {
  68550. // joint.physicsJoint.disableMotor();
  68551. // }
  68552. // }
  68553. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  68554. if (!motorIndex) {
  68555. joint.physicsJoint.enableMotor();
  68556. joint.physicsJoint.setMotorSpeed(speed);
  68557. if (maxForce) {
  68558. this.setLimit(joint, maxForce);
  68559. }
  68560. }
  68561. };
  68562. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  68563. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  68564. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  68565. };
  68566. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  68567. var body = impostor.physicsBody;
  68568. mesh.position.x = body.position.x;
  68569. mesh.position.y = body.position.y;
  68570. mesh.position.z = body.position.z;
  68571. if (mesh.rotationQuaternion) {
  68572. mesh.rotationQuaternion.x = body.quaternion.x;
  68573. mesh.rotationQuaternion.y = body.quaternion.y;
  68574. mesh.rotationQuaternion.z = body.quaternion.z;
  68575. mesh.rotationQuaternion.w = body.quaternion.w;
  68576. }
  68577. };
  68578. CannonJSPlugin.prototype.getRadius = function (impostor) {
  68579. var shape = impostor.physicsBody.shapes[0];
  68580. return shape.boundingSphereRadius;
  68581. };
  68582. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  68583. var shape = impostor.physicsBody.shapes[0];
  68584. result.x = shape.halfExtents.x * 2;
  68585. result.y = shape.halfExtents.y * 2;
  68586. result.z = shape.halfExtents.z * 2;
  68587. };
  68588. CannonJSPlugin.prototype.dispose = function () {
  68589. };
  68590. CannonJSPlugin.prototype._extendNamespace = function () {
  68591. //this will force cannon to execute at least one step when using interpolation
  68592. var step_tmp1 = new this.BJSCANNON.Vec3();
  68593. var Engine = this.BJSCANNON;
  68594. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  68595. maxSubSteps = maxSubSteps || 10;
  68596. timeSinceLastCalled = timeSinceLastCalled || 0;
  68597. if (timeSinceLastCalled === 0) {
  68598. this.internalStep(dt);
  68599. this.time += dt;
  68600. }
  68601. else {
  68602. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  68603. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  68604. var t0 = performance.now();
  68605. for (var i = 0; i !== internalSteps; i++) {
  68606. this.internalStep(dt);
  68607. if (performance.now() - t0 > dt * 1000) {
  68608. break;
  68609. }
  68610. }
  68611. this.time += timeSinceLastCalled;
  68612. var h = this.time % dt;
  68613. var h_div_dt = h / dt;
  68614. var interpvelo = step_tmp1;
  68615. var bodies = this.bodies;
  68616. for (var j = 0; j !== bodies.length; j++) {
  68617. var b = bodies[j];
  68618. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  68619. b.position.vsub(b.previousPosition, interpvelo);
  68620. interpvelo.scale(h_div_dt, interpvelo);
  68621. b.position.vadd(interpvelo, b.interpolatedPosition);
  68622. }
  68623. else {
  68624. b.interpolatedPosition.copy(b.position);
  68625. b.interpolatedQuaternion.copy(b.quaternion);
  68626. }
  68627. }
  68628. }
  68629. };
  68630. };
  68631. return CannonJSPlugin;
  68632. }());
  68633. BABYLON.CannonJSPlugin = CannonJSPlugin;
  68634. })(BABYLON || (BABYLON = {}));
  68635. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  68636. var BABYLON;
  68637. (function (BABYLON) {
  68638. var OimoJSPlugin = /** @class */ (function () {
  68639. function OimoJSPlugin(iterations) {
  68640. this.name = "OimoJSPlugin";
  68641. this._tmpImpostorsArray = [];
  68642. this._tmpPositionVector = BABYLON.Vector3.Zero();
  68643. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  68644. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  68645. this.world.worldscale(1);
  68646. this.world.clear();
  68647. //making sure no stats are calculated
  68648. this.world.isNoStat = true;
  68649. }
  68650. OimoJSPlugin.prototype.setGravity = function (gravity) {
  68651. this.world.gravity.copy(gravity);
  68652. };
  68653. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  68654. this.world.timeStep = timeStep;
  68655. };
  68656. OimoJSPlugin.prototype.getTimeStep = function () {
  68657. return this.world.timeStep;
  68658. };
  68659. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  68660. var _this = this;
  68661. impostors.forEach(function (impostor) {
  68662. impostor.beforeStep();
  68663. });
  68664. this.world.step();
  68665. impostors.forEach(function (impostor) {
  68666. impostor.afterStep();
  68667. //update the ordered impostors array
  68668. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  68669. });
  68670. //check for collisions
  68671. var contact = this.world.contacts;
  68672. while (contact !== null) {
  68673. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  68674. contact = contact.next;
  68675. continue;
  68676. }
  68677. //is this body colliding with any other? get the impostor
  68678. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  68679. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  68680. if (!mainImpostor || !collidingImpostor) {
  68681. contact = contact.next;
  68682. continue;
  68683. }
  68684. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  68685. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  68686. contact = contact.next;
  68687. }
  68688. };
  68689. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  68690. var mass = impostor.physicsBody.massInfo.mass;
  68691. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  68692. };
  68693. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  68694. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  68695. this.applyImpulse(impostor, force, contactPoint);
  68696. };
  68697. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  68698. var _this = this;
  68699. //parent-child relationship. Does this impostor has a parent impostor?
  68700. if (impostor.parent) {
  68701. if (impostor.physicsBody) {
  68702. this.removePhysicsBody(impostor);
  68703. //TODO is that needed?
  68704. impostor.forceUpdate();
  68705. }
  68706. return;
  68707. }
  68708. if (impostor.isBodyInitRequired()) {
  68709. var bodyConfig = {
  68710. name: impostor.uniqueId,
  68711. //Oimo must have mass, also for static objects.
  68712. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  68713. size: [],
  68714. type: [],
  68715. pos: [],
  68716. rot: [],
  68717. move: impostor.getParam("mass") !== 0,
  68718. //Supporting older versions of Oimo
  68719. world: this.world
  68720. };
  68721. var impostors = [impostor];
  68722. var addToArray = function (parent) {
  68723. if (!parent.getChildMeshes)
  68724. return;
  68725. parent.getChildMeshes().forEach(function (m) {
  68726. if (m.physicsImpostor) {
  68727. impostors.push(m.physicsImpostor);
  68728. //m.physicsImpostor._init();
  68729. }
  68730. });
  68731. };
  68732. addToArray(impostor.object);
  68733. var checkWithEpsilon_1 = function (value) {
  68734. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  68735. };
  68736. impostors.forEach(function (i) {
  68737. if (!impostor.object.rotationQuaternion) {
  68738. return;
  68739. }
  68740. //get the correct bounding box
  68741. var oldQuaternion = i.object.rotationQuaternion;
  68742. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  68743. x: impostor.object.rotationQuaternion.x,
  68744. y: impostor.object.rotationQuaternion.y,
  68745. z: impostor.object.rotationQuaternion.z,
  68746. s: impostor.object.rotationQuaternion.w
  68747. });
  68748. var extendSize = i.getObjectExtendSize();
  68749. if (i === impostor) {
  68750. var center = impostor.getObjectCenter();
  68751. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  68752. //Can also use Array.prototype.push.apply
  68753. bodyConfig.pos.push(center.x);
  68754. bodyConfig.pos.push(center.y);
  68755. bodyConfig.pos.push(center.z);
  68756. //tmp solution
  68757. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  68758. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  68759. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  68760. }
  68761. else {
  68762. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  68763. bodyConfig.pos.push(localPosition.x);
  68764. bodyConfig.pos.push(localPosition.y);
  68765. bodyConfig.pos.push(localPosition.z);
  68766. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  68767. bodyConfig.rot.push(0);
  68768. bodyConfig.rot.push(0);
  68769. bodyConfig.rot.push(0);
  68770. }
  68771. // register mesh
  68772. switch (i.type) {
  68773. case BABYLON.PhysicsImpostor.ParticleImpostor:
  68774. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  68775. case BABYLON.PhysicsImpostor.SphereImpostor:
  68776. var radiusX = extendSize.x;
  68777. var radiusY = extendSize.y;
  68778. var radiusZ = extendSize.z;
  68779. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  68780. bodyConfig.type.push('sphere');
  68781. //due to the way oimo works with compounds, add 3 times
  68782. bodyConfig.size.push(size);
  68783. bodyConfig.size.push(size);
  68784. bodyConfig.size.push(size);
  68785. break;
  68786. case BABYLON.PhysicsImpostor.CylinderImpostor:
  68787. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  68788. var sizeY = checkWithEpsilon_1(extendSize.y);
  68789. bodyConfig.type.push('cylinder');
  68790. bodyConfig.size.push(sizeX);
  68791. bodyConfig.size.push(sizeY);
  68792. //due to the way oimo works with compounds, add one more value.
  68793. bodyConfig.size.push(sizeY);
  68794. break;
  68795. case BABYLON.PhysicsImpostor.PlaneImpostor:
  68796. case BABYLON.PhysicsImpostor.BoxImpostor:
  68797. default:
  68798. var sizeX = checkWithEpsilon_1(extendSize.x);
  68799. var sizeY = checkWithEpsilon_1(extendSize.y);
  68800. var sizeZ = checkWithEpsilon_1(extendSize.z);
  68801. bodyConfig.type.push('box');
  68802. bodyConfig.size.push(sizeX);
  68803. bodyConfig.size.push(sizeY);
  68804. bodyConfig.size.push(sizeZ);
  68805. break;
  68806. }
  68807. //actually not needed, but hey...
  68808. i.object.rotationQuaternion = oldQuaternion;
  68809. });
  68810. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  68811. }
  68812. else {
  68813. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  68814. }
  68815. impostor.setDeltaPosition(this._tmpPositionVector);
  68816. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  68817. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  68818. };
  68819. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  68820. //impostor.physicsBody.dispose();
  68821. //Same as : (older oimo versions)
  68822. this.world.removeRigidBody(impostor.physicsBody);
  68823. };
  68824. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  68825. var mainBody = impostorJoint.mainImpostor.physicsBody;
  68826. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  68827. if (!mainBody || !connectedBody) {
  68828. return;
  68829. }
  68830. var jointData = impostorJoint.joint.jointData;
  68831. var options = jointData.nativeParams || {};
  68832. var type;
  68833. var nativeJointData = {
  68834. body1: mainBody,
  68835. body2: connectedBody,
  68836. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  68837. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  68838. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  68839. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  68840. min: options.min,
  68841. max: options.max,
  68842. collision: options.collision || jointData.collision,
  68843. spring: options.spring,
  68844. //supporting older version of Oimo
  68845. world: this.world
  68846. };
  68847. switch (impostorJoint.joint.type) {
  68848. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  68849. type = "jointBall";
  68850. break;
  68851. case BABYLON.PhysicsJoint.SpringJoint:
  68852. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  68853. var springData = jointData;
  68854. nativeJointData.min = springData.length || nativeJointData.min;
  68855. //Max should also be set, just make sure it is at least min
  68856. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  68857. case BABYLON.PhysicsJoint.DistanceJoint:
  68858. type = "jointDistance";
  68859. nativeJointData.max = jointData.maxDistance;
  68860. break;
  68861. case BABYLON.PhysicsJoint.PrismaticJoint:
  68862. type = "jointPrisme";
  68863. break;
  68864. case BABYLON.PhysicsJoint.SliderJoint:
  68865. type = "jointSlide";
  68866. break;
  68867. case BABYLON.PhysicsJoint.WheelJoint:
  68868. type = "jointWheel";
  68869. break;
  68870. case BABYLON.PhysicsJoint.HingeJoint:
  68871. default:
  68872. type = "jointHinge";
  68873. break;
  68874. }
  68875. nativeJointData.type = type;
  68876. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  68877. };
  68878. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  68879. //Bug in Oimo prevents us from disposing a joint in the playground
  68880. //joint.joint.physicsJoint.dispose();
  68881. //So we will bruteforce it!
  68882. try {
  68883. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  68884. }
  68885. catch (e) {
  68886. BABYLON.Tools.Warn(e);
  68887. }
  68888. };
  68889. OimoJSPlugin.prototype.isSupported = function () {
  68890. return this.BJSOIMO !== undefined;
  68891. };
  68892. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  68893. if (!impostor.physicsBody.sleeping) {
  68894. //TODO check that
  68895. if (impostor.physicsBody.shapes.next) {
  68896. var parentShape = this._getLastShape(impostor.physicsBody);
  68897. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  68898. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  68899. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  68900. }
  68901. else {
  68902. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  68903. }
  68904. if (impostor.object.rotationQuaternion) {
  68905. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  68906. impostor.object.rotationQuaternion.normalize();
  68907. }
  68908. }
  68909. };
  68910. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  68911. var body = impostor.physicsBody;
  68912. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  68913. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  68914. body.syncShapes();
  68915. body.awake();
  68916. };
  68917. OimoJSPlugin.prototype._getLastShape = function (body) {
  68918. var lastShape = body.shapes;
  68919. while (lastShape.next) {
  68920. lastShape = lastShape.next;
  68921. }
  68922. return lastShape;
  68923. };
  68924. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  68925. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  68926. };
  68927. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  68928. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  68929. };
  68930. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  68931. var v = impostor.physicsBody.linearVelocity;
  68932. if (!v) {
  68933. return null;
  68934. }
  68935. return new BABYLON.Vector3(v.x, v.y, v.z);
  68936. };
  68937. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  68938. var v = impostor.physicsBody.angularVelocity;
  68939. if (!v) {
  68940. return null;
  68941. }
  68942. return new BABYLON.Vector3(v.x, v.y, v.z);
  68943. };
  68944. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  68945. var staticBody = mass === 0;
  68946. //this will actually set the body's density and not its mass.
  68947. //But this is how oimo treats the mass variable.
  68948. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  68949. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  68950. };
  68951. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  68952. return impostor.physicsBody.shapes.density;
  68953. };
  68954. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  68955. return impostor.physicsBody.shapes.friction;
  68956. };
  68957. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  68958. impostor.physicsBody.shapes.friction = friction;
  68959. };
  68960. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  68961. return impostor.physicsBody.shapes.restitution;
  68962. };
  68963. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  68964. impostor.physicsBody.shapes.restitution = restitution;
  68965. };
  68966. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  68967. impostor.physicsBody.sleep();
  68968. };
  68969. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  68970. impostor.physicsBody.awake();
  68971. };
  68972. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  68973. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  68974. if (minDistance !== void 0) {
  68975. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  68976. }
  68977. };
  68978. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  68979. //TODO separate rotational and transational motors.
  68980. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  68981. if (motor) {
  68982. motor.setMotor(speed, maxForce);
  68983. }
  68984. };
  68985. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  68986. //TODO separate rotational and transational motors.
  68987. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  68988. if (motor) {
  68989. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  68990. }
  68991. };
  68992. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  68993. var body = impostor.physicsBody;
  68994. mesh.position.x = body.position.x;
  68995. mesh.position.y = body.position.y;
  68996. mesh.position.z = body.position.z;
  68997. if (mesh.rotationQuaternion) {
  68998. mesh.rotationQuaternion.x = body.orientation.x;
  68999. mesh.rotationQuaternion.y = body.orientation.y;
  69000. mesh.rotationQuaternion.z = body.orientation.z;
  69001. mesh.rotationQuaternion.w = body.orientation.s;
  69002. }
  69003. };
  69004. OimoJSPlugin.prototype.getRadius = function (impostor) {
  69005. return impostor.physicsBody.shapes.radius;
  69006. };
  69007. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  69008. var shape = impostor.physicsBody.shapes;
  69009. result.x = shape.halfWidth * 2;
  69010. result.y = shape.halfHeight * 2;
  69011. result.z = shape.halfDepth * 2;
  69012. };
  69013. OimoJSPlugin.prototype.dispose = function () {
  69014. this.world.clear();
  69015. };
  69016. return OimoJSPlugin;
  69017. }());
  69018. BABYLON.OimoJSPlugin = OimoJSPlugin;
  69019. })(BABYLON || (BABYLON = {}));
  69020. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  69021. var BABYLON;
  69022. (function (BABYLON) {
  69023. var Internals;
  69024. (function (Internals) {
  69025. /*
  69026. * Based on jsTGALoader - Javascript loader for TGA file
  69027. * By Vincent Thibault
  69028. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  69029. */
  69030. var TGATools = /** @class */ (function () {
  69031. function TGATools() {
  69032. }
  69033. TGATools.GetTGAHeader = function (data) {
  69034. var offset = 0;
  69035. var header = {
  69036. id_length: data[offset++],
  69037. colormap_type: data[offset++],
  69038. image_type: data[offset++],
  69039. colormap_index: data[offset++] | data[offset++] << 8,
  69040. colormap_length: data[offset++] | data[offset++] << 8,
  69041. colormap_size: data[offset++],
  69042. origin: [
  69043. data[offset++] | data[offset++] << 8,
  69044. data[offset++] | data[offset++] << 8
  69045. ],
  69046. width: data[offset++] | data[offset++] << 8,
  69047. height: data[offset++] | data[offset++] << 8,
  69048. pixel_size: data[offset++],
  69049. flags: data[offset++]
  69050. };
  69051. return header;
  69052. };
  69053. TGATools.UploadContent = function (gl, data) {
  69054. // Not enough data to contain header ?
  69055. if (data.length < 19) {
  69056. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  69057. return;
  69058. }
  69059. // Read Header
  69060. var offset = 18;
  69061. var header = TGATools.GetTGAHeader(data);
  69062. // Assume it's a valid Targa file.
  69063. if (header.id_length + offset > data.length) {
  69064. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  69065. return;
  69066. }
  69067. // Skip not needed data
  69068. offset += header.id_length;
  69069. var use_rle = false;
  69070. var use_pal = false;
  69071. var use_grey = false;
  69072. // Get some informations.
  69073. switch (header.image_type) {
  69074. case TGATools._TYPE_RLE_INDEXED:
  69075. use_rle = true;
  69076. case TGATools._TYPE_INDEXED:
  69077. use_pal = true;
  69078. break;
  69079. case TGATools._TYPE_RLE_RGB:
  69080. use_rle = true;
  69081. case TGATools._TYPE_RGB:
  69082. // use_rgb = true;
  69083. break;
  69084. case TGATools._TYPE_RLE_GREY:
  69085. use_rle = true;
  69086. case TGATools._TYPE_GREY:
  69087. use_grey = true;
  69088. break;
  69089. }
  69090. var pixel_data;
  69091. // var numAlphaBits = header.flags & 0xf;
  69092. var pixel_size = header.pixel_size >> 3;
  69093. var pixel_total = header.width * header.height * pixel_size;
  69094. // Read palettes
  69095. var palettes;
  69096. if (use_pal) {
  69097. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  69098. }
  69099. // Read LRE
  69100. if (use_rle) {
  69101. pixel_data = new Uint8Array(pixel_total);
  69102. var c, count, i;
  69103. var localOffset = 0;
  69104. var pixels = new Uint8Array(pixel_size);
  69105. while (offset < pixel_total && localOffset < pixel_total) {
  69106. c = data[offset++];
  69107. count = (c & 0x7f) + 1;
  69108. // RLE pixels
  69109. if (c & 0x80) {
  69110. // Bind pixel tmp array
  69111. for (i = 0; i < pixel_size; ++i) {
  69112. pixels[i] = data[offset++];
  69113. }
  69114. // Copy pixel array
  69115. for (i = 0; i < count; ++i) {
  69116. pixel_data.set(pixels, localOffset + i * pixel_size);
  69117. }
  69118. localOffset += pixel_size * count;
  69119. }
  69120. else {
  69121. count *= pixel_size;
  69122. for (i = 0; i < count; ++i) {
  69123. pixel_data[localOffset + i] = data[offset++];
  69124. }
  69125. localOffset += count;
  69126. }
  69127. }
  69128. }
  69129. else {
  69130. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  69131. }
  69132. // Load to texture
  69133. var x_start, y_start, x_step, y_step, y_end, x_end;
  69134. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  69135. default:
  69136. case TGATools._ORIGIN_UL:
  69137. x_start = 0;
  69138. x_step = 1;
  69139. x_end = header.width;
  69140. y_start = 0;
  69141. y_step = 1;
  69142. y_end = header.height;
  69143. break;
  69144. case TGATools._ORIGIN_BL:
  69145. x_start = 0;
  69146. x_step = 1;
  69147. x_end = header.width;
  69148. y_start = header.height - 1;
  69149. y_step = -1;
  69150. y_end = -1;
  69151. break;
  69152. case TGATools._ORIGIN_UR:
  69153. x_start = header.width - 1;
  69154. x_step = -1;
  69155. x_end = -1;
  69156. y_start = 0;
  69157. y_step = 1;
  69158. y_end = header.height;
  69159. break;
  69160. case TGATools._ORIGIN_BR:
  69161. x_start = header.width - 1;
  69162. x_step = -1;
  69163. x_end = -1;
  69164. y_start = header.height - 1;
  69165. y_step = -1;
  69166. y_end = -1;
  69167. break;
  69168. }
  69169. // Load the specify method
  69170. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  69171. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  69172. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  69173. };
  69174. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  69175. var image = pixel_data, colormap = palettes;
  69176. var width = header.width, height = header.height;
  69177. var color, i = 0, x, y;
  69178. var imageData = new Uint8Array(width * height * 4);
  69179. for (y = y_start; y !== y_end; y += y_step) {
  69180. for (x = x_start; x !== x_end; x += x_step, i++) {
  69181. color = image[i];
  69182. imageData[(x + width * y) * 4 + 3] = 255;
  69183. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  69184. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  69185. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  69186. }
  69187. }
  69188. return imageData;
  69189. };
  69190. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  69191. var image = pixel_data;
  69192. var width = header.width, height = header.height;
  69193. var color, i = 0, x, y;
  69194. var imageData = new Uint8Array(width * height * 4);
  69195. for (y = y_start; y !== y_end; y += y_step) {
  69196. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  69197. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  69198. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  69199. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  69200. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  69201. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  69202. }
  69203. }
  69204. return imageData;
  69205. };
  69206. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  69207. var image = pixel_data;
  69208. var width = header.width, height = header.height;
  69209. var i = 0, x, y;
  69210. var imageData = new Uint8Array(width * height * 4);
  69211. for (y = y_start; y !== y_end; y += y_step) {
  69212. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  69213. imageData[(x + width * y) * 4 + 3] = 255;
  69214. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  69215. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  69216. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  69217. }
  69218. }
  69219. return imageData;
  69220. };
  69221. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  69222. var image = pixel_data;
  69223. var width = header.width, height = header.height;
  69224. var i = 0, x, y;
  69225. var imageData = new Uint8Array(width * height * 4);
  69226. for (y = y_start; y !== y_end; y += y_step) {
  69227. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  69228. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  69229. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  69230. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  69231. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  69232. }
  69233. }
  69234. return imageData;
  69235. };
  69236. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  69237. var image = pixel_data;
  69238. var width = header.width, height = header.height;
  69239. var color, i = 0, x, y;
  69240. var imageData = new Uint8Array(width * height * 4);
  69241. for (y = y_start; y !== y_end; y += y_step) {
  69242. for (x = x_start; x !== x_end; x += x_step, i++) {
  69243. color = image[i];
  69244. imageData[(x + width * y) * 4 + 0] = color;
  69245. imageData[(x + width * y) * 4 + 1] = color;
  69246. imageData[(x + width * y) * 4 + 2] = color;
  69247. imageData[(x + width * y) * 4 + 3] = 255;
  69248. }
  69249. }
  69250. return imageData;
  69251. };
  69252. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  69253. var image = pixel_data;
  69254. var width = header.width, height = header.height;
  69255. var i = 0, x, y;
  69256. var imageData = new Uint8Array(width * height * 4);
  69257. for (y = y_start; y !== y_end; y += y_step) {
  69258. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  69259. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  69260. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  69261. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  69262. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  69263. }
  69264. }
  69265. return imageData;
  69266. };
  69267. //private static _TYPE_NO_DATA = 0;
  69268. TGATools._TYPE_INDEXED = 1;
  69269. TGATools._TYPE_RGB = 2;
  69270. TGATools._TYPE_GREY = 3;
  69271. TGATools._TYPE_RLE_INDEXED = 9;
  69272. TGATools._TYPE_RLE_RGB = 10;
  69273. TGATools._TYPE_RLE_GREY = 11;
  69274. TGATools._ORIGIN_MASK = 0x30;
  69275. TGATools._ORIGIN_SHIFT = 0x04;
  69276. TGATools._ORIGIN_BL = 0x00;
  69277. TGATools._ORIGIN_BR = 0x01;
  69278. TGATools._ORIGIN_UL = 0x02;
  69279. TGATools._ORIGIN_UR = 0x03;
  69280. return TGATools;
  69281. }());
  69282. Internals.TGATools = TGATools;
  69283. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  69284. })(BABYLON || (BABYLON = {}));
  69285. //# sourceMappingURL=babylon.tga.js.map
  69286. var BABYLON;
  69287. (function (BABYLON) {
  69288. var Internals;
  69289. (function (Internals) {
  69290. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  69291. // All values and structures referenced from:
  69292. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  69293. var DDS_MAGIC = 0x20534444;
  69294. var
  69295. //DDSD_CAPS = 0x1,
  69296. //DDSD_HEIGHT = 0x2,
  69297. //DDSD_WIDTH = 0x4,
  69298. //DDSD_PITCH = 0x8,
  69299. //DDSD_PIXELFORMAT = 0x1000,
  69300. DDSD_MIPMAPCOUNT = 0x20000;
  69301. //DDSD_LINEARSIZE = 0x80000,
  69302. //DDSD_DEPTH = 0x800000;
  69303. // var DDSCAPS_COMPLEX = 0x8,
  69304. // DDSCAPS_MIPMAP = 0x400000,
  69305. // DDSCAPS_TEXTURE = 0x1000;
  69306. var DDSCAPS2_CUBEMAP = 0x200;
  69307. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  69308. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  69309. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  69310. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  69311. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  69312. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  69313. // DDSCAPS2_VOLUME = 0x200000;
  69314. var
  69315. //DDPF_ALPHAPIXELS = 0x1,
  69316. //DDPF_ALPHA = 0x2,
  69317. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  69318. //DDPF_YUV = 0x200,
  69319. DDPF_LUMINANCE = 0x20000;
  69320. function FourCCToInt32(value) {
  69321. return value.charCodeAt(0) +
  69322. (value.charCodeAt(1) << 8) +
  69323. (value.charCodeAt(2) << 16) +
  69324. (value.charCodeAt(3) << 24);
  69325. }
  69326. function Int32ToFourCC(value) {
  69327. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  69328. }
  69329. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  69330. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  69331. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  69332. var FOURCC_DX10 = FourCCToInt32("DX10");
  69333. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  69334. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  69335. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  69336. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  69337. var headerLengthInt = 31; // The header length in 32 bit ints
  69338. // Offsets into the header array
  69339. var off_magic = 0;
  69340. var off_size = 1;
  69341. var off_flags = 2;
  69342. var off_height = 3;
  69343. var off_width = 4;
  69344. var off_mipmapCount = 7;
  69345. var off_pfFlags = 20;
  69346. var off_pfFourCC = 21;
  69347. var off_RGBbpp = 22;
  69348. // var off_RMask = 23;
  69349. // var off_GMask = 24;
  69350. // var off_BMask = 25;
  69351. // var off_AMask = 26;
  69352. // var off_caps1 = 27;
  69353. var off_caps2 = 28;
  69354. // var off_caps3 = 29;
  69355. // var off_caps4 = 30;
  69356. var off_dxgiFormat = 32;
  69357. ;
  69358. var DDSTools = /** @class */ (function () {
  69359. function DDSTools() {
  69360. }
  69361. DDSTools.GetDDSInfo = function (arrayBuffer) {
  69362. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  69363. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  69364. var mipmapCount = 1;
  69365. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  69366. mipmapCount = Math.max(1, header[off_mipmapCount]);
  69367. }
  69368. var fourCC = header[off_pfFourCC];
  69369. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  69370. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  69371. switch (fourCC) {
  69372. case FOURCC_D3DFMT_R16G16B16A16F:
  69373. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69374. break;
  69375. case FOURCC_D3DFMT_R32G32B32A32F:
  69376. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  69377. break;
  69378. case FOURCC_DX10:
  69379. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  69380. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69381. break;
  69382. }
  69383. }
  69384. return {
  69385. width: header[off_width],
  69386. height: header[off_height],
  69387. mipmapCount: mipmapCount,
  69388. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  69389. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  69390. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  69391. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  69392. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  69393. dxgiFormat: dxgiFormat,
  69394. textureType: textureType
  69395. };
  69396. };
  69397. DDSTools._ToHalfFloat = function (value) {
  69398. if (!DDSTools._FloatView) {
  69399. DDSTools._FloatView = new Float32Array(1);
  69400. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  69401. }
  69402. DDSTools._FloatView[0] = value;
  69403. var x = DDSTools._Int32View[0];
  69404. var bits = (x >> 16) & 0x8000; /* Get the sign */
  69405. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  69406. var e = (x >> 23) & 0xff; /* Using int is faster here */
  69407. /* If zero, or denormal, or exponent underflows too much for a denormal
  69408. * half, return signed zero. */
  69409. if (e < 103) {
  69410. return bits;
  69411. }
  69412. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  69413. if (e > 142) {
  69414. bits |= 0x7c00;
  69415. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  69416. * not Inf, so make sure we set one mantissa bit too. */
  69417. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  69418. return bits;
  69419. }
  69420. /* If exponent underflows but not too much, return a denormal */
  69421. if (e < 113) {
  69422. m |= 0x0800;
  69423. /* Extra rounding may overflow and set mantissa to 0 and exponent
  69424. * to 1, which is OK. */
  69425. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  69426. return bits;
  69427. }
  69428. bits |= ((e - 112) << 10) | (m >> 1);
  69429. bits += m & 1;
  69430. return bits;
  69431. };
  69432. DDSTools._FromHalfFloat = function (value) {
  69433. var s = (value & 0x8000) >> 15;
  69434. var e = (value & 0x7C00) >> 10;
  69435. var f = value & 0x03FF;
  69436. if (e === 0) {
  69437. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  69438. }
  69439. else if (e == 0x1F) {
  69440. return f ? NaN : ((s ? -1 : 1) * Infinity);
  69441. }
  69442. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  69443. };
  69444. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  69445. var destArray = new Float32Array(dataLength);
  69446. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  69447. var index = 0;
  69448. for (var y = 0; y < height; y++) {
  69449. for (var x = 0; x < width; x++) {
  69450. var srcPos = (x + y * width) * 4;
  69451. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  69452. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  69453. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  69454. if (DDSTools.StoreLODInAlphaChannel) {
  69455. destArray[index + 3] = lod;
  69456. }
  69457. else {
  69458. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  69459. }
  69460. index += 4;
  69461. }
  69462. }
  69463. return destArray;
  69464. };
  69465. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  69466. if (DDSTools.StoreLODInAlphaChannel) {
  69467. var destArray = new Uint16Array(dataLength);
  69468. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  69469. var index = 0;
  69470. for (var y = 0; y < height; y++) {
  69471. for (var x = 0; x < width; x++) {
  69472. var srcPos = (x + y * width) * 4;
  69473. destArray[index] = srcData[srcPos];
  69474. destArray[index + 1] = srcData[srcPos + 1];
  69475. destArray[index + 2] = srcData[srcPos + 2];
  69476. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  69477. index += 4;
  69478. }
  69479. }
  69480. return destArray;
  69481. }
  69482. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  69483. };
  69484. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  69485. if (DDSTools.StoreLODInAlphaChannel) {
  69486. var destArray = new Float32Array(dataLength);
  69487. var srcData = new Float32Array(arrayBuffer, dataOffset);
  69488. var index = 0;
  69489. for (var y = 0; y < height; y++) {
  69490. for (var x = 0; x < width; x++) {
  69491. var srcPos = (x + y * width) * 4;
  69492. destArray[index] = srcData[srcPos];
  69493. destArray[index + 1] = srcData[srcPos + 1];
  69494. destArray[index + 2] = srcData[srcPos + 2];
  69495. destArray[index + 3] = lod;
  69496. index += 4;
  69497. }
  69498. }
  69499. return destArray;
  69500. }
  69501. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  69502. };
  69503. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  69504. var destArray = new Uint8Array(dataLength);
  69505. var srcData = new Float32Array(arrayBuffer, dataOffset);
  69506. var index = 0;
  69507. for (var y = 0; y < height; y++) {
  69508. for (var x = 0; x < width; x++) {
  69509. var srcPos = (x + y * width) * 4;
  69510. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  69511. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  69512. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  69513. if (DDSTools.StoreLODInAlphaChannel) {
  69514. destArray[index + 3] = lod;
  69515. }
  69516. else {
  69517. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  69518. }
  69519. index += 4;
  69520. }
  69521. }
  69522. return destArray;
  69523. };
  69524. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  69525. var destArray = new Uint8Array(dataLength);
  69526. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  69527. var index = 0;
  69528. for (var y = 0; y < height; y++) {
  69529. for (var x = 0; x < width; x++) {
  69530. var srcPos = (x + y * width) * 4;
  69531. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  69532. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  69533. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  69534. if (DDSTools.StoreLODInAlphaChannel) {
  69535. destArray[index + 3] = lod;
  69536. }
  69537. else {
  69538. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  69539. }
  69540. index += 4;
  69541. }
  69542. }
  69543. return destArray;
  69544. };
  69545. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  69546. var byteArray = new Uint8Array(dataLength);
  69547. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  69548. var index = 0;
  69549. for (var y = 0; y < height; y++) {
  69550. for (var x = 0; x < width; x++) {
  69551. var srcPos = (x + y * width) * 4;
  69552. byteArray[index] = srcData[srcPos + 2];
  69553. byteArray[index + 1] = srcData[srcPos + 1];
  69554. byteArray[index + 2] = srcData[srcPos];
  69555. byteArray[index + 3] = srcData[srcPos + 3];
  69556. index += 4;
  69557. }
  69558. }
  69559. return byteArray;
  69560. };
  69561. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  69562. var byteArray = new Uint8Array(dataLength);
  69563. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  69564. var index = 0;
  69565. for (var y = 0; y < height; y++) {
  69566. for (var x = 0; x < width; x++) {
  69567. var srcPos = (x + y * width) * 3;
  69568. byteArray[index] = srcData[srcPos + 2];
  69569. byteArray[index + 1] = srcData[srcPos + 1];
  69570. byteArray[index + 2] = srcData[srcPos];
  69571. index += 3;
  69572. }
  69573. }
  69574. return byteArray;
  69575. };
  69576. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  69577. var byteArray = new Uint8Array(dataLength);
  69578. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  69579. var index = 0;
  69580. for (var y = 0; y < height; y++) {
  69581. for (var x = 0; x < width; x++) {
  69582. var srcPos = (x + y * width);
  69583. byteArray[index] = srcData[srcPos];
  69584. index++;
  69585. }
  69586. }
  69587. return byteArray;
  69588. };
  69589. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  69590. if (lodIndex === void 0) { lodIndex = -1; }
  69591. var ext = engine.getCaps().s3tc;
  69592. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  69593. var fourCC, width, height, dataLength = 0, dataOffset;
  69594. var byteArray, mipmapCount, mip;
  69595. var internalFormat = 0;
  69596. var format = 0;
  69597. var blockBytes = 1;
  69598. if (header[off_magic] !== DDS_MAGIC) {
  69599. BABYLON.Tools.Error("Invalid magic number in DDS header");
  69600. return;
  69601. }
  69602. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  69603. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  69604. return;
  69605. }
  69606. if (info.isCompressed && !ext) {
  69607. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  69608. return;
  69609. }
  69610. var bpp = header[off_RGBbpp];
  69611. dataOffset = header[off_size] + 4;
  69612. var computeFormats = false;
  69613. if (info.isFourCC) {
  69614. fourCC = header[off_pfFourCC];
  69615. switch (fourCC) {
  69616. case FOURCC_DXT1:
  69617. blockBytes = 8;
  69618. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  69619. break;
  69620. case FOURCC_DXT3:
  69621. blockBytes = 16;
  69622. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  69623. break;
  69624. case FOURCC_DXT5:
  69625. blockBytes = 16;
  69626. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  69627. break;
  69628. case FOURCC_D3DFMT_R16G16B16A16F:
  69629. computeFormats = true;
  69630. break;
  69631. case FOURCC_D3DFMT_R32G32B32A32F:
  69632. computeFormats = true;
  69633. break;
  69634. case FOURCC_DX10:
  69635. // There is an additionnal header so dataOffset need to be changed
  69636. dataOffset += 5 * 4; // 5 uints
  69637. var supported = false;
  69638. switch (info.dxgiFormat) {
  69639. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  69640. computeFormats = true;
  69641. supported = true;
  69642. break;
  69643. case DXGI_FORMAT_B8G8R8X8_UNORM:
  69644. info.isRGB = true;
  69645. info.isFourCC = false;
  69646. bpp = 32;
  69647. supported = true;
  69648. break;
  69649. }
  69650. if (supported) {
  69651. break;
  69652. }
  69653. default:
  69654. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  69655. return;
  69656. }
  69657. }
  69658. if (computeFormats) {
  69659. format = engine._getWebGLTextureType(info.textureType);
  69660. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  69661. }
  69662. mipmapCount = 1;
  69663. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  69664. mipmapCount = Math.max(1, header[off_mipmapCount]);
  69665. }
  69666. for (var face = 0; face < faces; face++) {
  69667. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  69668. width = header[off_width];
  69669. height = header[off_height];
  69670. for (mip = 0; mip < mipmapCount; ++mip) {
  69671. if (lodIndex === -1 || lodIndex === mip) {
  69672. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  69673. var i = (lodIndex === -1) ? mip : 0;
  69674. if (!info.isCompressed && info.isFourCC) {
  69675. dataLength = width * height * 4;
  69676. var floatArray = null;
  69677. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  69678. if (bpp === 128) {
  69679. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  69680. }
  69681. else if (bpp === 64) {
  69682. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  69683. }
  69684. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  69685. format = engine._getWebGLTextureType(info.textureType);
  69686. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  69687. }
  69688. else {
  69689. if (bpp === 128) {
  69690. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  69691. }
  69692. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  69693. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  69694. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  69695. format = engine._getWebGLTextureType(info.textureType);
  69696. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  69697. }
  69698. else {
  69699. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  69700. }
  69701. }
  69702. if (floatArray) {
  69703. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  69704. }
  69705. }
  69706. else if (info.isRGB) {
  69707. if (bpp === 24) {
  69708. dataLength = width * height * 3;
  69709. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  69710. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  69711. }
  69712. else {
  69713. dataLength = width * height * 4;
  69714. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  69715. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  69716. }
  69717. }
  69718. else if (info.isLuminance) {
  69719. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  69720. var unpaddedRowSize = width;
  69721. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  69722. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  69723. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  69724. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  69725. }
  69726. else {
  69727. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  69728. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  69729. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  69730. }
  69731. }
  69732. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  69733. width *= 0.5;
  69734. height *= 0.5;
  69735. width = Math.max(1.0, width);
  69736. height = Math.max(1.0, height);
  69737. }
  69738. if (currentFace !== undefined) {
  69739. // Loading a single face
  69740. break;
  69741. }
  69742. }
  69743. };
  69744. DDSTools.StoreLODInAlphaChannel = false;
  69745. return DDSTools;
  69746. }());
  69747. Internals.DDSTools = DDSTools;
  69748. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  69749. })(BABYLON || (BABYLON = {}));
  69750. //# sourceMappingURL=babylon.dds.js.map
  69751. var BABYLON;
  69752. (function (BABYLON) {
  69753. var Internals;
  69754. (function (Internals) {
  69755. /**
  69756. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  69757. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  69758. */
  69759. var KhronosTextureContainer = /** @class */ (function () {
  69760. /**
  69761. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  69762. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  69763. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  69764. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  69765. */
  69766. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  69767. this.arrayBuffer = arrayBuffer;
  69768. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  69769. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  69770. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  69771. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  69772. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  69773. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  69774. BABYLON.Tools.Error("texture missing KTX identifier");
  69775. return;
  69776. }
  69777. // load the reset of the header in native 32 bit int
  69778. var header = new Int32Array(this.arrayBuffer, 12, 13);
  69779. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  69780. var oppositeEndianess = header[0] === 0x01020304;
  69781. // read all the header elements in order they exist in the file, without modification (sans endainness)
  69782. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  69783. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  69784. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  69785. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  69786. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  69787. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  69788. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  69789. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  69790. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  69791. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  69792. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  69793. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  69794. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  69795. if (this.glType !== 0) {
  69796. BABYLON.Tools.Error("only compressed formats currently supported");
  69797. return;
  69798. }
  69799. else {
  69800. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  69801. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  69802. }
  69803. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  69804. BABYLON.Tools.Error("only 2D textures currently supported");
  69805. return;
  69806. }
  69807. if (this.numberOfArrayElements !== 0) {
  69808. BABYLON.Tools.Error("texture arrays not currently supported");
  69809. return;
  69810. }
  69811. if (this.numberOfFaces !== facesExpected) {
  69812. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  69813. return;
  69814. }
  69815. // we now have a completely validated file, so could use existence of loadType as success
  69816. // would need to make this more elaborate & adjust checks above to support more than one load type
  69817. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  69818. }
  69819. // not as fast hardware based, but will probably never need to use
  69820. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  69821. return ((val & 0xFF) << 24)
  69822. | ((val & 0xFF00) << 8)
  69823. | ((val >> 8) & 0xFF00)
  69824. | ((val >> 24) & 0xFF);
  69825. };
  69826. /**
  69827. * It is assumed that the texture has already been created & is currently bound
  69828. */
  69829. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  69830. switch (this.loadType) {
  69831. case KhronosTextureContainer.COMPRESSED_2D:
  69832. this._upload2DCompressedLevels(gl, loadMipmaps);
  69833. break;
  69834. case KhronosTextureContainer.TEX_2D:
  69835. case KhronosTextureContainer.COMPRESSED_3D:
  69836. case KhronosTextureContainer.TEX_3D:
  69837. }
  69838. };
  69839. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  69840. // initialize width & height for level 1
  69841. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  69842. var width = this.pixelWidth;
  69843. var height = this.pixelHeight;
  69844. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  69845. for (var level = 0; level < mipmapCount; level++) {
  69846. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  69847. for (var face = 0; face < this.numberOfFaces; face++) {
  69848. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  69849. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  69850. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  69851. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  69852. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  69853. }
  69854. width = Math.max(1.0, width * 0.5);
  69855. height = Math.max(1.0, height * 0.5);
  69856. }
  69857. };
  69858. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  69859. // load types
  69860. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  69861. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  69862. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  69863. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  69864. return KhronosTextureContainer;
  69865. }());
  69866. Internals.KhronosTextureContainer = KhronosTextureContainer;
  69867. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  69868. })(BABYLON || (BABYLON = {}));
  69869. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  69870. var BABYLON;
  69871. (function (BABYLON) {
  69872. var Debug;
  69873. (function (Debug) {
  69874. /**
  69875. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  69876. */
  69877. var SkeletonViewer = /** @class */ (function () {
  69878. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  69879. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  69880. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  69881. this.skeleton = skeleton;
  69882. this.mesh = mesh;
  69883. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  69884. this.renderingGroupId = renderingGroupId;
  69885. this.color = BABYLON.Color3.White();
  69886. this._debugLines = new Array();
  69887. this._isEnabled = false;
  69888. this._scene = scene;
  69889. this.update();
  69890. this._renderFunction = this.update.bind(this);
  69891. }
  69892. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  69893. get: function () {
  69894. return this._isEnabled;
  69895. },
  69896. set: function (value) {
  69897. if (this._isEnabled === value) {
  69898. return;
  69899. }
  69900. this._isEnabled = value;
  69901. if (value) {
  69902. this._scene.registerBeforeRender(this._renderFunction);
  69903. }
  69904. else {
  69905. this._scene.unregisterBeforeRender(this._renderFunction);
  69906. }
  69907. },
  69908. enumerable: true,
  69909. configurable: true
  69910. });
  69911. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  69912. if (x === void 0) { x = 0; }
  69913. if (y === void 0) { y = 0; }
  69914. if (z === void 0) { z = 0; }
  69915. var tmat = BABYLON.Tmp.Matrix[0];
  69916. var parentBone = bone.getParent();
  69917. tmat.copyFrom(bone.getLocalMatrix());
  69918. if (x !== 0 || y !== 0 || z !== 0) {
  69919. var tmat2 = BABYLON.Tmp.Matrix[1];
  69920. BABYLON.Matrix.IdentityToRef(tmat2);
  69921. tmat2.m[12] = x;
  69922. tmat2.m[13] = y;
  69923. tmat2.m[14] = z;
  69924. tmat2.multiplyToRef(tmat, tmat);
  69925. }
  69926. if (parentBone) {
  69927. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  69928. }
  69929. tmat.multiplyToRef(meshMat, tmat);
  69930. position.x = tmat.m[12];
  69931. position.y = tmat.m[13];
  69932. position.z = tmat.m[14];
  69933. };
  69934. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  69935. var len = bones.length;
  69936. var meshPos = this.mesh.position;
  69937. for (var i = 0; i < len; i++) {
  69938. var bone = bones[i];
  69939. var points = this._debugLines[i];
  69940. if (!points) {
  69941. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69942. this._debugLines[i] = points;
  69943. }
  69944. this._getBonePosition(points[0], bone, meshMat);
  69945. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  69946. points[0].subtractInPlace(meshPos);
  69947. points[1].subtractInPlace(meshPos);
  69948. }
  69949. };
  69950. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  69951. var len = bones.length;
  69952. var boneNum = 0;
  69953. var meshPos = this.mesh.position;
  69954. for (var i = len - 1; i >= 0; i--) {
  69955. var childBone = bones[i];
  69956. var parentBone = childBone.getParent();
  69957. if (!parentBone) {
  69958. continue;
  69959. }
  69960. var points = this._debugLines[boneNum];
  69961. if (!points) {
  69962. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69963. this._debugLines[boneNum] = points;
  69964. }
  69965. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  69966. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  69967. points[0].subtractInPlace(meshPos);
  69968. points[1].subtractInPlace(meshPos);
  69969. boneNum++;
  69970. }
  69971. };
  69972. SkeletonViewer.prototype.update = function () {
  69973. if (this.autoUpdateBonesMatrices) {
  69974. this.skeleton.computeAbsoluteTransforms();
  69975. }
  69976. if (this.skeleton.bones[0].length === undefined) {
  69977. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  69978. }
  69979. else {
  69980. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  69981. }
  69982. if (!this._debugMesh) {
  69983. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  69984. this._debugMesh.renderingGroupId = this.renderingGroupId;
  69985. }
  69986. else {
  69987. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  69988. }
  69989. this._debugMesh.position.copyFrom(this.mesh.position);
  69990. this._debugMesh.color = this.color;
  69991. };
  69992. SkeletonViewer.prototype.dispose = function () {
  69993. if (this._debugMesh) {
  69994. this.isEnabled = false;
  69995. this._debugMesh.dispose();
  69996. this._debugMesh = null;
  69997. }
  69998. };
  69999. return SkeletonViewer;
  70000. }());
  70001. Debug.SkeletonViewer = SkeletonViewer;
  70002. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  70003. })(BABYLON || (BABYLON = {}));
  70004. //# sourceMappingURL=babylon.skeletonViewer.js.map
  70005. var BABYLON;
  70006. (function (BABYLON) {
  70007. var Debug;
  70008. (function (Debug) {
  70009. var AxesViewer = /** @class */ (function () {
  70010. function AxesViewer(scene, scaleLines) {
  70011. if (scaleLines === void 0) { scaleLines = 1; }
  70012. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70013. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70014. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70015. this.scaleLines = 1;
  70016. this.scaleLines = scaleLines;
  70017. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  70018. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  70019. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  70020. this._xmesh.renderingGroupId = 2;
  70021. this._ymesh.renderingGroupId = 2;
  70022. this._zmesh.renderingGroupId = 2;
  70023. this._xmesh.material.checkReadyOnlyOnce = true;
  70024. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  70025. this._ymesh.material.checkReadyOnlyOnce = true;
  70026. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  70027. this._zmesh.material.checkReadyOnlyOnce = true;
  70028. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  70029. this.scene = scene;
  70030. }
  70031. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  70032. var scaleLines = this.scaleLines;
  70033. if (this._xmesh) {
  70034. this._xmesh.position.copyFrom(position);
  70035. }
  70036. if (this._ymesh) {
  70037. this._ymesh.position.copyFrom(position);
  70038. }
  70039. if (this._zmesh) {
  70040. this._zmesh.position.copyFrom(position);
  70041. }
  70042. var point2 = this._xline[1];
  70043. point2.x = xaxis.x * scaleLines;
  70044. point2.y = xaxis.y * scaleLines;
  70045. point2.z = xaxis.z * scaleLines;
  70046. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  70047. point2 = this._yline[1];
  70048. point2.x = yaxis.x * scaleLines;
  70049. point2.y = yaxis.y * scaleLines;
  70050. point2.z = yaxis.z * scaleLines;
  70051. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  70052. point2 = this._zline[1];
  70053. point2.x = zaxis.x * scaleLines;
  70054. point2.y = zaxis.y * scaleLines;
  70055. point2.z = zaxis.z * scaleLines;
  70056. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  70057. };
  70058. AxesViewer.prototype.dispose = function () {
  70059. if (this._xmesh) {
  70060. this._xmesh.dispose();
  70061. }
  70062. if (this._ymesh) {
  70063. this._ymesh.dispose();
  70064. }
  70065. if (this._zmesh) {
  70066. this._zmesh.dispose();
  70067. }
  70068. this._xmesh = null;
  70069. this._ymesh = null;
  70070. this._zmesh = null;
  70071. this.scene = null;
  70072. };
  70073. return AxesViewer;
  70074. }());
  70075. Debug.AxesViewer = AxesViewer;
  70076. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  70077. })(BABYLON || (BABYLON = {}));
  70078. //# sourceMappingURL=babylon.axesViewer.js.map
  70079. var BABYLON;
  70080. (function (BABYLON) {
  70081. var Debug;
  70082. (function (Debug) {
  70083. var BoneAxesViewer = /** @class */ (function (_super) {
  70084. __extends(BoneAxesViewer, _super);
  70085. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  70086. if (scaleLines === void 0) { scaleLines = 1; }
  70087. var _this = _super.call(this, scene, scaleLines) || this;
  70088. _this.pos = BABYLON.Vector3.Zero();
  70089. _this.xaxis = BABYLON.Vector3.Zero();
  70090. _this.yaxis = BABYLON.Vector3.Zero();
  70091. _this.zaxis = BABYLON.Vector3.Zero();
  70092. _this.mesh = mesh;
  70093. _this.bone = bone;
  70094. return _this;
  70095. }
  70096. BoneAxesViewer.prototype.update = function () {
  70097. if (!this.mesh || !this.bone) {
  70098. return;
  70099. }
  70100. var bone = this.bone;
  70101. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  70102. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  70103. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  70104. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  70105. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  70106. };
  70107. BoneAxesViewer.prototype.dispose = function () {
  70108. if (this.mesh) {
  70109. this.mesh = null;
  70110. this.bone = null;
  70111. _super.prototype.dispose.call(this);
  70112. }
  70113. };
  70114. return BoneAxesViewer;
  70115. }(Debug.AxesViewer));
  70116. Debug.BoneAxesViewer = BoneAxesViewer;
  70117. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  70118. })(BABYLON || (BABYLON = {}));
  70119. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  70120. var BABYLON;
  70121. (function (BABYLON) {
  70122. var RayHelper = /** @class */ (function () {
  70123. function RayHelper(ray) {
  70124. this.ray = ray;
  70125. }
  70126. RayHelper.CreateAndShow = function (ray, scene, color) {
  70127. var helper = new RayHelper(ray);
  70128. helper.show(scene, color);
  70129. return helper;
  70130. };
  70131. RayHelper.prototype.show = function (scene, color) {
  70132. if (!this._renderFunction && this.ray) {
  70133. var ray = this.ray;
  70134. this._renderFunction = this._render.bind(this);
  70135. this._scene = scene;
  70136. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  70137. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  70138. if (this._renderFunction) {
  70139. this._scene.registerBeforeRender(this._renderFunction);
  70140. }
  70141. }
  70142. if (color && this._renderLine) {
  70143. this._renderLine.color.copyFrom(color);
  70144. }
  70145. };
  70146. RayHelper.prototype.hide = function () {
  70147. if (this._renderFunction && this._scene) {
  70148. this._scene.unregisterBeforeRender(this._renderFunction);
  70149. this._scene = null;
  70150. this._renderFunction = null;
  70151. if (this._renderLine) {
  70152. this._renderLine.dispose();
  70153. this._renderLine = null;
  70154. }
  70155. this._renderPoints = [];
  70156. }
  70157. };
  70158. RayHelper.prototype._render = function () {
  70159. var ray = this.ray;
  70160. if (!ray) {
  70161. return;
  70162. }
  70163. var point = this._renderPoints[1];
  70164. var len = Math.min(ray.length, 1000000);
  70165. point.copyFrom(ray.direction);
  70166. point.scaleInPlace(len);
  70167. point.addInPlace(ray.origin);
  70168. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  70169. };
  70170. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  70171. this._attachedToMesh = mesh;
  70172. var ray = this.ray;
  70173. if (!ray) {
  70174. return;
  70175. }
  70176. if (!ray.direction) {
  70177. ray.direction = BABYLON.Vector3.Zero();
  70178. }
  70179. if (!ray.origin) {
  70180. ray.origin = BABYLON.Vector3.Zero();
  70181. }
  70182. if (length) {
  70183. ray.length = length;
  70184. }
  70185. if (!meshSpaceOrigin) {
  70186. meshSpaceOrigin = BABYLON.Vector3.Zero();
  70187. }
  70188. if (!meshSpaceDirection) {
  70189. // -1 so that this will work with Mesh.lookAt
  70190. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  70191. }
  70192. if (!this._meshSpaceDirection) {
  70193. this._meshSpaceDirection = meshSpaceDirection.clone();
  70194. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  70195. }
  70196. else {
  70197. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  70198. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  70199. }
  70200. if (!this._updateToMeshFunction) {
  70201. this._updateToMeshFunction = this._updateToMesh.bind(this);
  70202. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  70203. }
  70204. this._updateToMesh();
  70205. };
  70206. RayHelper.prototype.detachFromMesh = function () {
  70207. if (this._attachedToMesh) {
  70208. if (this._updateToMeshFunction) {
  70209. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  70210. }
  70211. this._attachedToMesh = null;
  70212. this._updateToMeshFunction = null;
  70213. }
  70214. };
  70215. RayHelper.prototype._updateToMesh = function () {
  70216. var ray = this.ray;
  70217. if (!this._attachedToMesh || !ray) {
  70218. return;
  70219. }
  70220. if (this._attachedToMesh._isDisposed) {
  70221. this.detachFromMesh();
  70222. return;
  70223. }
  70224. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  70225. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  70226. };
  70227. RayHelper.prototype.dispose = function () {
  70228. this.hide();
  70229. this.detachFromMesh();
  70230. this.ray = null;
  70231. };
  70232. return RayHelper;
  70233. }());
  70234. BABYLON.RayHelper = RayHelper;
  70235. })(BABYLON || (BABYLON = {}));
  70236. //# sourceMappingURL=babylon.rayHelper.js.map
  70237. var BABYLON;
  70238. (function (BABYLON) {
  70239. // load the inspector using require, if not present in the global namespace.
  70240. var DebugLayer = /** @class */ (function () {
  70241. function DebugLayer(scene) {
  70242. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  70243. this._scene = scene;
  70244. // load inspector using require, if it doesn't exist on the global namespace.
  70245. }
  70246. /** Creates the inspector window. */
  70247. DebugLayer.prototype._createInspector = function (config) {
  70248. if (config === void 0) { config = {}; }
  70249. var popup = config.popup || false;
  70250. var initialTab = config.initialTab || 0;
  70251. var parentElement = config.parentElement || null;
  70252. if (!this._inspector) {
  70253. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  70254. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  70255. } // else nothing to do,; instance is already existing
  70256. };
  70257. DebugLayer.prototype.isVisible = function () {
  70258. if (!this._inspector) {
  70259. return false;
  70260. }
  70261. return true;
  70262. };
  70263. DebugLayer.prototype.hide = function () {
  70264. if (this._inspector) {
  70265. try {
  70266. this._inspector.dispose();
  70267. }
  70268. catch (e) {
  70269. // If the inspector has been removed directly from the inspector tool
  70270. }
  70271. this._inspector = null;
  70272. }
  70273. };
  70274. DebugLayer.prototype.show = function (config) {
  70275. if (config === void 0) { config = {}; }
  70276. if (typeof this.BJSINSPECTOR == 'undefined') {
  70277. // Load inspector and add it to the DOM
  70278. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  70279. }
  70280. else {
  70281. // Otherwise creates the inspector
  70282. this._createInspector(config);
  70283. }
  70284. };
  70285. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  70286. return DebugLayer;
  70287. }());
  70288. BABYLON.DebugLayer = DebugLayer;
  70289. })(BABYLON || (BABYLON = {}));
  70290. //# sourceMappingURL=babylon.debugLayer.js.map
  70291. var BABYLON;
  70292. (function (BABYLON) {
  70293. var Debug;
  70294. (function (Debug) {
  70295. var PhysicsViewer = /** @class */ (function () {
  70296. function PhysicsViewer(scene) {
  70297. this._impostors = [];
  70298. this._meshes = [];
  70299. this._numMeshes = 0;
  70300. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  70301. var physicEngine = this._scene.getPhysicsEngine();
  70302. if (physicEngine) {
  70303. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  70304. }
  70305. }
  70306. PhysicsViewer.prototype._updateDebugMeshes = function () {
  70307. var plugin = this._physicsEnginePlugin;
  70308. for (var i = 0; i < this._numMeshes; i++) {
  70309. var impostor = this._impostors[i];
  70310. if (!impostor) {
  70311. continue;
  70312. }
  70313. if (impostor.isDisposed) {
  70314. this.hideImpostor(this._impostors[i--]);
  70315. }
  70316. else {
  70317. var mesh = this._meshes[i];
  70318. if (mesh && plugin) {
  70319. plugin.syncMeshWithImpostor(mesh, impostor);
  70320. }
  70321. }
  70322. }
  70323. };
  70324. PhysicsViewer.prototype.showImpostor = function (impostor) {
  70325. if (!this._scene) {
  70326. return;
  70327. }
  70328. for (var i = 0; i < this._numMeshes; i++) {
  70329. if (this._impostors[i] == impostor) {
  70330. return;
  70331. }
  70332. }
  70333. var debugMesh = this._getDebugMesh(impostor, this._scene);
  70334. if (debugMesh) {
  70335. this._impostors[this._numMeshes] = impostor;
  70336. this._meshes[this._numMeshes] = debugMesh;
  70337. if (this._numMeshes === 0) {
  70338. this._renderFunction = this._updateDebugMeshes.bind(this);
  70339. this._scene.registerBeforeRender(this._renderFunction);
  70340. }
  70341. this._numMeshes++;
  70342. }
  70343. };
  70344. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  70345. if (!impostor || !this._scene) {
  70346. return;
  70347. }
  70348. var removed = false;
  70349. for (var i = 0; i < this._numMeshes; i++) {
  70350. if (this._impostors[i] == impostor) {
  70351. var mesh = this._meshes[i];
  70352. if (!mesh) {
  70353. continue;
  70354. }
  70355. this._scene.removeMesh(mesh);
  70356. mesh.dispose();
  70357. this._numMeshes--;
  70358. if (this._numMeshes > 0) {
  70359. this._meshes[i] = this._meshes[this._numMeshes];
  70360. this._impostors[i] = this._impostors[this._numMeshes];
  70361. this._meshes[this._numMeshes] = null;
  70362. this._impostors[this._numMeshes] = null;
  70363. }
  70364. else {
  70365. this._meshes[0] = null;
  70366. this._impostors[0] = null;
  70367. }
  70368. removed = true;
  70369. break;
  70370. }
  70371. }
  70372. if (removed && this._numMeshes === 0) {
  70373. this._scene.unregisterBeforeRender(this._renderFunction);
  70374. }
  70375. };
  70376. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  70377. if (!this._debugMaterial) {
  70378. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  70379. this._debugMaterial.wireframe = true;
  70380. }
  70381. return this._debugMaterial;
  70382. };
  70383. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  70384. if (!this._debugBoxMesh) {
  70385. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  70386. this._debugBoxMesh.renderingGroupId = 1;
  70387. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  70388. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  70389. scene.removeMesh(this._debugBoxMesh);
  70390. }
  70391. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  70392. };
  70393. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  70394. if (!this._debugSphereMesh) {
  70395. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  70396. this._debugSphereMesh.renderingGroupId = 1;
  70397. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  70398. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  70399. scene.removeMesh(this._debugSphereMesh);
  70400. }
  70401. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  70402. };
  70403. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  70404. var mesh = null;
  70405. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  70406. mesh = this._getDebugBoxMesh(scene);
  70407. impostor.getBoxSizeToRef(mesh.scaling);
  70408. }
  70409. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  70410. mesh = this._getDebugSphereMesh(scene);
  70411. var radius = impostor.getRadius();
  70412. mesh.scaling.x = radius * 2;
  70413. mesh.scaling.y = radius * 2;
  70414. mesh.scaling.z = radius * 2;
  70415. }
  70416. return mesh;
  70417. };
  70418. PhysicsViewer.prototype.dispose = function () {
  70419. for (var i = 0; i < this._numMeshes; i++) {
  70420. this.hideImpostor(this._impostors[i]);
  70421. }
  70422. if (this._debugBoxMesh) {
  70423. this._debugBoxMesh.dispose();
  70424. }
  70425. if (this._debugSphereMesh) {
  70426. this._debugSphereMesh.dispose();
  70427. }
  70428. if (this._debugMaterial) {
  70429. this._debugMaterial.dispose();
  70430. }
  70431. this._impostors.length = 0;
  70432. this._scene = null;
  70433. this._physicsEnginePlugin = null;
  70434. };
  70435. return PhysicsViewer;
  70436. }());
  70437. Debug.PhysicsViewer = PhysicsViewer;
  70438. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  70439. })(BABYLON || (BABYLON = {}));
  70440. //# sourceMappingURL=babylon.physicsViewer.js.map
  70441. var BABYLON;
  70442. (function (BABYLON) {
  70443. var BoundingBoxRenderer = /** @class */ (function () {
  70444. function BoundingBoxRenderer(scene) {
  70445. this.frontColor = new BABYLON.Color3(1, 1, 1);
  70446. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  70447. this.showBackLines = true;
  70448. this.renderList = new BABYLON.SmartArray(32);
  70449. this._vertexBuffers = {};
  70450. this._scene = scene;
  70451. }
  70452. BoundingBoxRenderer.prototype._prepareRessources = function () {
  70453. if (this._colorShader) {
  70454. return;
  70455. }
  70456. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  70457. attributes: [BABYLON.VertexBuffer.PositionKind],
  70458. uniforms: ["world", "viewProjection", "color"]
  70459. });
  70460. var engine = this._scene.getEngine();
  70461. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  70462. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  70463. this._createIndexBuffer();
  70464. };
  70465. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  70466. var engine = this._scene.getEngine();
  70467. 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]);
  70468. };
  70469. BoundingBoxRenderer.prototype._rebuild = function () {
  70470. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70471. if (vb) {
  70472. vb._rebuild();
  70473. }
  70474. this._createIndexBuffer();
  70475. };
  70476. BoundingBoxRenderer.prototype.reset = function () {
  70477. this.renderList.reset();
  70478. };
  70479. BoundingBoxRenderer.prototype.render = function () {
  70480. if (this.renderList.length === 0) {
  70481. return;
  70482. }
  70483. this._prepareRessources();
  70484. if (!this._colorShader.isReady()) {
  70485. return;
  70486. }
  70487. var engine = this._scene.getEngine();
  70488. engine.setDepthWrite(false);
  70489. this._colorShader._preBind();
  70490. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  70491. var boundingBox = this.renderList.data[boundingBoxIndex];
  70492. var min = boundingBox.minimum;
  70493. var max = boundingBox.maximum;
  70494. var diff = max.subtract(min);
  70495. var median = min.add(diff.scale(0.5));
  70496. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  70497. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  70498. .multiply(boundingBox.getWorldMatrix());
  70499. // VBOs
  70500. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  70501. if (this.showBackLines) {
  70502. // Back
  70503. engine.setDepthFunctionToGreaterOrEqual();
  70504. this._scene.resetCachedMaterial();
  70505. this._colorShader.setColor4("color", this.backColor.toColor4());
  70506. this._colorShader.bind(worldMatrix);
  70507. // Draw order
  70508. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  70509. }
  70510. // Front
  70511. engine.setDepthFunctionToLess();
  70512. this._scene.resetCachedMaterial();
  70513. this._colorShader.setColor4("color", this.frontColor.toColor4());
  70514. this._colorShader.bind(worldMatrix);
  70515. // Draw order
  70516. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  70517. }
  70518. this._colorShader.unbind();
  70519. engine.setDepthFunctionToLessOrEqual();
  70520. engine.setDepthWrite(true);
  70521. };
  70522. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  70523. this._prepareRessources();
  70524. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  70525. return;
  70526. }
  70527. var engine = this._scene.getEngine();
  70528. engine.setDepthWrite(false);
  70529. engine.setColorWrite(false);
  70530. this._colorShader._preBind();
  70531. var boundingBox = mesh._boundingInfo.boundingBox;
  70532. var min = boundingBox.minimum;
  70533. var max = boundingBox.maximum;
  70534. var diff = max.subtract(min);
  70535. var median = min.add(diff.scale(0.5));
  70536. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  70537. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  70538. .multiply(boundingBox.getWorldMatrix());
  70539. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  70540. engine.setDepthFunctionToLess();
  70541. this._scene.resetCachedMaterial();
  70542. this._colorShader.bind(worldMatrix);
  70543. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 24);
  70544. this._colorShader.unbind();
  70545. engine.setDepthFunctionToLessOrEqual();
  70546. engine.setDepthWrite(true);
  70547. engine.setColorWrite(true);
  70548. };
  70549. BoundingBoxRenderer.prototype.dispose = function () {
  70550. if (!this._colorShader) {
  70551. return;
  70552. }
  70553. this.renderList.dispose();
  70554. this._colorShader.dispose();
  70555. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70556. if (buffer) {
  70557. buffer.dispose();
  70558. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70559. }
  70560. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  70561. };
  70562. return BoundingBoxRenderer;
  70563. }());
  70564. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  70565. })(BABYLON || (BABYLON = {}));
  70566. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  70567. var BABYLON;
  70568. (function (BABYLON) {
  70569. var MorphTarget = /** @class */ (function () {
  70570. function MorphTarget(name, influence) {
  70571. if (influence === void 0) { influence = 0; }
  70572. this.name = name;
  70573. this.animations = new Array();
  70574. this._positions = null;
  70575. this._normals = null;
  70576. this._tangents = null;
  70577. this.onInfluenceChanged = new BABYLON.Observable();
  70578. this.influence = influence;
  70579. }
  70580. Object.defineProperty(MorphTarget.prototype, "influence", {
  70581. get: function () {
  70582. return this._influence;
  70583. },
  70584. set: function (influence) {
  70585. if (this._influence === influence) {
  70586. return;
  70587. }
  70588. var previous = this._influence;
  70589. this._influence = influence;
  70590. if (this.onInfluenceChanged.hasObservers) {
  70591. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  70592. }
  70593. },
  70594. enumerable: true,
  70595. configurable: true
  70596. });
  70597. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  70598. get: function () {
  70599. return !!this._positions;
  70600. },
  70601. enumerable: true,
  70602. configurable: true
  70603. });
  70604. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  70605. get: function () {
  70606. return !!this._normals;
  70607. },
  70608. enumerable: true,
  70609. configurable: true
  70610. });
  70611. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  70612. get: function () {
  70613. return !!this._tangents;
  70614. },
  70615. enumerable: true,
  70616. configurable: true
  70617. });
  70618. MorphTarget.prototype.setPositions = function (data) {
  70619. this._positions = data;
  70620. };
  70621. MorphTarget.prototype.getPositions = function () {
  70622. return this._positions;
  70623. };
  70624. MorphTarget.prototype.setNormals = function (data) {
  70625. this._normals = data;
  70626. };
  70627. MorphTarget.prototype.getNormals = function () {
  70628. return this._normals;
  70629. };
  70630. MorphTarget.prototype.setTangents = function (data) {
  70631. this._tangents = data;
  70632. };
  70633. MorphTarget.prototype.getTangents = function () {
  70634. return this._tangents;
  70635. };
  70636. /**
  70637. * Serializes the current target into a Serialization object.
  70638. * Returns the serialized object.
  70639. */
  70640. MorphTarget.prototype.serialize = function () {
  70641. var serializationObject = {};
  70642. serializationObject.name = this.name;
  70643. serializationObject.influence = this.influence;
  70644. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  70645. if (this.hasNormals) {
  70646. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  70647. }
  70648. if (this.hasTangents) {
  70649. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  70650. }
  70651. // Animations
  70652. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  70653. return serializationObject;
  70654. };
  70655. // Statics
  70656. MorphTarget.Parse = function (serializationObject) {
  70657. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  70658. result.setPositions(serializationObject.positions);
  70659. if (serializationObject.normals) {
  70660. result.setNormals(serializationObject.normals);
  70661. }
  70662. if (serializationObject.tangents) {
  70663. result.setTangents(serializationObject.tangents);
  70664. }
  70665. // Animations
  70666. if (serializationObject.animations) {
  70667. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  70668. var parsedAnimation = serializationObject.animations[animationIndex];
  70669. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  70670. }
  70671. }
  70672. return result;
  70673. };
  70674. MorphTarget.FromMesh = function (mesh, name, influence) {
  70675. if (!name) {
  70676. name = mesh.name;
  70677. }
  70678. var result = new MorphTarget(name, influence);
  70679. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  70680. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  70681. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  70682. }
  70683. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  70684. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  70685. }
  70686. return result;
  70687. };
  70688. return MorphTarget;
  70689. }());
  70690. BABYLON.MorphTarget = MorphTarget;
  70691. })(BABYLON || (BABYLON = {}));
  70692. //# sourceMappingURL=babylon.morphTarget.js.map
  70693. var BABYLON;
  70694. (function (BABYLON) {
  70695. var MorphTargetManager = /** @class */ (function () {
  70696. function MorphTargetManager(scene) {
  70697. if (scene === void 0) { scene = null; }
  70698. this._targets = new Array();
  70699. this._targetObservable = new Array();
  70700. this._activeTargets = new BABYLON.SmartArray(16);
  70701. this._supportsNormals = false;
  70702. this._supportsTangents = false;
  70703. this._vertexCount = 0;
  70704. this._uniqueId = 0;
  70705. this._tempInfluences = new Array();
  70706. if (!scene) {
  70707. scene = BABYLON.Engine.LastCreatedScene;
  70708. }
  70709. this._scene = scene;
  70710. if (this._scene) {
  70711. this._scene.morphTargetManagers.push(this);
  70712. this._uniqueId = this._scene.getUniqueId();
  70713. }
  70714. }
  70715. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  70716. get: function () {
  70717. return this._uniqueId;
  70718. },
  70719. enumerable: true,
  70720. configurable: true
  70721. });
  70722. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  70723. get: function () {
  70724. return this._vertexCount;
  70725. },
  70726. enumerable: true,
  70727. configurable: true
  70728. });
  70729. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  70730. get: function () {
  70731. return this._supportsNormals;
  70732. },
  70733. enumerable: true,
  70734. configurable: true
  70735. });
  70736. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  70737. get: function () {
  70738. return this._supportsTangents;
  70739. },
  70740. enumerable: true,
  70741. configurable: true
  70742. });
  70743. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  70744. get: function () {
  70745. return this._targets.length;
  70746. },
  70747. enumerable: true,
  70748. configurable: true
  70749. });
  70750. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  70751. get: function () {
  70752. return this._activeTargets.length;
  70753. },
  70754. enumerable: true,
  70755. configurable: true
  70756. });
  70757. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  70758. get: function () {
  70759. return this._influences;
  70760. },
  70761. enumerable: true,
  70762. configurable: true
  70763. });
  70764. MorphTargetManager.prototype.getActiveTarget = function (index) {
  70765. return this._activeTargets.data[index];
  70766. };
  70767. MorphTargetManager.prototype.getTarget = function (index) {
  70768. return this._targets[index];
  70769. };
  70770. MorphTargetManager.prototype.addTarget = function (target) {
  70771. var _this = this;
  70772. this._targets.push(target);
  70773. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  70774. _this._syncActiveTargets(needUpdate);
  70775. }));
  70776. this._syncActiveTargets(true);
  70777. };
  70778. MorphTargetManager.prototype.removeTarget = function (target) {
  70779. var index = this._targets.indexOf(target);
  70780. if (index >= 0) {
  70781. this._targets.splice(index, 1);
  70782. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  70783. this._syncActiveTargets(true);
  70784. }
  70785. };
  70786. /**
  70787. * Serializes the current manager into a Serialization object.
  70788. * Returns the serialized object.
  70789. */
  70790. MorphTargetManager.prototype.serialize = function () {
  70791. var serializationObject = {};
  70792. serializationObject.id = this.uniqueId;
  70793. serializationObject.targets = [];
  70794. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  70795. var target = _a[_i];
  70796. serializationObject.targets.push(target.serialize());
  70797. }
  70798. return serializationObject;
  70799. };
  70800. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  70801. var influenceCount = 0;
  70802. this._activeTargets.reset();
  70803. this._supportsNormals = true;
  70804. this._supportsTangents = true;
  70805. this._vertexCount = 0;
  70806. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  70807. var target = _a[_i];
  70808. if (target.influence > 0) {
  70809. this._activeTargets.push(target);
  70810. this._tempInfluences[influenceCount++] = target.influence;
  70811. this._supportsNormals = this._supportsNormals && target.hasNormals;
  70812. this._supportsTangents = this._supportsTangents && target.hasTangents;
  70813. var positions = target.getPositions();
  70814. if (!positions) {
  70815. BABYLON.Tools.Error("Invalid target. Target must positions.");
  70816. return;
  70817. }
  70818. var vertexCount = positions.length / 3;
  70819. if (this._vertexCount === 0) {
  70820. this._vertexCount = vertexCount;
  70821. }
  70822. else if (this._vertexCount !== vertexCount) {
  70823. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  70824. return;
  70825. }
  70826. }
  70827. }
  70828. if (!this._influences || this._influences.length !== influenceCount) {
  70829. this._influences = new Float32Array(influenceCount);
  70830. }
  70831. for (var index = 0; index < influenceCount; index++) {
  70832. this._influences[index] = this._tempInfluences[index];
  70833. }
  70834. if (needUpdate && this._scene) {
  70835. // Flag meshes as dirty to resync with the active targets
  70836. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  70837. var mesh = _c[_b];
  70838. if (mesh.morphTargetManager === this) {
  70839. mesh._syncGeometryWithMorphTargetManager();
  70840. }
  70841. }
  70842. }
  70843. };
  70844. // Statics
  70845. MorphTargetManager.Parse = function (serializationObject, scene) {
  70846. var result = new MorphTargetManager(scene);
  70847. result._uniqueId = serializationObject.id;
  70848. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  70849. var targetData = _a[_i];
  70850. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  70851. }
  70852. return result;
  70853. };
  70854. return MorphTargetManager;
  70855. }());
  70856. BABYLON.MorphTargetManager = MorphTargetManager;
  70857. })(BABYLON || (BABYLON = {}));
  70858. //# sourceMappingURL=babylon.morphTargetManager.js.map
  70859. var BABYLON;
  70860. (function (BABYLON) {
  70861. var Octree = /** @class */ (function () {
  70862. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  70863. if (maxDepth === void 0) { maxDepth = 2; }
  70864. this.maxDepth = maxDepth;
  70865. this.dynamicContent = new Array();
  70866. this._maxBlockCapacity = maxBlockCapacity || 64;
  70867. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  70868. this._creationFunc = creationFunc;
  70869. }
  70870. // Methods
  70871. Octree.prototype.update = function (worldMin, worldMax, entries) {
  70872. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  70873. };
  70874. Octree.prototype.addMesh = function (entry) {
  70875. for (var index = 0; index < this.blocks.length; index++) {
  70876. var block = this.blocks[index];
  70877. block.addEntry(entry);
  70878. }
  70879. };
  70880. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  70881. this._selectionContent.reset();
  70882. for (var index = 0; index < this.blocks.length; index++) {
  70883. var block = this.blocks[index];
  70884. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  70885. }
  70886. if (allowDuplicate) {
  70887. this._selectionContent.concat(this.dynamicContent);
  70888. }
  70889. else {
  70890. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  70891. }
  70892. return this._selectionContent;
  70893. };
  70894. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  70895. this._selectionContent.reset();
  70896. for (var index = 0; index < this.blocks.length; index++) {
  70897. var block = this.blocks[index];
  70898. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  70899. }
  70900. if (allowDuplicate) {
  70901. this._selectionContent.concat(this.dynamicContent);
  70902. }
  70903. else {
  70904. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  70905. }
  70906. return this._selectionContent;
  70907. };
  70908. Octree.prototype.intersectsRay = function (ray) {
  70909. this._selectionContent.reset();
  70910. for (var index = 0; index < this.blocks.length; index++) {
  70911. var block = this.blocks[index];
  70912. block.intersectsRay(ray, this._selectionContent);
  70913. }
  70914. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  70915. return this._selectionContent;
  70916. };
  70917. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  70918. target.blocks = new Array();
  70919. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  70920. // Segmenting space
  70921. for (var x = 0; x < 2; x++) {
  70922. for (var y = 0; y < 2; y++) {
  70923. for (var z = 0; z < 2; z++) {
  70924. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  70925. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  70926. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  70927. block.addEntries(entries);
  70928. target.blocks.push(block);
  70929. }
  70930. }
  70931. }
  70932. };
  70933. Octree.CreationFuncForMeshes = function (entry, block) {
  70934. var boundingInfo = entry.getBoundingInfo();
  70935. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  70936. block.entries.push(entry);
  70937. }
  70938. };
  70939. Octree.CreationFuncForSubMeshes = function (entry, block) {
  70940. var boundingInfo = entry.getBoundingInfo();
  70941. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  70942. block.entries.push(entry);
  70943. }
  70944. };
  70945. return Octree;
  70946. }());
  70947. BABYLON.Octree = Octree;
  70948. })(BABYLON || (BABYLON = {}));
  70949. //# sourceMappingURL=babylon.octree.js.map
  70950. var BABYLON;
  70951. (function (BABYLON) {
  70952. var OctreeBlock = /** @class */ (function () {
  70953. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  70954. this.entries = new Array();
  70955. this._boundingVectors = new Array();
  70956. this._capacity = capacity;
  70957. this._depth = depth;
  70958. this._maxDepth = maxDepth;
  70959. this._creationFunc = creationFunc;
  70960. this._minPoint = minPoint;
  70961. this._maxPoint = maxPoint;
  70962. this._boundingVectors.push(minPoint.clone());
  70963. this._boundingVectors.push(maxPoint.clone());
  70964. this._boundingVectors.push(minPoint.clone());
  70965. this._boundingVectors[2].x = maxPoint.x;
  70966. this._boundingVectors.push(minPoint.clone());
  70967. this._boundingVectors[3].y = maxPoint.y;
  70968. this._boundingVectors.push(minPoint.clone());
  70969. this._boundingVectors[4].z = maxPoint.z;
  70970. this._boundingVectors.push(maxPoint.clone());
  70971. this._boundingVectors[5].z = minPoint.z;
  70972. this._boundingVectors.push(maxPoint.clone());
  70973. this._boundingVectors[6].x = minPoint.x;
  70974. this._boundingVectors.push(maxPoint.clone());
  70975. this._boundingVectors[7].y = minPoint.y;
  70976. }
  70977. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  70978. // Property
  70979. get: function () {
  70980. return this._capacity;
  70981. },
  70982. enumerable: true,
  70983. configurable: true
  70984. });
  70985. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  70986. get: function () {
  70987. return this._minPoint;
  70988. },
  70989. enumerable: true,
  70990. configurable: true
  70991. });
  70992. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  70993. get: function () {
  70994. return this._maxPoint;
  70995. },
  70996. enumerable: true,
  70997. configurable: true
  70998. });
  70999. // Methods
  71000. OctreeBlock.prototype.addEntry = function (entry) {
  71001. if (this.blocks) {
  71002. for (var index = 0; index < this.blocks.length; index++) {
  71003. var block = this.blocks[index];
  71004. block.addEntry(entry);
  71005. }
  71006. return;
  71007. }
  71008. this._creationFunc(entry, this);
  71009. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  71010. this.createInnerBlocks();
  71011. }
  71012. };
  71013. OctreeBlock.prototype.addEntries = function (entries) {
  71014. for (var index = 0; index < entries.length; index++) {
  71015. var mesh = entries[index];
  71016. this.addEntry(mesh);
  71017. }
  71018. };
  71019. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  71020. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  71021. if (this.blocks) {
  71022. for (var index = 0; index < this.blocks.length; index++) {
  71023. var block = this.blocks[index];
  71024. block.select(frustumPlanes, selection, allowDuplicate);
  71025. }
  71026. return;
  71027. }
  71028. if (allowDuplicate) {
  71029. selection.concat(this.entries);
  71030. }
  71031. else {
  71032. selection.concatWithNoDuplicate(this.entries);
  71033. }
  71034. }
  71035. };
  71036. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  71037. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  71038. if (this.blocks) {
  71039. for (var index = 0; index < this.blocks.length; index++) {
  71040. var block = this.blocks[index];
  71041. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  71042. }
  71043. return;
  71044. }
  71045. if (allowDuplicate) {
  71046. selection.concat(this.entries);
  71047. }
  71048. else {
  71049. selection.concatWithNoDuplicate(this.entries);
  71050. }
  71051. }
  71052. };
  71053. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  71054. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  71055. if (this.blocks) {
  71056. for (var index = 0; index < this.blocks.length; index++) {
  71057. var block = this.blocks[index];
  71058. block.intersectsRay(ray, selection);
  71059. }
  71060. return;
  71061. }
  71062. selection.concatWithNoDuplicate(this.entries);
  71063. }
  71064. };
  71065. OctreeBlock.prototype.createInnerBlocks = function () {
  71066. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  71067. };
  71068. return OctreeBlock;
  71069. }());
  71070. BABYLON.OctreeBlock = OctreeBlock;
  71071. })(BABYLON || (BABYLON = {}));
  71072. //# sourceMappingURL=babylon.octreeBlock.js.map
  71073. var BABYLON;
  71074. (function (BABYLON) {
  71075. var SIMDVector3 = /** @class */ (function () {
  71076. function SIMDVector3() {
  71077. }
  71078. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  71079. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  71080. };
  71081. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  71082. var m = transformation.m;
  71083. var m0 = SIMD.Float32x4.load(m, 0);
  71084. var m1 = SIMD.Float32x4.load(m, 4);
  71085. var m2 = SIMD.Float32x4.load(m, 8);
  71086. var m3 = SIMD.Float32x4.load(m, 12);
  71087. var r = SIMD.Float32x4.add(SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(x), m0), SIMD.Float32x4.mul(SIMD.Float32x4.splat(y), m1)), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(z), m2), m3));
  71088. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  71089. result.x = SIMD.Float32x4.extractLane(r, 0);
  71090. result.y = SIMD.Float32x4.extractLane(r, 1);
  71091. result.z = SIMD.Float32x4.extractLane(r, 2);
  71092. };
  71093. return SIMDVector3;
  71094. }());
  71095. var SIMDMatrix = /** @class */ (function () {
  71096. function SIMDMatrix() {
  71097. }
  71098. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  71099. var tm = this.m;
  71100. var om = other.m;
  71101. var m0 = SIMD.Float32x4.load(om, 0);
  71102. var m1 = SIMD.Float32x4.load(om, 4);
  71103. var m2 = SIMD.Float32x4.load(om, 8);
  71104. var m3 = SIMD.Float32x4.load(om, 12);
  71105. for (var i = 0; i < 16; i += 4) {
  71106. SIMD.Float32x4.store(result, i + offset, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i]), m0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 1]), m1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 2]), m2), SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 3]), m3)))));
  71107. }
  71108. return this;
  71109. };
  71110. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  71111. var src = this.m;
  71112. var dest = other.m;
  71113. // Load the 4 rows
  71114. var src0 = SIMD.Float32x4.load(src, 0);
  71115. var src1 = SIMD.Float32x4.load(src, 4);
  71116. var src2 = SIMD.Float32x4.load(src, 8);
  71117. var src3 = SIMD.Float32x4.load(src, 12);
  71118. // Transpose the source matrix. Sort of. Not a true transpose operation
  71119. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  71120. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  71121. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  71122. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  71123. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  71124. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  71125. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  71126. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  71127. // This is a true transposition, but it will lead to an incorrect result
  71128. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  71129. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  71130. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  71131. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  71132. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  71133. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  71134. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  71135. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  71136. // ----
  71137. tmp1 = SIMD.Float32x4.mul(row2, row3);
  71138. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  71139. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  71140. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  71141. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  71142. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  71143. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  71144. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  71145. // ----
  71146. tmp1 = SIMD.Float32x4.mul(row1, row2);
  71147. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  71148. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  71149. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  71150. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  71151. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  71152. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  71153. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  71154. // ----
  71155. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  71156. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  71157. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  71158. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  71159. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  71160. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  71161. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  71162. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  71163. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  71164. // ----
  71165. tmp1 = SIMD.Float32x4.mul(row0, row1);
  71166. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  71167. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  71168. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  71169. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  71170. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  71171. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  71172. // ----
  71173. tmp1 = SIMD.Float32x4.mul(row0, row3);
  71174. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  71175. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  71176. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  71177. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  71178. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  71179. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  71180. // ----
  71181. tmp1 = SIMD.Float32x4.mul(row0, row2);
  71182. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  71183. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  71184. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  71185. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  71186. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  71187. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  71188. // Compute determinant
  71189. var det = SIMD.Float32x4.mul(row0, minor0);
  71190. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  71191. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  71192. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  71193. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  71194. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  71195. // These shuffles aren't necessary if the faulty transposition is done
  71196. // up at the top of this function.
  71197. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  71198. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  71199. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  71200. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  71201. // Compute final values by multiplying with 1/det
  71202. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  71203. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  71204. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  71205. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  71206. return this;
  71207. };
  71208. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  71209. var out = result.m;
  71210. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  71211. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  71212. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  71213. // cc.kmVec3Subtract(f, pCenter, pEye);
  71214. var f = SIMD.Float32x4.sub(center, eye);
  71215. // cc.kmVec3Normalize(f, f);
  71216. var tmp = SIMD.Float32x4.mul(f, f);
  71217. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  71218. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  71219. // cc.kmVec3Assign(up, pUp);
  71220. // cc.kmVec3Normalize(up, up);
  71221. tmp = SIMD.Float32x4.mul(up, up);
  71222. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  71223. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  71224. // cc.kmVec3Cross(s, f, up);
  71225. var s = SIMD.Float32x4.sub(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(f, 1, 2, 0, 3), SIMD.Float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(f, 2, 0, 1, 3), SIMD.Float32x4.swizzle(up, 1, 2, 0, 3)));
  71226. // cc.kmVec3Normalize(s, s);
  71227. tmp = SIMD.Float32x4.mul(s, s);
  71228. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  71229. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  71230. // cc.kmVec3Cross(u, s, f);
  71231. var u = SIMD.Float32x4.sub(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(s, 1, 2, 0, 3), SIMD.Float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(s, 2, 0, 1, 3), SIMD.Float32x4.swizzle(f, 1, 2, 0, 3)));
  71232. // cc.kmVec3Normalize(s, s);
  71233. tmp = SIMD.Float32x4.mul(s, s);
  71234. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  71235. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  71236. var zero = SIMD.Float32x4.splat(0.0);
  71237. s = SIMD.Float32x4.neg(s);
  71238. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  71239. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  71240. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  71241. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  71242. var a2 = SIMD.Float32x4.shuffle(SIMD.Float32x4.shuffle(s, u, 2, 3, 6, 7), SIMD.Float32x4.shuffle(f, zero, 2, 3, 6, 7), 0, 2, 4, 6);
  71243. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  71244. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  71245. SIMD.Float32x4.store(out, 0, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  71246. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  71247. SIMD.Float32x4.store(out, 4, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  71248. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  71249. SIMD.Float32x4.store(out, 8, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  71250. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  71251. SIMD.Float32x4.store(out, 12, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  71252. };
  71253. return SIMDMatrix;
  71254. }());
  71255. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  71256. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  71257. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  71258. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  71259. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  71260. var SIMDHelper = /** @class */ (function () {
  71261. function SIMDHelper() {
  71262. }
  71263. Object.defineProperty(SIMDHelper, "IsEnabled", {
  71264. get: function () {
  71265. return SIMDHelper._isEnabled;
  71266. },
  71267. enumerable: true,
  71268. configurable: true
  71269. });
  71270. SIMDHelper.DisableSIMD = function () {
  71271. // Replace functions
  71272. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  71273. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  71274. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  71275. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  71276. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  71277. SIMDHelper._isEnabled = false;
  71278. };
  71279. SIMDHelper.EnableSIMD = function () {
  71280. if (self.SIMD === undefined) {
  71281. return;
  71282. }
  71283. // check if polyfills needed
  71284. if (!self.Math.fround) {
  71285. self.Math.fround = (function (array) { return function (x) {
  71286. return array[0] = x, array[0];
  71287. }; })(new Float32Array(1));
  71288. }
  71289. if (!self.Math.imul) {
  71290. self.Math.imul = function (a, b) {
  71291. var ah = (a >>> 16) & 0xffff;
  71292. var al = a & 0xffff;
  71293. var bh = (b >>> 16) & 0xffff;
  71294. var bl = b & 0xffff;
  71295. // the shift by 0 fixes the sign on the high part
  71296. // the final |0 converts the unsigned value into a signed value
  71297. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  71298. };
  71299. }
  71300. // Replace functions
  71301. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  71302. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  71303. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  71304. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  71305. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  71306. SIMDHelper._isEnabled = true;
  71307. };
  71308. SIMDHelper._isEnabled = false;
  71309. return SIMDHelper;
  71310. }());
  71311. BABYLON.SIMDHelper = SIMDHelper;
  71312. })(BABYLON || (BABYLON = {}));
  71313. //# sourceMappingURL=babylon.math.SIMD.js.map
  71314. var BABYLON;
  71315. (function (BABYLON) {
  71316. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  71317. __extends(VRDistortionCorrectionPostProcess, _super);
  71318. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  71319. var _this = _super.call(this, name, "vrDistortionCorrection", [
  71320. 'LensCenter',
  71321. 'Scale',
  71322. 'ScaleIn',
  71323. 'HmdWarpParam'
  71324. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  71325. _this._isRightEye = isRightEye;
  71326. _this._distortionFactors = vrMetrics.distortionK;
  71327. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  71328. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  71329. _this.adaptScaleToCurrentViewport = true;
  71330. _this.onSizeChangedObservable.add(function () {
  71331. _this.aspectRatio = _this.width * .5 / _this.height;
  71332. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  71333. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  71334. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  71335. });
  71336. _this.onApplyObservable.add(function (effect) {
  71337. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  71338. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  71339. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  71340. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  71341. });
  71342. return _this;
  71343. }
  71344. return VRDistortionCorrectionPostProcess;
  71345. }(BABYLON.PostProcess));
  71346. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  71347. })(BABYLON || (BABYLON = {}));
  71348. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  71349. var BABYLON;
  71350. (function (BABYLON) {
  71351. var AnaglyphPostProcess = /** @class */ (function (_super) {
  71352. __extends(AnaglyphPostProcess, _super);
  71353. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  71354. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  71355. _this._passedProcess = rigCameras[0]._rigPostProcess;
  71356. _this.onApplyObservable.add(function (effect) {
  71357. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  71358. });
  71359. return _this;
  71360. }
  71361. return AnaglyphPostProcess;
  71362. }(BABYLON.PostProcess));
  71363. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  71364. })(BABYLON || (BABYLON = {}));
  71365. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  71366. var BABYLON;
  71367. (function (BABYLON) {
  71368. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  71369. __extends(StereoscopicInterlacePostProcess, _super);
  71370. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  71371. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  71372. _this._passedProcess = rigCameras[0]._rigPostProcess;
  71373. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  71374. _this.onSizeChangedObservable.add(function () {
  71375. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  71376. });
  71377. _this.onApplyObservable.add(function (effect) {
  71378. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  71379. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  71380. });
  71381. return _this;
  71382. }
  71383. return StereoscopicInterlacePostProcess;
  71384. }(BABYLON.PostProcess));
  71385. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  71386. })(BABYLON || (BABYLON = {}));
  71387. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  71388. var BABYLON;
  71389. (function (BABYLON) {
  71390. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  71391. function FreeCameraDeviceOrientationInput() {
  71392. var _this = this;
  71393. this._screenOrientationAngle = 0;
  71394. this._screenQuaternion = new BABYLON.Quaternion();
  71395. this._alpha = 0;
  71396. this._beta = 0;
  71397. this._gamma = 0;
  71398. this._orientationChanged = function () {
  71399. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  71400. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  71401. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  71402. };
  71403. this._deviceOrientation = function (evt) {
  71404. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  71405. _this._beta = evt.beta !== null ? evt.beta : 0;
  71406. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  71407. };
  71408. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  71409. this._orientationChanged();
  71410. }
  71411. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  71412. get: function () {
  71413. return this._camera;
  71414. },
  71415. set: function (camera) {
  71416. this._camera = camera;
  71417. if (this._camera != null && !this._camera.rotationQuaternion) {
  71418. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  71419. }
  71420. },
  71421. enumerable: true,
  71422. configurable: true
  71423. });
  71424. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  71425. window.addEventListener("orientationchange", this._orientationChanged);
  71426. window.addEventListener("deviceorientation", this._deviceOrientation);
  71427. //In certain cases, the attach control is called AFTER orientation was changed,
  71428. //So this is needed.
  71429. this._orientationChanged();
  71430. };
  71431. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  71432. window.removeEventListener("orientationchange", this._orientationChanged);
  71433. window.removeEventListener("deviceorientation", this._deviceOrientation);
  71434. };
  71435. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  71436. //if no device orientation provided, don't update the rotation.
  71437. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  71438. if (!this._alpha)
  71439. return;
  71440. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  71441. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  71442. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  71443. //Mirror on XY Plane
  71444. this._camera.rotationQuaternion.z *= -1;
  71445. this._camera.rotationQuaternion.w *= -1;
  71446. };
  71447. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  71448. return "FreeCameraDeviceOrientationInput";
  71449. };
  71450. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  71451. return "deviceOrientation";
  71452. };
  71453. return FreeCameraDeviceOrientationInput;
  71454. }());
  71455. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  71456. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  71457. })(BABYLON || (BABYLON = {}));
  71458. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  71459. var BABYLON;
  71460. (function (BABYLON) {
  71461. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  71462. function ArcRotateCameraVRDeviceOrientationInput() {
  71463. this.alphaCorrection = 1;
  71464. this.betaCorrection = 1;
  71465. this.gammaCorrection = 1;
  71466. this._alpha = 0;
  71467. this._gamma = 0;
  71468. this._dirty = false;
  71469. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  71470. }
  71471. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  71472. this.camera.attachControl(element, noPreventDefault);
  71473. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  71474. };
  71475. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  71476. if (evt.alpha !== null) {
  71477. this._alpha = +evt.alpha | 0;
  71478. }
  71479. if (evt.gamma !== null) {
  71480. this._gamma = +evt.gamma | 0;
  71481. }
  71482. this._dirty = true;
  71483. };
  71484. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  71485. if (this._dirty) {
  71486. this._dirty = false;
  71487. if (this._gamma < 0) {
  71488. this._gamma = 180 + this._gamma;
  71489. }
  71490. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  71491. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  71492. }
  71493. };
  71494. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  71495. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  71496. };
  71497. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  71498. return "ArcRotateCameraVRDeviceOrientationInput";
  71499. };
  71500. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  71501. return "VRDeviceOrientation";
  71502. };
  71503. return ArcRotateCameraVRDeviceOrientationInput;
  71504. }());
  71505. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  71506. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  71507. })(BABYLON || (BABYLON = {}));
  71508. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  71509. var BABYLON;
  71510. (function (BABYLON) {
  71511. var VRCameraMetrics = /** @class */ (function () {
  71512. function VRCameraMetrics() {
  71513. this.compensateDistortion = true;
  71514. }
  71515. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  71516. get: function () {
  71517. return this.hResolution / (2 * this.vResolution);
  71518. },
  71519. enumerable: true,
  71520. configurable: true
  71521. });
  71522. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  71523. get: function () {
  71524. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  71525. },
  71526. enumerable: true,
  71527. configurable: true
  71528. });
  71529. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  71530. get: function () {
  71531. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  71532. var h = (4 * meters) / this.hScreenSize;
  71533. return BABYLON.Matrix.Translation(h, 0, 0);
  71534. },
  71535. enumerable: true,
  71536. configurable: true
  71537. });
  71538. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  71539. get: function () {
  71540. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  71541. var h = (4 * meters) / this.hScreenSize;
  71542. return BABYLON.Matrix.Translation(-h, 0, 0);
  71543. },
  71544. enumerable: true,
  71545. configurable: true
  71546. });
  71547. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  71548. get: function () {
  71549. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  71550. },
  71551. enumerable: true,
  71552. configurable: true
  71553. });
  71554. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  71555. get: function () {
  71556. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  71557. },
  71558. enumerable: true,
  71559. configurable: true
  71560. });
  71561. VRCameraMetrics.GetDefault = function () {
  71562. var result = new VRCameraMetrics();
  71563. result.hResolution = 1280;
  71564. result.vResolution = 800;
  71565. result.hScreenSize = 0.149759993;
  71566. result.vScreenSize = 0.0935999975;
  71567. result.vScreenCenter = 0.0467999987;
  71568. result.eyeToScreenDistance = 0.0410000011;
  71569. result.lensSeparationDistance = 0.0635000020;
  71570. result.interpupillaryDistance = 0.0640000030;
  71571. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  71572. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  71573. result.postProcessScaleFactor = 1.714605507808412;
  71574. result.lensCenterOffset = 0.151976421;
  71575. return result;
  71576. };
  71577. return VRCameraMetrics;
  71578. }());
  71579. BABYLON.VRCameraMetrics = VRCameraMetrics;
  71580. })(BABYLON || (BABYLON = {}));
  71581. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  71582. var BABYLON;
  71583. (function (BABYLON) {
  71584. var WebVRFreeCamera = /** @class */ (function (_super) {
  71585. __extends(WebVRFreeCamera, _super);
  71586. function WebVRFreeCamera(name, position, scene, webVROptions) {
  71587. if (webVROptions === void 0) { webVROptions = {}; }
  71588. var _this = _super.call(this, name, position, scene) || this;
  71589. _this.webVROptions = webVROptions;
  71590. _this._vrDevice = null;
  71591. _this.rawPose = null;
  71592. _this._specsVersion = "1.1";
  71593. _this._attached = false;
  71594. _this._descendants = [];
  71595. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71596. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71597. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  71598. _this._standingMatrix = null;
  71599. // Represents device position and rotation in babylon space
  71600. _this.devicePosition = BABYLON.Vector3.Zero();
  71601. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  71602. _this.deviceScaleFactor = 1;
  71603. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71604. _this._worldToDevice = BABYLON.Matrix.Identity();
  71605. _this.controllers = [];
  71606. _this.onControllersAttachedObservable = new BABYLON.Observable();
  71607. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  71608. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  71609. _this._defaultHeight = 0;
  71610. _this.deviceDistanceToRoomGround = function () {
  71611. if (_this._standingMatrix) {
  71612. // Add standing matrix offset to get real offset from ground in room
  71613. _this._standingMatrix.getTranslationToRef(_this._workingVector);
  71614. return _this._deviceRoomPosition.y + _this._workingVector.y;
  71615. }
  71616. else {
  71617. return _this._defaultHeight;
  71618. }
  71619. };
  71620. _this.useStandingMatrix = function (callback) {
  71621. if (callback === void 0) { callback = function (bool) { }; }
  71622. // Use standing matrix if availible
  71623. if (!navigator || !navigator.getVRDisplays) {
  71624. callback(false);
  71625. }
  71626. else {
  71627. navigator.getVRDisplays().then(function (displays) {
  71628. if (!displays || !displays[0] || !displays[0].stageParameters || !displays[0].stageParameters.sittingToStandingTransform) {
  71629. callback(false);
  71630. }
  71631. else {
  71632. _this._standingMatrix = new BABYLON.Matrix();
  71633. BABYLON.Matrix.FromFloat32ArrayToRefScaled(displays[0].stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  71634. if (!_this.getScene().useRightHandedSystem) {
  71635. [2, 6, 8, 9, 14].forEach(function (num) {
  71636. if (_this._standingMatrix) {
  71637. _this._standingMatrix.m[num] *= -1;
  71638. }
  71639. });
  71640. }
  71641. callback(true);
  71642. }
  71643. });
  71644. }
  71645. };
  71646. _this._workingVector = BABYLON.Vector3.Zero();
  71647. _this._oneVector = BABYLON.Vector3.One();
  71648. _this._workingMatrix = BABYLON.Matrix.Identity();
  71649. _this._cache.position = BABYLON.Vector3.Zero();
  71650. if (webVROptions.defaultHeight) {
  71651. _this._defaultHeight = webVROptions.defaultHeight;
  71652. _this.position.y = _this._defaultHeight;
  71653. }
  71654. _this.minZ = 0.1;
  71655. //legacy support - the compensation boolean was removed.
  71656. if (arguments.length === 5) {
  71657. _this.webVROptions = arguments[4];
  71658. }
  71659. // default webVR options
  71660. if (_this.webVROptions.trackPosition == undefined) {
  71661. _this.webVROptions.trackPosition = true;
  71662. }
  71663. if (_this.webVROptions.controllerMeshes == undefined) {
  71664. _this.webVROptions.controllerMeshes = true;
  71665. }
  71666. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  71667. _this.webVROptions.defaultLightingOnControllers = true;
  71668. }
  71669. _this.rotationQuaternion = new BABYLON.Quaternion();
  71670. if (_this.webVROptions && _this.webVROptions.positionScale) {
  71671. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  71672. }
  71673. //enable VR
  71674. var engine = _this.getEngine();
  71675. _this._onVREnabled = function (success) { if (success) {
  71676. _this.initControllers();
  71677. } };
  71678. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  71679. engine.initWebVR().add(function (event) {
  71680. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  71681. return;
  71682. }
  71683. _this._vrDevice = event.vrDisplay;
  71684. //reset the rig parameters.
  71685. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  71686. if (_this._attached) {
  71687. _this.getEngine().enableVR();
  71688. }
  71689. });
  71690. if (typeof (VRFrameData) !== "undefined")
  71691. _this._frameData = new VRFrameData();
  71692. /**
  71693. * The idea behind the following lines:
  71694. * objects that have the camera as parent should actually have the rig cameras as a parent.
  71695. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  71696. * the second will not show it correctly.
  71697. *
  71698. * To solve this - each object that has the camera as parent will be added to a protected array.
  71699. * When the rig camera renders, it will take this array and set all of those to be its children.
  71700. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  71701. * Amazing!
  71702. */
  71703. scene.onBeforeCameraRenderObservable.add(function (camera) {
  71704. if (camera.parent === _this && _this.rigParenting) {
  71705. _this._descendants = _this.getDescendants(true, function (n) {
  71706. // don't take the cameras or the controllers!
  71707. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  71708. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  71709. return !isController && !isRigCamera;
  71710. });
  71711. _this._descendants.forEach(function (node) {
  71712. node.parent = camera;
  71713. });
  71714. }
  71715. });
  71716. scene.onAfterCameraRenderObservable.add(function (camera) {
  71717. if (camera.parent === _this && _this.rigParenting) {
  71718. _this._descendants.forEach(function (node) {
  71719. node.parent = _this;
  71720. });
  71721. }
  71722. });
  71723. return _this;
  71724. }
  71725. WebVRFreeCamera.prototype.dispose = function () {
  71726. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  71727. _super.prototype.dispose.call(this);
  71728. };
  71729. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  71730. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  71731. var gp = _a[_i];
  71732. if (gp.hand === name) {
  71733. return gp;
  71734. }
  71735. }
  71736. return null;
  71737. };
  71738. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  71739. get: function () {
  71740. if (!this._leftController) {
  71741. this._leftController = this.getControllerByName("left");
  71742. }
  71743. return this._leftController;
  71744. },
  71745. enumerable: true,
  71746. configurable: true
  71747. });
  71748. ;
  71749. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  71750. get: function () {
  71751. if (!this._rightController) {
  71752. this._rightController = this.getControllerByName("right");
  71753. }
  71754. return this._rightController;
  71755. },
  71756. enumerable: true,
  71757. configurable: true
  71758. });
  71759. ;
  71760. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  71761. if (length === void 0) { length = 100; }
  71762. if (this.leftCamera) {
  71763. // Use left eye to avoid computation to compute center on every call
  71764. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  71765. }
  71766. else {
  71767. return _super.prototype.getForwardRay.call(this, length);
  71768. }
  71769. };
  71770. WebVRFreeCamera.prototype._checkInputs = function () {
  71771. if (this._vrDevice && this._vrDevice.isPresenting) {
  71772. this._vrDevice.getFrameData(this._frameData);
  71773. this.updateFromDevice(this._frameData.pose);
  71774. }
  71775. _super.prototype._checkInputs.call(this);
  71776. };
  71777. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  71778. if (poseData && poseData.orientation) {
  71779. this.rawPose = poseData;
  71780. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  71781. if (this.getScene().useRightHandedSystem) {
  71782. this._deviceRoomRotationQuaternion.z *= -1;
  71783. this._deviceRoomRotationQuaternion.w *= -1;
  71784. }
  71785. if (this.webVROptions.trackPosition && this.rawPose.position) {
  71786. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  71787. if (this.getScene().useRightHandedSystem) {
  71788. this._deviceRoomPosition.z *= -1;
  71789. }
  71790. }
  71791. }
  71792. };
  71793. /**
  71794. * WebVR's attach control will start broadcasting frames to the device.
  71795. * Note that in certain browsers (chrome for example) this function must be called
  71796. * within a user-interaction callback. Example:
  71797. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  71798. *
  71799. * @param {HTMLElement} element
  71800. * @param {boolean} [noPreventDefault]
  71801. *
  71802. * @memberOf WebVRFreeCamera
  71803. */
  71804. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  71805. _super.prototype.attachControl.call(this, element, noPreventDefault);
  71806. this._attached = true;
  71807. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  71808. if (this._vrDevice) {
  71809. this.getEngine().enableVR();
  71810. }
  71811. };
  71812. WebVRFreeCamera.prototype.detachControl = function (element) {
  71813. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  71814. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  71815. _super.prototype.detachControl.call(this, element);
  71816. this._attached = false;
  71817. this.getEngine().disableVR();
  71818. };
  71819. WebVRFreeCamera.prototype.getClassName = function () {
  71820. return "WebVRFreeCamera";
  71821. };
  71822. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  71823. //uses the vrDisplay's "resetPose()".
  71824. //pitch and roll won't be affected.
  71825. this._vrDevice.resetPose();
  71826. };
  71827. WebVRFreeCamera.prototype._updateRigCameras = function () {
  71828. var camLeft = this._rigCameras[0];
  71829. var camRight = this._rigCameras[1];
  71830. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  71831. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  71832. camLeft.position.copyFrom(this._deviceRoomPosition);
  71833. camRight.position.copyFrom(this._deviceRoomPosition);
  71834. };
  71835. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  71836. var _this = this;
  71837. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  71838. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  71839. this.update();
  71840. // Set working vector to the device position in room space rotated by the new rotation
  71841. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  71842. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  71843. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  71844. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  71845. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  71846. // Add translation from anchor position
  71847. this._deviceToWorld.getTranslationToRef(this._workingVector);
  71848. this._workingVector.addInPlace(this.position);
  71849. this._workingVector.subtractInPlace(this._cache.position);
  71850. this._deviceToWorld.setTranslation(this._workingVector);
  71851. // Set an inverted matrix to be used when updating the camera
  71852. this._deviceToWorld.invertToRef(this._worldToDevice);
  71853. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  71854. this.controllers.forEach(function (controller) {
  71855. controller._deviceToWorld = _this._deviceToWorld;
  71856. controller.update();
  71857. });
  71858. this.update();
  71859. }
  71860. if (!ignoreParentClass) {
  71861. _super.prototype._updateCache.call(this);
  71862. }
  71863. };
  71864. WebVRFreeCamera.prototype.update = function () {
  71865. // Get current device position in babylon world
  71866. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  71867. // Get current device rotation in babylon world
  71868. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  71869. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  71870. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71871. _super.prototype.update.call(this);
  71872. };
  71873. WebVRFreeCamera.prototype._getViewMatrix = function () {
  71874. return BABYLON.Matrix.Identity();
  71875. };
  71876. /**
  71877. * This function is called by the two RIG cameras.
  71878. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  71879. */
  71880. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  71881. var _this = this;
  71882. //WebVR 1.1
  71883. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  71884. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  71885. if (!this.getScene().useRightHandedSystem) {
  71886. [2, 6, 8, 9, 14].forEach(function (num) {
  71887. _this._webvrViewMatrix.m[num] *= -1;
  71888. });
  71889. }
  71890. // update the camera rotation matrix
  71891. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  71892. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  71893. // Computing target and final matrix
  71894. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  71895. var parentCamera = this._cameraRigParams["parentCamera"];
  71896. // should the view matrix be updated with scale and position offset?
  71897. if (parentCamera.deviceScaleFactor !== 1) {
  71898. this._webvrViewMatrix.invert();
  71899. // scale the position, if set
  71900. if (parentCamera.deviceScaleFactor) {
  71901. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  71902. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  71903. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  71904. }
  71905. this._webvrViewMatrix.invert();
  71906. }
  71907. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  71908. return this._webvrViewMatrix;
  71909. };
  71910. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  71911. var _this = this;
  71912. var parentCamera = this.parent;
  71913. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  71914. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  71915. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  71916. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  71917. //babylon compatible matrix
  71918. if (!this.getScene().useRightHandedSystem) {
  71919. [8, 9, 10, 11].forEach(function (num) {
  71920. _this._projectionMatrix.m[num] *= -1;
  71921. });
  71922. }
  71923. return this._projectionMatrix;
  71924. };
  71925. WebVRFreeCamera.prototype.initControllers = function () {
  71926. var _this = this;
  71927. this.controllers = [];
  71928. var manager = this.getScene().gamepadManager;
  71929. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  71930. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  71931. var webVrController = gamepad;
  71932. if (webVrController.defaultModel) {
  71933. webVrController.defaultModel.setEnabled(false);
  71934. }
  71935. if (webVrController.hand === "right") {
  71936. _this._rightController = null;
  71937. }
  71938. if (webVrController.hand === "left") {
  71939. _this._rightController = null;
  71940. }
  71941. var controllerIndex = _this.controllers.indexOf(webVrController);
  71942. if (controllerIndex !== -1) {
  71943. _this.controllers.splice(controllerIndex, 1);
  71944. }
  71945. }
  71946. });
  71947. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  71948. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  71949. var webVrController_1 = gamepad;
  71950. webVrController_1._deviceToWorld = _this._deviceToWorld;
  71951. if (_this.webVROptions.controllerMeshes) {
  71952. if (webVrController_1.defaultModel) {
  71953. webVrController_1.defaultModel.setEnabled(true);
  71954. }
  71955. else {
  71956. // Load the meshes
  71957. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  71958. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  71959. if (_this.webVROptions.defaultLightingOnControllers) {
  71960. if (!_this._lightOnControllers) {
  71961. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  71962. }
  71963. var activateLightOnSubMeshes_1 = function (mesh, light) {
  71964. var children = mesh.getChildren();
  71965. if (children.length !== 0) {
  71966. children.forEach(function (mesh) {
  71967. light.includedOnlyMeshes.push(mesh);
  71968. activateLightOnSubMeshes_1(mesh, light);
  71969. });
  71970. }
  71971. };
  71972. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  71973. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  71974. }
  71975. });
  71976. }
  71977. }
  71978. webVrController_1.attachToPoseControlledCamera(_this);
  71979. // since this is async - sanity check. Is the controller already stored?
  71980. if (_this.controllers.indexOf(webVrController_1) === -1) {
  71981. //add to the controllers array
  71982. _this.controllers.push(webVrController_1);
  71983. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  71984. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  71985. // So we're overriding setting left & right manually to be sure
  71986. var firstViveWandDetected = false;
  71987. for (var i = 0; i < _this.controllers.length; i++) {
  71988. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  71989. if (!firstViveWandDetected) {
  71990. firstViveWandDetected = true;
  71991. _this.controllers[i].hand = "left";
  71992. }
  71993. else {
  71994. _this.controllers[i].hand = "right";
  71995. }
  71996. }
  71997. }
  71998. //did we find enough controllers? Great! let the developer know.
  71999. if (_this.controllers.length >= 2) {
  72000. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  72001. }
  72002. }
  72003. }
  72004. });
  72005. };
  72006. return WebVRFreeCamera;
  72007. }(BABYLON.FreeCamera));
  72008. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  72009. })(BABYLON || (BABYLON = {}));
  72010. //# sourceMappingURL=babylon.webVRCamera.js.map
  72011. var BABYLON;
  72012. (function (BABYLON) {
  72013. // We're mainly based on the logic defined into the FreeCamera code
  72014. var DeviceOrientationCamera = /** @class */ (function (_super) {
  72015. __extends(DeviceOrientationCamera, _super);
  72016. function DeviceOrientationCamera(name, position, scene) {
  72017. var _this = _super.call(this, name, position, scene) || this;
  72018. _this._quaternionCache = new BABYLON.Quaternion();
  72019. _this.inputs.addDeviceOrientation();
  72020. return _this;
  72021. }
  72022. DeviceOrientationCamera.prototype.getClassName = function () {
  72023. return "DeviceOrientationCamera";
  72024. };
  72025. DeviceOrientationCamera.prototype._checkInputs = function () {
  72026. _super.prototype._checkInputs.call(this);
  72027. this._quaternionCache.copyFrom(this.rotationQuaternion);
  72028. if (this._initialQuaternion) {
  72029. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  72030. }
  72031. };
  72032. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  72033. var _this = this;
  72034. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  72035. //can only work if this camera has a rotation quaternion already.
  72036. if (!this.rotationQuaternion)
  72037. return;
  72038. if (!this._initialQuaternion) {
  72039. this._initialQuaternion = new BABYLON.Quaternion();
  72040. }
  72041. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  72042. ['x', 'y', 'z'].forEach(function (axisName) {
  72043. if (!axis[axisName]) {
  72044. _this._initialQuaternion[axisName] = 0;
  72045. }
  72046. else {
  72047. _this._initialQuaternion[axisName] *= -1;
  72048. }
  72049. });
  72050. this._initialQuaternion.normalize();
  72051. //force rotation update
  72052. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  72053. };
  72054. return DeviceOrientationCamera;
  72055. }(BABYLON.FreeCamera));
  72056. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  72057. })(BABYLON || (BABYLON = {}));
  72058. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  72059. var BABYLON;
  72060. (function (BABYLON) {
  72061. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  72062. __extends(VRDeviceOrientationFreeCamera, _super);
  72063. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  72064. if (compensateDistortion === void 0) { compensateDistortion = true; }
  72065. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  72066. var _this = _super.call(this, name, position, scene) || this;
  72067. vrCameraMetrics.compensateDistortion = compensateDistortion;
  72068. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  72069. return _this;
  72070. }
  72071. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  72072. return "VRDeviceOrientationFreeCamera";
  72073. };
  72074. return VRDeviceOrientationFreeCamera;
  72075. }(BABYLON.DeviceOrientationCamera));
  72076. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  72077. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  72078. __extends(VRDeviceOrientationGamepadCamera, _super);
  72079. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  72080. if (compensateDistortion === void 0) { compensateDistortion = true; }
  72081. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  72082. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  72083. _this.inputs.addGamepad();
  72084. return _this;
  72085. }
  72086. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  72087. return "VRDeviceOrientationGamepadCamera";
  72088. };
  72089. return VRDeviceOrientationGamepadCamera;
  72090. }(VRDeviceOrientationFreeCamera));
  72091. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  72092. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  72093. __extends(VRDeviceOrientationArcRotateCamera, _super);
  72094. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  72095. if (compensateDistortion === void 0) { compensateDistortion = true; }
  72096. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  72097. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  72098. vrCameraMetrics.compensateDistortion = compensateDistortion;
  72099. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  72100. _this.inputs.addVRDeviceOrientation();
  72101. return _this;
  72102. }
  72103. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  72104. return "VRDeviceOrientationArcRotateCamera";
  72105. };
  72106. return VRDeviceOrientationArcRotateCamera;
  72107. }(BABYLON.ArcRotateCamera));
  72108. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  72109. })(BABYLON || (BABYLON = {}));
  72110. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  72111. var BABYLON;
  72112. (function (BABYLON) {
  72113. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  72114. __extends(AnaglyphFreeCamera, _super);
  72115. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  72116. var _this = _super.call(this, name, position, scene) || this;
  72117. _this.interaxialDistance = interaxialDistance;
  72118. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  72119. return _this;
  72120. }
  72121. AnaglyphFreeCamera.prototype.getClassName = function () {
  72122. return "AnaglyphFreeCamera";
  72123. };
  72124. return AnaglyphFreeCamera;
  72125. }(BABYLON.FreeCamera));
  72126. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  72127. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  72128. __extends(AnaglyphArcRotateCamera, _super);
  72129. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  72130. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  72131. _this.interaxialDistance = interaxialDistance;
  72132. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  72133. return _this;
  72134. }
  72135. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  72136. return "AnaglyphArcRotateCamera";
  72137. };
  72138. return AnaglyphArcRotateCamera;
  72139. }(BABYLON.ArcRotateCamera));
  72140. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  72141. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  72142. __extends(AnaglyphGamepadCamera, _super);
  72143. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  72144. var _this = _super.call(this, name, position, scene) || this;
  72145. _this.interaxialDistance = interaxialDistance;
  72146. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  72147. return _this;
  72148. }
  72149. AnaglyphGamepadCamera.prototype.getClassName = function () {
  72150. return "AnaglyphGamepadCamera";
  72151. };
  72152. return AnaglyphGamepadCamera;
  72153. }(BABYLON.GamepadCamera));
  72154. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  72155. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  72156. __extends(AnaglyphUniversalCamera, _super);
  72157. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  72158. var _this = _super.call(this, name, position, scene) || this;
  72159. _this.interaxialDistance = interaxialDistance;
  72160. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  72161. return _this;
  72162. }
  72163. AnaglyphUniversalCamera.prototype.getClassName = function () {
  72164. return "AnaglyphUniversalCamera";
  72165. };
  72166. return AnaglyphUniversalCamera;
  72167. }(BABYLON.UniversalCamera));
  72168. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  72169. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  72170. __extends(StereoscopicFreeCamera, _super);
  72171. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  72172. var _this = _super.call(this, name, position, scene) || this;
  72173. _this.interaxialDistance = interaxialDistance;
  72174. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  72175. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  72176. return _this;
  72177. }
  72178. StereoscopicFreeCamera.prototype.getClassName = function () {
  72179. return "StereoscopicFreeCamera";
  72180. };
  72181. return StereoscopicFreeCamera;
  72182. }(BABYLON.FreeCamera));
  72183. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  72184. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  72185. __extends(StereoscopicArcRotateCamera, _super);
  72186. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  72187. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  72188. _this.interaxialDistance = interaxialDistance;
  72189. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  72190. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  72191. return _this;
  72192. }
  72193. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  72194. return "StereoscopicArcRotateCamera";
  72195. };
  72196. return StereoscopicArcRotateCamera;
  72197. }(BABYLON.ArcRotateCamera));
  72198. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  72199. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  72200. __extends(StereoscopicGamepadCamera, _super);
  72201. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  72202. var _this = _super.call(this, name, position, scene) || this;
  72203. _this.interaxialDistance = interaxialDistance;
  72204. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  72205. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  72206. return _this;
  72207. }
  72208. StereoscopicGamepadCamera.prototype.getClassName = function () {
  72209. return "StereoscopicGamepadCamera";
  72210. };
  72211. return StereoscopicGamepadCamera;
  72212. }(BABYLON.GamepadCamera));
  72213. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  72214. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  72215. __extends(StereoscopicUniversalCamera, _super);
  72216. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  72217. var _this = _super.call(this, name, position, scene) || this;
  72218. _this.interaxialDistance = interaxialDistance;
  72219. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  72220. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  72221. return _this;
  72222. }
  72223. StereoscopicUniversalCamera.prototype.getClassName = function () {
  72224. return "StereoscopicUniversalCamera";
  72225. };
  72226. return StereoscopicUniversalCamera;
  72227. }(BABYLON.UniversalCamera));
  72228. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  72229. })(BABYLON || (BABYLON = {}));
  72230. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  72231. var BABYLON;
  72232. (function (BABYLON) {
  72233. var VRExperienceHelper = /** @class */ (function () {
  72234. function VRExperienceHelper(scene, webVROptions) {
  72235. if (webVROptions === void 0) { webVROptions = {}; }
  72236. var _this = this;
  72237. this.webVROptions = webVROptions;
  72238. // Can the system support WebVR, even if a headset isn't plugged in?
  72239. this._webVRsupported = false;
  72240. // If WebVR is supported, is a headset plugged in and are we ready to present?
  72241. this._webVRready = false;
  72242. // Are we waiting for the requestPresent callback to complete?
  72243. this._webVRrequesting = false;
  72244. // Are we presenting to the headset right now?
  72245. this._webVRpresenting = false;
  72246. // Are we presenting in the fullscreen fallback?
  72247. this._fullscreenVRpresenting = false;
  72248. /**
  72249. * Observable raised when entering VR.
  72250. */
  72251. this.onEnteringVRObservable = new BABYLON.Observable();
  72252. /**
  72253. * Observable raised when exiting VR.
  72254. */
  72255. this.onExitingVRObservable = new BABYLON.Observable();
  72256. /**
  72257. * Observable raised when controller mesh is loaded.
  72258. */
  72259. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  72260. this._useCustomVRButton = false;
  72261. this._teleportationRequested = false;
  72262. this._teleportationEnabledOnLeftController = false;
  72263. this._teleportationEnabledOnRightController = false;
  72264. this._interactionsEnabledOnLeftController = false;
  72265. this._interactionsEnabledOnRightController = false;
  72266. this._leftControllerReady = false;
  72267. this._rightControllerReady = false;
  72268. this._floorMeshesCollection = [];
  72269. this._teleportationAllowed = false;
  72270. this._rotationAllowed = true;
  72271. this._teleportationRequestInitiated = false;
  72272. this._teleportationBackRequestInitiated = false;
  72273. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  72274. this._rotationRightAsked = false;
  72275. this._rotationLeftAsked = false;
  72276. this._isDefaultTeleportationTarget = true;
  72277. this._teleportationFillColor = "#444444";
  72278. this._teleportationBorderColor = "#FFFFFF";
  72279. this._rotationAngle = 0;
  72280. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  72281. this._padSensibilityUp = 0.65;
  72282. this._padSensibilityDown = 0.35;
  72283. this.onNewMeshSelected = new BABYLON.Observable();
  72284. /**
  72285. * Observable raised when current selected mesh gets unselected
  72286. */
  72287. this.onSelectedMeshUnselected = new BABYLON.Observable();
  72288. this._pointerDownOnMeshAsked = false;
  72289. this._isActionableMesh = false;
  72290. this._teleportationEnabled = false;
  72291. this._interactionsEnabled = false;
  72292. this._interactionsRequested = false;
  72293. this._displayGaze = true;
  72294. this._displayLaserPointer = true;
  72295. this._dpadPressed = true;
  72296. this._onResize = function () {
  72297. _this.moveButtonToBottomRight();
  72298. if (_this._fullscreenVRpresenting && _this._webVRready) {
  72299. _this.exitVR();
  72300. }
  72301. };
  72302. this._onFullscreenChange = function () {
  72303. if (document.fullscreen !== undefined) {
  72304. _this._fullscreenVRpresenting = document.fullscreen;
  72305. }
  72306. else if (document.mozFullScreen !== undefined) {
  72307. _this._fullscreenVRpresenting = document.mozFullScreen;
  72308. }
  72309. else if (document.webkitIsFullScreen !== undefined) {
  72310. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  72311. }
  72312. else if (document.msIsFullScreen !== undefined) {
  72313. _this._fullscreenVRpresenting = document.msIsFullScreen;
  72314. }
  72315. if (!_this._fullscreenVRpresenting && _this._canvas) {
  72316. _this.exitVR();
  72317. if (!_this._useCustomVRButton) {
  72318. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  72319. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  72320. }
  72321. }
  72322. };
  72323. this.beforeRender = function () {
  72324. _this._castRayAndSelectObject();
  72325. };
  72326. this._onNewGamepadConnected = function (gamepad) {
  72327. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  72328. if (gamepad.leftStick) {
  72329. gamepad.onleftstickchanged(function (stickValues) {
  72330. if (_this._teleportationEnabled) {
  72331. // Listening to classic/xbox gamepad only if no VR controller is active
  72332. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  72333. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  72334. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  72335. _this._checkTeleportWithRay(stickValues);
  72336. _this._checkTeleportBackwards(stickValues);
  72337. }
  72338. }
  72339. });
  72340. }
  72341. if (gamepad.rightStick) {
  72342. gamepad.onrightstickchanged(function (stickValues) {
  72343. if (_this._teleportationEnabled) {
  72344. _this._checkRotate(stickValues);
  72345. }
  72346. });
  72347. }
  72348. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  72349. gamepad.onbuttondown(function (buttonPressed) {
  72350. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  72351. _this._selectionPointerDown();
  72352. }
  72353. });
  72354. gamepad.onbuttonup(function (buttonPressed) {
  72355. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  72356. _this._selectionPointerUp();
  72357. }
  72358. });
  72359. }
  72360. }
  72361. else {
  72362. var webVRController = gamepad;
  72363. _this._tryEnableInteractionOnController(webVRController);
  72364. }
  72365. };
  72366. // 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
  72367. this._tryEnableInteractionOnController = function (webVRController) {
  72368. if (webVRController.hand === "left") {
  72369. _this._leftControllerReady = true;
  72370. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  72371. _this._enableInteractionOnController(webVRController);
  72372. }
  72373. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  72374. _this._enableTeleportationOnController(webVRController);
  72375. }
  72376. }
  72377. if (webVRController.hand === "right") {
  72378. _this._rightControllerReady = true;
  72379. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  72380. _this._enableInteractionOnController(webVRController);
  72381. }
  72382. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  72383. _this._enableTeleportationOnController(webVRController);
  72384. }
  72385. }
  72386. };
  72387. this._onNewGamepadDisconnected = function (gamepad) {
  72388. if (gamepad instanceof BABYLON.WebVRController) {
  72389. if (gamepad.hand === "left") {
  72390. _this._interactionsEnabledOnLeftController = false;
  72391. _this._teleportationEnabledOnLeftController = false;
  72392. _this._leftControllerReady = false;
  72393. if (_this._leftLaserPointer) {
  72394. _this._leftLaserPointer.dispose();
  72395. }
  72396. }
  72397. if (gamepad.hand === "right") {
  72398. _this._interactionsEnabledOnRightController = false;
  72399. _this._teleportationEnabledOnRightController = false;
  72400. _this._rightControllerReady = false;
  72401. if (_this._rightLaserPointer) {
  72402. _this._rightLaserPointer.dispose();
  72403. }
  72404. }
  72405. }
  72406. };
  72407. this._workingVector = BABYLON.Vector3.Zero();
  72408. this._workingQuaternion = BABYLON.Quaternion.Identity();
  72409. this._workingMatrix = BABYLON.Matrix.Identity();
  72410. this._scene = scene;
  72411. this._canvas = scene.getEngine().getRenderingCanvas();
  72412. // Parse options
  72413. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  72414. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  72415. }
  72416. if (webVROptions.createDeviceOrientationCamera === undefined) {
  72417. webVROptions.createDeviceOrientationCamera = true;
  72418. }
  72419. if (webVROptions.defaultHeight === undefined) {
  72420. webVROptions.defaultHeight = 1.7;
  72421. }
  72422. if (webVROptions.useCustomVRButton) {
  72423. this._useCustomVRButton = true;
  72424. if (webVROptions.customVRButton) {
  72425. this._btnVR = webVROptions.customVRButton;
  72426. }
  72427. }
  72428. if (webVROptions.rayLength) {
  72429. this._rayLength = webVROptions.rayLength;
  72430. }
  72431. this._defaultHeight = webVROptions.defaultHeight;
  72432. // Set position
  72433. if (this._scene.activeCamera) {
  72434. this._position = this._scene.activeCamera.position.clone();
  72435. }
  72436. else {
  72437. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  72438. }
  72439. // Set non-vr camera
  72440. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  72441. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  72442. // Copy data from existing camera
  72443. if (this._scene.activeCamera) {
  72444. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  72445. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  72446. // Set rotation from previous camera
  72447. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  72448. var targetCamera = this._scene.activeCamera;
  72449. if (targetCamera.rotationQuaternion) {
  72450. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  72451. }
  72452. else {
  72453. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  72454. }
  72455. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  72456. }
  72457. }
  72458. this._scene.activeCamera = this._deviceOrientationCamera;
  72459. if (this._canvas) {
  72460. this._scene.activeCamera.attachControl(this._canvas);
  72461. }
  72462. }
  72463. else {
  72464. this._existingCamera = this._scene.activeCamera;
  72465. }
  72466. // Create VR cameras
  72467. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  72468. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  72469. }
  72470. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  72471. this._webVRCamera.useStandingMatrix();
  72472. // Create default button
  72473. if (!this._useCustomVRButton) {
  72474. this._btnVR = document.createElement("BUTTON");
  72475. this._btnVR.className = "babylonVRicon";
  72476. this._btnVR.id = "babylonVRiconbtn";
  72477. this._btnVR.title = "Click to switch to VR";
  72478. 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) }";
  72479. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  72480. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  72481. // css += ".babylonVRicon.vrdisplaysupported { }";
  72482. // css += ".babylonVRicon.vrdisplayready { }";
  72483. // css += ".babylonVRicon.vrdisplayrequesting { }";
  72484. var style = document.createElement('style');
  72485. style.appendChild(document.createTextNode(css));
  72486. document.getElementsByTagName('head')[0].appendChild(style);
  72487. this.moveButtonToBottomRight();
  72488. }
  72489. // VR button click event
  72490. if (this._btnVR) {
  72491. this._btnVR.addEventListener("click", function () {
  72492. if (!_this.isInVRMode) {
  72493. _this.enterVR();
  72494. }
  72495. else {
  72496. _this.exitVR();
  72497. }
  72498. });
  72499. }
  72500. // Window events
  72501. window.addEventListener("resize", this._onResize);
  72502. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  72503. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  72504. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  72505. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  72506. // Display vr button when headset is connected
  72507. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  72508. this.displayVRButton();
  72509. }
  72510. else {
  72511. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  72512. if (e.vrDisplay) {
  72513. _this.displayVRButton();
  72514. }
  72515. });
  72516. }
  72517. // Exiting VR mode using 'ESC' key on desktop
  72518. this._onKeyDown = function (event) {
  72519. if (event.keyCode === 27 && _this.isInVRMode) {
  72520. _this.exitVR();
  72521. }
  72522. };
  72523. document.addEventListener("keydown", this._onKeyDown);
  72524. // Exiting VR mode double tapping the touch screen
  72525. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  72526. if (_this.isInVRMode) {
  72527. _this.exitVR();
  72528. if (_this._fullscreenVRpresenting) {
  72529. _this._scene.getEngine().switchFullscreen(true);
  72530. }
  72531. }
  72532. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  72533. // Listen for WebVR display changes
  72534. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  72535. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  72536. this._onVRRequestPresentStart = function () {
  72537. _this._webVRrequesting = true;
  72538. _this.updateButtonVisibility();
  72539. };
  72540. this._onVRRequestPresentComplete = function (success) {
  72541. _this._webVRrequesting = false;
  72542. _this.updateButtonVisibility();
  72543. };
  72544. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  72545. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  72546. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  72547. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  72548. scene.onDisposeObservable.add(function () {
  72549. _this.dispose();
  72550. });
  72551. // Gamepad connection events
  72552. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  72553. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  72554. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  72555. this.updateButtonVisibility();
  72556. //create easing functions
  72557. this._circleEase = new BABYLON.CircleEase();
  72558. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  72559. }
  72560. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  72561. /** Return this.onEnteringVRObservable
  72562. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  72563. */
  72564. get: function () {
  72565. return this.onEnteringVRObservable;
  72566. },
  72567. enumerable: true,
  72568. configurable: true
  72569. });
  72570. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  72571. /** Return this.onExitingVRObservable
  72572. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  72573. */
  72574. get: function () {
  72575. return this.onExitingVRObservable;
  72576. },
  72577. enumerable: true,
  72578. configurable: true
  72579. });
  72580. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  72581. /** Return this.onControllerMeshLoadedObservable
  72582. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  72583. */
  72584. get: function () {
  72585. return this.onControllerMeshLoadedObservable;
  72586. },
  72587. enumerable: true,
  72588. configurable: true
  72589. });
  72590. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  72591. get: function () {
  72592. return this._teleportationTarget;
  72593. },
  72594. set: function (value) {
  72595. if (value) {
  72596. value.name = "teleportationTarget";
  72597. this._isDefaultTeleportationTarget = false;
  72598. this._teleportationTarget = value;
  72599. }
  72600. },
  72601. enumerable: true,
  72602. configurable: true
  72603. });
  72604. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  72605. get: function () {
  72606. return this._displayGaze;
  72607. },
  72608. set: function (value) {
  72609. this._displayGaze = value;
  72610. if (!value) {
  72611. this._gazeTracker.isVisible = false;
  72612. }
  72613. },
  72614. enumerable: true,
  72615. configurable: true
  72616. });
  72617. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  72618. get: function () {
  72619. return this._displayLaserPointer;
  72620. },
  72621. set: function (value) {
  72622. this._displayLaserPointer = value;
  72623. if (!value) {
  72624. if (this._rightLaserPointer) {
  72625. this._rightLaserPointer.isVisible = false;
  72626. }
  72627. if (this._leftLaserPointer) {
  72628. this._leftLaserPointer.isVisible = false;
  72629. }
  72630. }
  72631. else {
  72632. if (this._rightLaserPointer) {
  72633. this._rightLaserPointer.isVisible = true;
  72634. }
  72635. else if (this._leftLaserPointer) {
  72636. this._leftLaserPointer.isVisible = true;
  72637. }
  72638. }
  72639. },
  72640. enumerable: true,
  72641. configurable: true
  72642. });
  72643. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  72644. get: function () {
  72645. return this._deviceOrientationCamera;
  72646. },
  72647. enumerable: true,
  72648. configurable: true
  72649. });
  72650. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  72651. // Based on the current WebVR support, returns the current VR camera used
  72652. get: function () {
  72653. if (this._webVRready) {
  72654. return this._webVRCamera;
  72655. }
  72656. else {
  72657. return this._scene.activeCamera;
  72658. }
  72659. },
  72660. enumerable: true,
  72661. configurable: true
  72662. });
  72663. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  72664. get: function () {
  72665. return this._webVRCamera;
  72666. },
  72667. enumerable: true,
  72668. configurable: true
  72669. });
  72670. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  72671. get: function () {
  72672. return this._vrDeviceOrientationCamera;
  72673. },
  72674. enumerable: true,
  72675. configurable: true
  72676. });
  72677. // Raised when one of the controller has loaded successfully its associated default mesh
  72678. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  72679. this._tryEnableInteractionOnController(webVRController);
  72680. try {
  72681. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  72682. }
  72683. catch (err) {
  72684. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  72685. }
  72686. };
  72687. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  72688. /**
  72689. * Gets a value indicating if we are currently in VR mode.
  72690. */
  72691. get: function () {
  72692. return this._webVRpresenting || this._fullscreenVRpresenting;
  72693. },
  72694. enumerable: true,
  72695. configurable: true
  72696. });
  72697. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  72698. var vrDisplay = this._scene.getEngine().getVRDevice();
  72699. if (vrDisplay) {
  72700. var wasPresenting = this._webVRpresenting;
  72701. // A VR display is connected
  72702. this._webVRpresenting = vrDisplay.isPresenting;
  72703. if (wasPresenting && !this._webVRpresenting)
  72704. this.exitVR();
  72705. }
  72706. else {
  72707. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  72708. }
  72709. this.updateButtonVisibility();
  72710. };
  72711. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  72712. this._webVRsupported = eventArgs.vrSupported;
  72713. this._webVRready = !!eventArgs.vrDisplay;
  72714. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  72715. this.updateButtonVisibility();
  72716. };
  72717. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  72718. if (this._canvas && !this._useCustomVRButton) {
  72719. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  72720. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  72721. }
  72722. };
  72723. VRExperienceHelper.prototype.displayVRButton = function () {
  72724. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  72725. document.body.appendChild(this._btnVR);
  72726. this._btnVRDisplayed = true;
  72727. }
  72728. };
  72729. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  72730. if (!this._btnVR || this._useCustomVRButton) {
  72731. return;
  72732. }
  72733. this._btnVR.className = "babylonVRicon";
  72734. if (this.isInVRMode) {
  72735. this._btnVR.className += " vrdisplaypresenting";
  72736. }
  72737. else {
  72738. if (this._webVRready)
  72739. this._btnVR.className += " vrdisplayready";
  72740. if (this._webVRsupported)
  72741. this._btnVR.className += " vrdisplaysupported";
  72742. if (this._webVRrequesting)
  72743. this._btnVR.className += " vrdisplayrequesting";
  72744. }
  72745. };
  72746. /**
  72747. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  72748. * Otherwise, will use the fullscreen API.
  72749. */
  72750. VRExperienceHelper.prototype.enterVR = function () {
  72751. if (this.onEnteringVRObservable) {
  72752. try {
  72753. this.onEnteringVRObservable.notifyObservers(this);
  72754. }
  72755. catch (err) {
  72756. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  72757. }
  72758. }
  72759. if (this._scene.activeCamera) {
  72760. this._position = this._scene.activeCamera.position.clone();
  72761. // make sure that we return to the last active camera
  72762. this._existingCamera = this._scene.activeCamera;
  72763. }
  72764. if (this._webVRrequesting)
  72765. return;
  72766. // If WebVR is supported and a headset is connected
  72767. if (this._webVRready) {
  72768. if (!this._webVRpresenting) {
  72769. this._webVRCamera.position = this._position;
  72770. this._scene.activeCamera = this._webVRCamera;
  72771. }
  72772. }
  72773. else if (this._vrDeviceOrientationCamera) {
  72774. this._vrDeviceOrientationCamera.position = this._position;
  72775. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  72776. this._scene.getEngine().switchFullscreen(true);
  72777. this.updateButtonVisibility();
  72778. }
  72779. if (this._scene.activeCamera && this._canvas) {
  72780. this._scene.activeCamera.attachControl(this._canvas);
  72781. }
  72782. if (this._interactionsEnabled) {
  72783. this._scene.registerBeforeRender(this.beforeRender);
  72784. }
  72785. };
  72786. /**
  72787. * Attempt to exit VR, or fullscreen.
  72788. */
  72789. VRExperienceHelper.prototype.exitVR = function () {
  72790. if (this.onExitingVRObservable) {
  72791. try {
  72792. this.onExitingVRObservable.notifyObservers(this);
  72793. }
  72794. catch (err) {
  72795. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  72796. }
  72797. }
  72798. if (this._webVRpresenting) {
  72799. this._scene.getEngine().disableVR();
  72800. }
  72801. if (this._scene.activeCamera) {
  72802. this._position = this._scene.activeCamera.position.clone();
  72803. }
  72804. if (this._deviceOrientationCamera) {
  72805. this._deviceOrientationCamera.position = this._position;
  72806. this._scene.activeCamera = this._deviceOrientationCamera;
  72807. if (this._canvas) {
  72808. this._scene.activeCamera.attachControl(this._canvas);
  72809. }
  72810. }
  72811. else if (this._existingCamera) {
  72812. this._existingCamera.position = this._position;
  72813. this._scene.activeCamera = this._existingCamera;
  72814. }
  72815. this.updateButtonVisibility();
  72816. if (this._interactionsEnabled) {
  72817. this._scene.unregisterBeforeRender(this.beforeRender);
  72818. }
  72819. };
  72820. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  72821. get: function () {
  72822. return this._position;
  72823. },
  72824. set: function (value) {
  72825. this._position = value;
  72826. if (this._scene.activeCamera) {
  72827. this._scene.activeCamera.position = value;
  72828. }
  72829. },
  72830. enumerable: true,
  72831. configurable: true
  72832. });
  72833. VRExperienceHelper.prototype.enableInteractions = function () {
  72834. var _this = this;
  72835. if (!this._interactionsEnabled) {
  72836. this._interactionsRequested = true;
  72837. if (this._leftControllerReady && this._webVRCamera.leftController) {
  72838. this._enableInteractionOnController(this._webVRCamera.leftController);
  72839. }
  72840. if (this._rightControllerReady && this._webVRCamera.rightController) {
  72841. this._enableInteractionOnController(this._webVRCamera.rightController);
  72842. }
  72843. this._createGazeTracker();
  72844. this.raySelectionPredicate = function (mesh) {
  72845. return true;
  72846. };
  72847. this.meshSelectionPredicate = function (mesh) {
  72848. return true;
  72849. };
  72850. this._raySelectionPredicate = function (mesh) {
  72851. if (_this._isTeleportationFloor(mesh) || (mesh.isVisible && mesh.name.indexOf("gazeTracker") === -1
  72852. && mesh.name.indexOf("teleportationTarget") === -1
  72853. && mesh.name.indexOf("torusTeleportation") === -1
  72854. && mesh.name.indexOf("laserPointer") === -1)) {
  72855. return _this.raySelectionPredicate(mesh);
  72856. }
  72857. return false;
  72858. };
  72859. this._interactionsEnabled = true;
  72860. }
  72861. };
  72862. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  72863. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  72864. if (this._floorMeshesCollection[i].id === mesh.id) {
  72865. return true;
  72866. }
  72867. }
  72868. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  72869. return true;
  72870. }
  72871. return false;
  72872. };
  72873. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  72874. if (!this._floorMeshesCollection) {
  72875. return;
  72876. }
  72877. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  72878. return;
  72879. }
  72880. this._floorMeshesCollection.push(floorMesh);
  72881. };
  72882. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  72883. if (!this._floorMeshesCollection) {
  72884. return;
  72885. }
  72886. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  72887. if (meshIndex !== -1) {
  72888. this._floorMeshesCollection.splice(meshIndex, 1);
  72889. }
  72890. };
  72891. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  72892. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  72893. if (!this._teleportationEnabled) {
  72894. this._teleportationRequested = true;
  72895. this.enableInteractions();
  72896. if (vrTeleportationOptions.floorMeshName) {
  72897. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  72898. }
  72899. if (vrTeleportationOptions.floorMeshes) {
  72900. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  72901. }
  72902. if (this._leftControllerReady && this._webVRCamera.leftController) {
  72903. this._enableTeleportationOnController(this._webVRCamera.leftController);
  72904. }
  72905. if (this._rightControllerReady && this._webVRCamera.rightController) {
  72906. this._enableTeleportationOnController(this._webVRCamera.rightController);
  72907. }
  72908. // Creates an image processing post process for the vignette not relying
  72909. // on the main scene configuration for image processing to reduce setup and spaces
  72910. // (gamma/linear) conflicts.
  72911. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  72912. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  72913. imageProcessingConfiguration.vignetteEnabled = true;
  72914. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  72915. this._webVRCamera.detachPostProcess(this._postProcessMove);
  72916. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  72917. this._teleportationEnabled = true;
  72918. if (this._isDefaultTeleportationTarget) {
  72919. this._createTeleportationCircles();
  72920. }
  72921. }
  72922. };
  72923. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  72924. var _this = this;
  72925. var controllerMesh = webVRController.mesh;
  72926. if (controllerMesh) {
  72927. var makeNotPick = function (root) {
  72928. root.name += " laserPointer";
  72929. root.getChildMeshes().forEach(function (c) {
  72930. makeNotPick(c);
  72931. });
  72932. };
  72933. makeNotPick(controllerMesh);
  72934. var childMeshes = controllerMesh.getChildMeshes();
  72935. for (var i = 0; i < childMeshes.length; i++) {
  72936. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  72937. controllerMesh = childMeshes[i];
  72938. break;
  72939. }
  72940. }
  72941. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  72942. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  72943. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  72944. laserPointerMaterial.alpha = 0.6;
  72945. laserPointer.material = laserPointerMaterial;
  72946. laserPointer.rotation.x = Math.PI / 2;
  72947. laserPointer.parent = controllerMesh;
  72948. laserPointer.position.z = -0.5;
  72949. laserPointer.isVisible = false;
  72950. if (webVRController.hand === "left") {
  72951. this._leftLaserPointer = laserPointer;
  72952. this._interactionsEnabledOnLeftController = true;
  72953. if (!this._rightLaserPointer) {
  72954. this._leftLaserPointer.isVisible = true;
  72955. }
  72956. }
  72957. else {
  72958. this._rightLaserPointer = laserPointer;
  72959. this._interactionsEnabledOnRightController = true;
  72960. if (!this._leftLaserPointer) {
  72961. this._rightLaserPointer.isVisible = true;
  72962. }
  72963. }
  72964. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  72965. // Enabling / disabling laserPointer
  72966. if (_this._displayLaserPointer && stateObject.value === 1) {
  72967. laserPointer.isVisible = !laserPointer.isVisible;
  72968. // Laser pointer can only be active on left or right, not both at the same time
  72969. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  72970. _this._rightLaserPointer.isVisible = false;
  72971. }
  72972. else if (_this._leftLaserPointer) {
  72973. _this._leftLaserPointer.isVisible = false;
  72974. }
  72975. }
  72976. });
  72977. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  72978. if (!_this._pointerDownOnMeshAsked) {
  72979. if (stateObject.value > _this._padSensibilityUp) {
  72980. _this._selectionPointerDown();
  72981. }
  72982. }
  72983. else if (stateObject.value < _this._padSensibilityDown) {
  72984. _this._selectionPointerUp();
  72985. }
  72986. });
  72987. }
  72988. };
  72989. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  72990. if (webVRController === void 0) { webVRController = null; }
  72991. if (!this._teleportationRequestInitiated) {
  72992. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  72993. if (webVRController) {
  72994. // If laser pointer wasn't enabled yet
  72995. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  72996. this._leftLaserPointer.isVisible = true;
  72997. if (this._rightLaserPointer) {
  72998. this._rightLaserPointer.isVisible = false;
  72999. }
  73000. }
  73001. else if (this._displayLaserPointer && this._rightLaserPointer) {
  73002. this._rightLaserPointer.isVisible = true;
  73003. if (this._leftLaserPointer) {
  73004. this._leftLaserPointer.isVisible = false;
  73005. }
  73006. }
  73007. }
  73008. this._teleportationRequestInitiated = true;
  73009. }
  73010. }
  73011. else {
  73012. // Listening to the proper controller values changes to confirm teleportation
  73013. if (webVRController == null
  73014. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  73015. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  73016. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  73017. if (this._teleportationAllowed) {
  73018. this._teleportationAllowed = false;
  73019. this._teleportCamera();
  73020. }
  73021. this._teleportationRequestInitiated = false;
  73022. }
  73023. }
  73024. }
  73025. };
  73026. VRExperienceHelper.prototype._selectionPointerDown = function () {
  73027. this._pointerDownOnMeshAsked = true;
  73028. if (this._currentMeshSelected && this._currentHit) {
  73029. this._scene.simulatePointerDown(this._currentHit);
  73030. }
  73031. };
  73032. VRExperienceHelper.prototype._selectionPointerUp = function () {
  73033. if (this._currentMeshSelected && this._currentHit) {
  73034. this._scene.simulatePointerUp(this._currentHit);
  73035. }
  73036. this._pointerDownOnMeshAsked = false;
  73037. };
  73038. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  73039. // Only rotate when user is not currently selecting a teleportation location
  73040. if (this._teleportationRequestInitiated) {
  73041. return;
  73042. }
  73043. if (!this._rotationLeftAsked) {
  73044. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  73045. this._rotationLeftAsked = true;
  73046. if (this._rotationAllowed) {
  73047. this._rotateCamera(false);
  73048. }
  73049. }
  73050. }
  73051. else {
  73052. if (stateObject.x > -this._padSensibilityDown) {
  73053. this._rotationLeftAsked = false;
  73054. }
  73055. }
  73056. if (!this._rotationRightAsked) {
  73057. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  73058. this._rotationRightAsked = true;
  73059. if (this._rotationAllowed) {
  73060. this._rotateCamera(true);
  73061. }
  73062. }
  73063. }
  73064. else {
  73065. if (stateObject.x < this._padSensibilityDown) {
  73066. this._rotationRightAsked = false;
  73067. }
  73068. }
  73069. };
  73070. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  73071. // Only teleport backwards when user is not currently selecting a teleportation location
  73072. if (this._teleportationRequestInitiated) {
  73073. return;
  73074. }
  73075. // Teleport backwards
  73076. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  73077. if (!this._teleportationBackRequestInitiated) {
  73078. if (!this.currentVRCamera) {
  73079. return;
  73080. }
  73081. // Get rotation and position of the current camera
  73082. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  73083. var position = this.currentVRCamera.position;
  73084. // If the camera has device position, use that instead
  73085. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  73086. rotation = this.currentVRCamera.deviceRotationQuaternion;
  73087. position = this.currentVRCamera.devicePosition;
  73088. }
  73089. // Get matrix with only the y rotation of the device rotation
  73090. rotation.toEulerAnglesToRef(this._workingVector);
  73091. this._workingVector.z = 0;
  73092. this._workingVector.x = 0;
  73093. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  73094. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  73095. // Rotate backwards ray by device rotation to cast at the ground behind the user
  73096. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  73097. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  73098. var ray = new BABYLON.Ray(position, this._workingVector);
  73099. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  73100. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  73101. this._teleportCamera(hit.pickedPoint);
  73102. }
  73103. this._teleportationBackRequestInitiated = true;
  73104. }
  73105. }
  73106. else {
  73107. this._teleportationBackRequestInitiated = false;
  73108. }
  73109. };
  73110. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  73111. var _this = this;
  73112. var controllerMesh = webVRController.mesh;
  73113. if (controllerMesh) {
  73114. if (webVRController.hand === "left") {
  73115. if (!this._interactionsEnabledOnLeftController) {
  73116. this._enableInteractionOnController(webVRController);
  73117. }
  73118. this._teleportationEnabledOnLeftController = true;
  73119. }
  73120. else {
  73121. if (!this._interactionsEnabledOnRightController) {
  73122. this._enableInteractionOnController(webVRController);
  73123. }
  73124. this._teleportationEnabledOnRightController = true;
  73125. }
  73126. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  73127. this._dpadPressed = false;
  73128. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  73129. _this._dpadPressed = stateObject.pressed;
  73130. if (!_this._dpadPressed) {
  73131. _this._rotationLeftAsked = false;
  73132. _this._rotationRightAsked = false;
  73133. _this._teleportationBackRequestInitiated = false;
  73134. }
  73135. });
  73136. }
  73137. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  73138. _this._checkTeleportBackwards(stateObject);
  73139. _this._checkTeleportWithRay(stateObject, webVRController);
  73140. _this._checkRotate(stateObject);
  73141. });
  73142. }
  73143. };
  73144. // Gaze support used to point to teleport or to interact with an object
  73145. VRExperienceHelper.prototype._createGazeTracker = function () {
  73146. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  73147. this._gazeTracker.bakeCurrentTransformIntoVertices();
  73148. this._gazeTracker.isPickable = false;
  73149. this._gazeTracker.isVisible = false;
  73150. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  73151. targetMat.specularColor = BABYLON.Color3.Black();
  73152. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  73153. targetMat.backFaceCulling = false;
  73154. this._gazeTracker.material = targetMat;
  73155. };
  73156. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  73157. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  73158. this._teleportationTarget.isPickable = false;
  73159. var length = 512;
  73160. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  73161. dynamicTexture.hasAlpha = true;
  73162. var context = dynamicTexture.getContext();
  73163. var centerX = length / 2;
  73164. var centerY = length / 2;
  73165. var radius = 200;
  73166. context.beginPath();
  73167. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  73168. context.fillStyle = this._teleportationFillColor;
  73169. context.fill();
  73170. context.lineWidth = 10;
  73171. context.strokeStyle = this._teleportationBorderColor;
  73172. context.stroke();
  73173. context.closePath();
  73174. dynamicTexture.update();
  73175. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  73176. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  73177. this._teleportationTarget.material = teleportationCircleMaterial;
  73178. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  73179. torus.isPickable = false;
  73180. torus.parent = this._teleportationTarget;
  73181. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  73182. var keys = [];
  73183. keys.push({
  73184. frame: 0,
  73185. value: 0
  73186. });
  73187. keys.push({
  73188. frame: 30,
  73189. value: 0.4
  73190. });
  73191. keys.push({
  73192. frame: 60,
  73193. value: 0
  73194. });
  73195. animationInnerCircle.setKeys(keys);
  73196. var easingFunction = new BABYLON.SineEase();
  73197. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  73198. animationInnerCircle.setEasingFunction(easingFunction);
  73199. torus.animations = [];
  73200. torus.animations.push(animationInnerCircle);
  73201. this._scene.beginAnimation(torus, 0, 60, true);
  73202. this._hideTeleportationTarget();
  73203. };
  73204. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  73205. if (this._teleportationEnabled) {
  73206. this._teleportationTarget.isVisible = true;
  73207. if (this._isDefaultTeleportationTarget) {
  73208. this._teleportationTarget.getChildren()[0].isVisible = true;
  73209. }
  73210. }
  73211. };
  73212. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  73213. if (this._teleportationEnabled) {
  73214. this._teleportationTarget.isVisible = false;
  73215. if (this._isDefaultTeleportationTarget) {
  73216. this._teleportationTarget.getChildren()[0].isVisible = false;
  73217. }
  73218. }
  73219. };
  73220. VRExperienceHelper.prototype._rotateCamera = function (right) {
  73221. var _this = this;
  73222. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  73223. return;
  73224. }
  73225. if (right) {
  73226. this._rotationAngle++;
  73227. }
  73228. else {
  73229. this._rotationAngle--;
  73230. }
  73231. this.currentVRCamera.animations = [];
  73232. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  73233. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  73234. var animationRotationKeys = [];
  73235. animationRotationKeys.push({
  73236. frame: 0,
  73237. value: this.currentVRCamera.rotationQuaternion
  73238. });
  73239. animationRotationKeys.push({
  73240. frame: 6,
  73241. value: target
  73242. });
  73243. animationRotation.setKeys(animationRotationKeys);
  73244. animationRotation.setEasingFunction(this._circleEase);
  73245. this.currentVRCamera.animations.push(animationRotation);
  73246. this._postProcessMove.animations = [];
  73247. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  73248. var vignetteWeightKeys = [];
  73249. vignetteWeightKeys.push({
  73250. frame: 0,
  73251. value: 0
  73252. });
  73253. vignetteWeightKeys.push({
  73254. frame: 3,
  73255. value: 4
  73256. });
  73257. vignetteWeightKeys.push({
  73258. frame: 6,
  73259. value: 0
  73260. });
  73261. animationPP.setKeys(vignetteWeightKeys);
  73262. animationPP.setEasingFunction(this._circleEase);
  73263. this._postProcessMove.animations.push(animationPP);
  73264. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  73265. var vignetteStretchKeys = [];
  73266. vignetteStretchKeys.push({
  73267. frame: 0,
  73268. value: 0
  73269. });
  73270. vignetteStretchKeys.push({
  73271. frame: 3,
  73272. value: 10
  73273. });
  73274. vignetteStretchKeys.push({
  73275. frame: 6,
  73276. value: 0
  73277. });
  73278. animationPP2.setKeys(vignetteStretchKeys);
  73279. animationPP2.setEasingFunction(this._circleEase);
  73280. this._postProcessMove.animations.push(animationPP2);
  73281. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  73282. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  73283. this._webVRCamera.attachPostProcess(this._postProcessMove);
  73284. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  73285. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  73286. });
  73287. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  73288. };
  73289. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  73290. if (hit.pickedPoint) {
  73291. this._teleportationAllowed = true;
  73292. if (this._teleportationRequestInitiated) {
  73293. this._displayTeleportationTarget();
  73294. }
  73295. else {
  73296. this._hideTeleportationTarget();
  73297. }
  73298. this._haloCenter.copyFrom(hit.pickedPoint);
  73299. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  73300. var pickNormal = hit.getNormal(true, false);
  73301. if (pickNormal) {
  73302. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  73303. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  73304. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  73305. }
  73306. this._teleportationTarget.position.y += 0.1;
  73307. }
  73308. };
  73309. VRExperienceHelper.prototype._teleportCamera = function (location) {
  73310. var _this = this;
  73311. if (location === void 0) { location = null; }
  73312. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  73313. return;
  73314. }
  73315. if (!location) {
  73316. location = this._haloCenter;
  73317. }
  73318. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  73319. // offset of the headset from the anchor.
  73320. if (this.webVRCamera.leftCamera) {
  73321. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  73322. this._workingVector.subtractInPlace(this.webVRCamera.position);
  73323. location.subtractToRef(this._workingVector, this._workingVector);
  73324. }
  73325. else {
  73326. this._workingVector.copyFrom(location);
  73327. }
  73328. // Add height to account for user's height offset
  73329. if (this.isInVRMode) {
  73330. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  73331. }
  73332. else {
  73333. this._workingVector.y += this._defaultHeight;
  73334. }
  73335. // Create animation from the camera's position to the new location
  73336. this.currentVRCamera.animations = [];
  73337. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  73338. var animationCameraTeleportationKeys = [{
  73339. frame: 0,
  73340. value: this.currentVRCamera.position
  73341. },
  73342. {
  73343. frame: 11,
  73344. value: this._workingVector
  73345. }
  73346. ];
  73347. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  73348. animationCameraTeleportation.setEasingFunction(this._circleEase);
  73349. this.currentVRCamera.animations.push(animationCameraTeleportation);
  73350. this._postProcessMove.animations = [];
  73351. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  73352. var vignetteWeightKeys = [];
  73353. vignetteWeightKeys.push({
  73354. frame: 0,
  73355. value: 0
  73356. });
  73357. vignetteWeightKeys.push({
  73358. frame: 5,
  73359. value: 8
  73360. });
  73361. vignetteWeightKeys.push({
  73362. frame: 11,
  73363. value: 0
  73364. });
  73365. animationPP.setKeys(vignetteWeightKeys);
  73366. this._postProcessMove.animations.push(animationPP);
  73367. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  73368. var vignetteStretchKeys = [];
  73369. vignetteStretchKeys.push({
  73370. frame: 0,
  73371. value: 0
  73372. });
  73373. vignetteStretchKeys.push({
  73374. frame: 5,
  73375. value: 10
  73376. });
  73377. vignetteStretchKeys.push({
  73378. frame: 11,
  73379. value: 0
  73380. });
  73381. animationPP2.setKeys(vignetteStretchKeys);
  73382. this._postProcessMove.animations.push(animationPP2);
  73383. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  73384. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  73385. this._webVRCamera.attachPostProcess(this._postProcessMove);
  73386. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  73387. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  73388. });
  73389. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1);
  73390. };
  73391. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  73392. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  73393. return;
  73394. }
  73395. var ray;
  73396. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  73397. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  73398. }
  73399. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  73400. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  73401. }
  73402. else {
  73403. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  73404. }
  73405. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  73406. // Moving the gazeTracker on the mesh face targetted
  73407. if (hit && hit.pickedPoint) {
  73408. if (this._displayGaze) {
  73409. var multiplier = 1;
  73410. this._gazeTracker.isVisible = true;
  73411. if (this._isActionableMesh) {
  73412. multiplier = 3;
  73413. }
  73414. this._gazeTracker.scaling.x = hit.distance * multiplier;
  73415. this._gazeTracker.scaling.y = hit.distance * multiplier;
  73416. this._gazeTracker.scaling.z = hit.distance * multiplier;
  73417. var pickNormal = hit.getNormal();
  73418. // To avoid z-fighting
  73419. var deltaFighting = 0.002;
  73420. if (pickNormal) {
  73421. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  73422. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  73423. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  73424. }
  73425. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  73426. if (this._gazeTracker.position.x < 0) {
  73427. this._gazeTracker.position.x += deltaFighting;
  73428. }
  73429. else {
  73430. this._gazeTracker.position.x -= deltaFighting;
  73431. }
  73432. if (this._gazeTracker.position.y < 0) {
  73433. this._gazeTracker.position.y += deltaFighting;
  73434. }
  73435. else {
  73436. this._gazeTracker.position.y -= deltaFighting;
  73437. }
  73438. if (this._gazeTracker.position.z < 0) {
  73439. this._gazeTracker.position.z += deltaFighting;
  73440. }
  73441. else {
  73442. this._gazeTracker.position.z -= deltaFighting;
  73443. }
  73444. }
  73445. // Changing the size of the laser pointer based on the distance from the targetted point
  73446. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  73447. this._rightLaserPointer.scaling.y = hit.distance;
  73448. this._rightLaserPointer.position.z = -hit.distance / 2;
  73449. }
  73450. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  73451. this._leftLaserPointer.scaling.y = hit.distance;
  73452. this._leftLaserPointer.position.z = -hit.distance / 2;
  73453. }
  73454. }
  73455. else {
  73456. this._gazeTracker.isVisible = false;
  73457. }
  73458. if (hit && hit.pickedMesh) {
  73459. this._currentHit = hit;
  73460. if (this._pointerDownOnMeshAsked) {
  73461. this._scene.simulatePointerMove(this._currentHit);
  73462. }
  73463. // The object selected is the floor, we're in a teleportation scenario
  73464. if (this._teleportationEnabled && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  73465. // Moving the teleportation area to this targetted point
  73466. this._moveTeleportationSelectorTo(hit);
  73467. return;
  73468. }
  73469. // If not, we're in a selection scenario
  73470. this._hideTeleportationTarget();
  73471. this._teleportationAllowed = false;
  73472. if (hit.pickedMesh !== this._currentMeshSelected) {
  73473. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  73474. this._currentMeshSelected = hit.pickedMesh;
  73475. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  73476. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  73477. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  73478. this._isActionableMesh = true;
  73479. }
  73480. else {
  73481. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  73482. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  73483. this._isActionableMesh = false;
  73484. }
  73485. try {
  73486. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  73487. }
  73488. catch (err) {
  73489. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  73490. }
  73491. }
  73492. else {
  73493. if (this._currentMeshSelected) {
  73494. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  73495. }
  73496. this._currentMeshSelected = null;
  73497. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  73498. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  73499. }
  73500. }
  73501. }
  73502. else {
  73503. this._currentHit = null;
  73504. this._currentMeshSelected = null;
  73505. this._teleportationAllowed = false;
  73506. this._hideTeleportationTarget();
  73507. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  73508. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  73509. }
  73510. };
  73511. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  73512. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  73513. this._leftLaserPointer.material.emissiveColor = color;
  73514. }
  73515. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  73516. this._rightLaserPointer.material.emissiveColor = color;
  73517. }
  73518. };
  73519. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  73520. if (this._gazeTracker.material) {
  73521. this._gazeTracker.material.emissiveColor = color;
  73522. }
  73523. };
  73524. VRExperienceHelper.prototype.dispose = function () {
  73525. if (this.isInVRMode) {
  73526. this.exitVR();
  73527. }
  73528. if (this._passProcessMove) {
  73529. this._passProcessMove.dispose();
  73530. }
  73531. if (this._postProcessMove) {
  73532. this._postProcessMove.dispose();
  73533. }
  73534. if (this._webVRCamera) {
  73535. this._webVRCamera.dispose();
  73536. }
  73537. if (this._vrDeviceOrientationCamera) {
  73538. this._vrDeviceOrientationCamera.dispose();
  73539. }
  73540. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  73541. document.body.removeChild(this._btnVR);
  73542. }
  73543. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  73544. this._deviceOrientationCamera.dispose();
  73545. }
  73546. if (this._gazeTracker) {
  73547. this._gazeTracker.dispose();
  73548. }
  73549. if (this._teleportationTarget) {
  73550. this._teleportationTarget.dispose();
  73551. }
  73552. this._floorMeshesCollection = [];
  73553. document.removeEventListener("keydown", this._onKeyDown);
  73554. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  73555. window.removeEventListener("resize", this._onResize);
  73556. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  73557. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  73558. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  73559. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  73560. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  73561. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  73562. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  73563. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  73564. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  73565. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  73566. this._scene.unregisterBeforeRender(this.beforeRender);
  73567. };
  73568. VRExperienceHelper.prototype.getClassName = function () {
  73569. return "VRExperienceHelper";
  73570. };
  73571. return VRExperienceHelper;
  73572. }());
  73573. BABYLON.VRExperienceHelper = VRExperienceHelper;
  73574. })(BABYLON || (BABYLON = {}));
  73575. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  73576. // Mainly based on these 2 articles :
  73577. // 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
  73578. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  73579. var BABYLON;
  73580. (function (BABYLON) {
  73581. var JoystickAxis;
  73582. (function (JoystickAxis) {
  73583. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  73584. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  73585. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  73586. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  73587. var VirtualJoystick = /** @class */ (function () {
  73588. function VirtualJoystick(leftJoystick) {
  73589. var _this = this;
  73590. if (leftJoystick) {
  73591. this._leftJoystick = true;
  73592. }
  73593. else {
  73594. this._leftJoystick = false;
  73595. }
  73596. VirtualJoystick._globalJoystickIndex++;
  73597. // By default left & right arrow keys are moving the X
  73598. // and up & down keys are moving the Y
  73599. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  73600. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  73601. this.reverseLeftRight = false;
  73602. this.reverseUpDown = false;
  73603. // collections of pointers
  73604. this._touches = new BABYLON.StringDictionary();
  73605. this.deltaPosition = BABYLON.Vector3.Zero();
  73606. this._joystickSensibility = 25;
  73607. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  73608. this._onResize = function (evt) {
  73609. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  73610. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  73611. if (VirtualJoystick.vjCanvas) {
  73612. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  73613. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  73614. }
  73615. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  73616. };
  73617. // injecting a canvas element on top of the canvas 3D game
  73618. if (!VirtualJoystick.vjCanvas) {
  73619. window.addEventListener("resize", this._onResize, false);
  73620. VirtualJoystick.vjCanvas = document.createElement("canvas");
  73621. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  73622. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  73623. VirtualJoystick.vjCanvas.width = window.innerWidth;
  73624. VirtualJoystick.vjCanvas.height = window.innerHeight;
  73625. VirtualJoystick.vjCanvas.style.width = "100%";
  73626. VirtualJoystick.vjCanvas.style.height = "100%";
  73627. VirtualJoystick.vjCanvas.style.position = "absolute";
  73628. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  73629. VirtualJoystick.vjCanvas.style.top = "0px";
  73630. VirtualJoystick.vjCanvas.style.left = "0px";
  73631. VirtualJoystick.vjCanvas.style.zIndex = "5";
  73632. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  73633. // Support for jQuery PEP polyfill
  73634. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  73635. var context = VirtualJoystick.vjCanvas.getContext('2d');
  73636. if (!context) {
  73637. throw new Error("Unable to create canvas for virtual joystick");
  73638. }
  73639. VirtualJoystick.vjCanvasContext = context;
  73640. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  73641. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  73642. document.body.appendChild(VirtualJoystick.vjCanvas);
  73643. }
  73644. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  73645. this.pressed = false;
  73646. // default joystick color
  73647. this._joystickColor = "cyan";
  73648. this._joystickPointerID = -1;
  73649. // current joystick position
  73650. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  73651. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  73652. // origin joystick position
  73653. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  73654. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  73655. this._onPointerDownHandlerRef = function (evt) {
  73656. _this._onPointerDown(evt);
  73657. };
  73658. this._onPointerMoveHandlerRef = function (evt) {
  73659. _this._onPointerMove(evt);
  73660. };
  73661. this._onPointerUpHandlerRef = function (evt) {
  73662. _this._onPointerUp(evt);
  73663. };
  73664. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  73665. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  73666. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  73667. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  73668. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  73669. evt.preventDefault(); // Disables system menu
  73670. }, false);
  73671. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  73672. }
  73673. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  73674. this._joystickSensibility = newJoystickSensibility;
  73675. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  73676. };
  73677. VirtualJoystick.prototype._onPointerDown = function (e) {
  73678. var positionOnScreenCondition;
  73679. e.preventDefault();
  73680. if (this._leftJoystick === true) {
  73681. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  73682. }
  73683. else {
  73684. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  73685. }
  73686. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  73687. // First contact will be dedicated to the virtual joystick
  73688. this._joystickPointerID = e.pointerId;
  73689. this._joystickPointerStartPos.x = e.clientX;
  73690. this._joystickPointerStartPos.y = e.clientY;
  73691. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  73692. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  73693. this._deltaJoystickVector.x = 0;
  73694. this._deltaJoystickVector.y = 0;
  73695. this.pressed = true;
  73696. this._touches.add(e.pointerId.toString(), e);
  73697. }
  73698. else {
  73699. // You can only trigger the action buttons with a joystick declared
  73700. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  73701. this._action();
  73702. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  73703. }
  73704. }
  73705. };
  73706. VirtualJoystick.prototype._onPointerMove = function (e) {
  73707. // If the current pointer is the one associated to the joystick (first touch contact)
  73708. if (this._joystickPointerID == e.pointerId) {
  73709. this._joystickPointerPos.x = e.clientX;
  73710. this._joystickPointerPos.y = e.clientY;
  73711. this._deltaJoystickVector = this._joystickPointerPos.clone();
  73712. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  73713. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  73714. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  73715. switch (this._axisTargetedByLeftAndRight) {
  73716. case JoystickAxis.X:
  73717. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  73718. break;
  73719. case JoystickAxis.Y:
  73720. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  73721. break;
  73722. case JoystickAxis.Z:
  73723. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  73724. break;
  73725. }
  73726. var directionUpDown = this.reverseUpDown ? 1 : -1;
  73727. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  73728. switch (this._axisTargetedByUpAndDown) {
  73729. case JoystickAxis.X:
  73730. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  73731. break;
  73732. case JoystickAxis.Y:
  73733. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  73734. break;
  73735. case JoystickAxis.Z:
  73736. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  73737. break;
  73738. }
  73739. }
  73740. else {
  73741. var data = this._touches.get(e.pointerId.toString());
  73742. if (data) {
  73743. data.x = e.clientX;
  73744. data.y = e.clientY;
  73745. }
  73746. }
  73747. };
  73748. VirtualJoystick.prototype._onPointerUp = function (e) {
  73749. if (this._joystickPointerID == e.pointerId) {
  73750. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  73751. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  73752. this._joystickPointerID = -1;
  73753. this.pressed = false;
  73754. }
  73755. else {
  73756. var touch = this._touches.get(e.pointerId.toString());
  73757. if (touch) {
  73758. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  73759. }
  73760. }
  73761. this._deltaJoystickVector.x = 0;
  73762. this._deltaJoystickVector.y = 0;
  73763. this._touches.remove(e.pointerId.toString());
  73764. };
  73765. /**
  73766. * Change the color of the virtual joystick
  73767. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  73768. */
  73769. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  73770. this._joystickColor = newColor;
  73771. };
  73772. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  73773. this._action = action;
  73774. };
  73775. // Define which axis you'd like to control for left & right
  73776. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  73777. switch (axis) {
  73778. case JoystickAxis.X:
  73779. case JoystickAxis.Y:
  73780. case JoystickAxis.Z:
  73781. this._axisTargetedByLeftAndRight = axis;
  73782. break;
  73783. default:
  73784. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  73785. break;
  73786. }
  73787. };
  73788. // Define which axis you'd like to control for up & down
  73789. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  73790. switch (axis) {
  73791. case JoystickAxis.X:
  73792. case JoystickAxis.Y:
  73793. case JoystickAxis.Z:
  73794. this._axisTargetedByUpAndDown = axis;
  73795. break;
  73796. default:
  73797. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  73798. break;
  73799. }
  73800. };
  73801. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  73802. var _this = this;
  73803. if (this.pressed) {
  73804. this._touches.forEach(function (key, touch) {
  73805. if (touch.pointerId === _this._joystickPointerID) {
  73806. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  73807. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  73808. VirtualJoystick.vjCanvasContext.beginPath();
  73809. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  73810. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  73811. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  73812. VirtualJoystick.vjCanvasContext.stroke();
  73813. VirtualJoystick.vjCanvasContext.closePath();
  73814. VirtualJoystick.vjCanvasContext.beginPath();
  73815. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  73816. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  73817. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  73818. VirtualJoystick.vjCanvasContext.stroke();
  73819. VirtualJoystick.vjCanvasContext.closePath();
  73820. VirtualJoystick.vjCanvasContext.beginPath();
  73821. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  73822. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  73823. VirtualJoystick.vjCanvasContext.stroke();
  73824. VirtualJoystick.vjCanvasContext.closePath();
  73825. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  73826. }
  73827. else {
  73828. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  73829. VirtualJoystick.vjCanvasContext.beginPath();
  73830. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  73831. VirtualJoystick.vjCanvasContext.beginPath();
  73832. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  73833. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  73834. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  73835. VirtualJoystick.vjCanvasContext.stroke();
  73836. VirtualJoystick.vjCanvasContext.closePath();
  73837. touch.prevX = touch.x;
  73838. touch.prevY = touch.y;
  73839. }
  73840. ;
  73841. });
  73842. }
  73843. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  73844. };
  73845. VirtualJoystick.prototype.releaseCanvas = function () {
  73846. if (VirtualJoystick.vjCanvas) {
  73847. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  73848. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  73849. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  73850. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  73851. window.removeEventListener("resize", this._onResize);
  73852. document.body.removeChild(VirtualJoystick.vjCanvas);
  73853. VirtualJoystick.vjCanvas = null;
  73854. }
  73855. };
  73856. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  73857. VirtualJoystick._globalJoystickIndex = 0;
  73858. return VirtualJoystick;
  73859. }());
  73860. BABYLON.VirtualJoystick = VirtualJoystick;
  73861. })(BABYLON || (BABYLON = {}));
  73862. //# sourceMappingURL=babylon.virtualJoystick.js.map
  73863. var BABYLON;
  73864. (function (BABYLON) {
  73865. // We're mainly based on the logic defined into the FreeCamera code
  73866. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  73867. __extends(VirtualJoysticksCamera, _super);
  73868. function VirtualJoysticksCamera(name, position, scene) {
  73869. var _this = _super.call(this, name, position, scene) || this;
  73870. _this.inputs.addVirtualJoystick();
  73871. return _this;
  73872. }
  73873. VirtualJoysticksCamera.prototype.getClassName = function () {
  73874. return "VirtualJoysticksCamera";
  73875. };
  73876. return VirtualJoysticksCamera;
  73877. }(BABYLON.FreeCamera));
  73878. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  73879. })(BABYLON || (BABYLON = {}));
  73880. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  73881. var BABYLON;
  73882. (function (BABYLON) {
  73883. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  73884. function FreeCameraVirtualJoystickInput() {
  73885. }
  73886. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  73887. return this._leftjoystick;
  73888. };
  73889. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  73890. return this._rightjoystick;
  73891. };
  73892. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  73893. if (this._leftjoystick) {
  73894. var camera = this.camera;
  73895. var speed = camera._computeLocalCameraSpeed() * 50;
  73896. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  73897. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  73898. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  73899. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  73900. if (!this._leftjoystick.pressed) {
  73901. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  73902. }
  73903. if (!this._rightjoystick.pressed) {
  73904. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  73905. }
  73906. }
  73907. };
  73908. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  73909. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  73910. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  73911. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  73912. this._leftjoystick.setJoystickSensibility(0.15);
  73913. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  73914. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  73915. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  73916. this._rightjoystick.reverseUpDown = true;
  73917. this._rightjoystick.setJoystickSensibility(0.05);
  73918. this._rightjoystick.setJoystickColor("yellow");
  73919. };
  73920. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  73921. this._leftjoystick.releaseCanvas();
  73922. this._rightjoystick.releaseCanvas();
  73923. };
  73924. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  73925. return "FreeCameraVirtualJoystickInput";
  73926. };
  73927. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  73928. return "virtualJoystick";
  73929. };
  73930. return FreeCameraVirtualJoystickInput;
  73931. }());
  73932. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  73933. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  73934. })(BABYLON || (BABYLON = {}));
  73935. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  73936. var BABYLON;
  73937. (function (BABYLON) {
  73938. var SimplificationSettings = /** @class */ (function () {
  73939. function SimplificationSettings(quality, distance, optimizeMesh) {
  73940. this.quality = quality;
  73941. this.distance = distance;
  73942. this.optimizeMesh = optimizeMesh;
  73943. }
  73944. return SimplificationSettings;
  73945. }());
  73946. BABYLON.SimplificationSettings = SimplificationSettings;
  73947. var SimplificationQueue = /** @class */ (function () {
  73948. function SimplificationQueue() {
  73949. this.running = false;
  73950. this._simplificationArray = [];
  73951. }
  73952. SimplificationQueue.prototype.addTask = function (task) {
  73953. this._simplificationArray.push(task);
  73954. };
  73955. SimplificationQueue.prototype.executeNext = function () {
  73956. var task = this._simplificationArray.pop();
  73957. if (task) {
  73958. this.running = true;
  73959. this.runSimplification(task);
  73960. }
  73961. else {
  73962. this.running = false;
  73963. }
  73964. };
  73965. SimplificationQueue.prototype.runSimplification = function (task) {
  73966. var _this = this;
  73967. if (task.parallelProcessing) {
  73968. //parallel simplifier
  73969. task.settings.forEach(function (setting) {
  73970. var simplifier = _this.getSimplifier(task);
  73971. simplifier.simplify(setting, function (newMesh) {
  73972. task.mesh.addLODLevel(setting.distance, newMesh);
  73973. newMesh.isVisible = true;
  73974. //check if it is the last
  73975. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  73976. //all done, run the success callback.
  73977. task.successCallback();
  73978. }
  73979. _this.executeNext();
  73980. });
  73981. });
  73982. }
  73983. else {
  73984. //single simplifier.
  73985. var simplifier = this.getSimplifier(task);
  73986. var runDecimation = function (setting, callback) {
  73987. simplifier.simplify(setting, function (newMesh) {
  73988. task.mesh.addLODLevel(setting.distance, newMesh);
  73989. newMesh.isVisible = true;
  73990. //run the next quality level
  73991. callback();
  73992. });
  73993. };
  73994. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  73995. runDecimation(task.settings[loop.index], function () {
  73996. loop.executeNext();
  73997. });
  73998. }, function () {
  73999. //execution ended, run the success callback.
  74000. if (task.successCallback) {
  74001. task.successCallback();
  74002. }
  74003. _this.executeNext();
  74004. });
  74005. }
  74006. };
  74007. SimplificationQueue.prototype.getSimplifier = function (task) {
  74008. switch (task.simplificationType) {
  74009. case SimplificationType.QUADRATIC:
  74010. default:
  74011. return new QuadraticErrorSimplification(task.mesh);
  74012. }
  74013. };
  74014. return SimplificationQueue;
  74015. }());
  74016. BABYLON.SimplificationQueue = SimplificationQueue;
  74017. /**
  74018. * The implemented types of simplification.
  74019. * At the moment only Quadratic Error Decimation is implemented.
  74020. */
  74021. var SimplificationType;
  74022. (function (SimplificationType) {
  74023. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  74024. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  74025. var DecimationTriangle = /** @class */ (function () {
  74026. function DecimationTriangle(vertices) {
  74027. this.vertices = vertices;
  74028. this.error = new Array(4);
  74029. this.deleted = false;
  74030. this.isDirty = false;
  74031. this.deletePending = false;
  74032. this.borderFactor = 0;
  74033. }
  74034. return DecimationTriangle;
  74035. }());
  74036. BABYLON.DecimationTriangle = DecimationTriangle;
  74037. var DecimationVertex = /** @class */ (function () {
  74038. function DecimationVertex(position, id) {
  74039. this.position = position;
  74040. this.id = id;
  74041. this.isBorder = true;
  74042. this.q = new QuadraticMatrix();
  74043. this.triangleCount = 0;
  74044. this.triangleStart = 0;
  74045. this.originalOffsets = [];
  74046. }
  74047. DecimationVertex.prototype.updatePosition = function (newPosition) {
  74048. this.position.copyFrom(newPosition);
  74049. };
  74050. return DecimationVertex;
  74051. }());
  74052. BABYLON.DecimationVertex = DecimationVertex;
  74053. var QuadraticMatrix = /** @class */ (function () {
  74054. function QuadraticMatrix(data) {
  74055. this.data = new Array(10);
  74056. for (var i = 0; i < 10; ++i) {
  74057. if (data && data[i]) {
  74058. this.data[i] = data[i];
  74059. }
  74060. else {
  74061. this.data[i] = 0;
  74062. }
  74063. }
  74064. }
  74065. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  74066. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  74067. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  74068. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  74069. return det;
  74070. };
  74071. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  74072. for (var i = 0; i < 10; ++i) {
  74073. this.data[i] += matrix.data[i];
  74074. }
  74075. };
  74076. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  74077. for (var i = 0; i < 10; ++i) {
  74078. this.data[i] += data[i];
  74079. }
  74080. };
  74081. QuadraticMatrix.prototype.add = function (matrix) {
  74082. var m = new QuadraticMatrix();
  74083. for (var i = 0; i < 10; ++i) {
  74084. m.data[i] = this.data[i] + matrix.data[i];
  74085. }
  74086. return m;
  74087. };
  74088. QuadraticMatrix.FromData = function (a, b, c, d) {
  74089. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  74090. };
  74091. //returning an array to avoid garbage collection
  74092. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  74093. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  74094. };
  74095. return QuadraticMatrix;
  74096. }());
  74097. BABYLON.QuadraticMatrix = QuadraticMatrix;
  74098. var Reference = /** @class */ (function () {
  74099. function Reference(vertexId, triangleId) {
  74100. this.vertexId = vertexId;
  74101. this.triangleId = triangleId;
  74102. }
  74103. return Reference;
  74104. }());
  74105. BABYLON.Reference = Reference;
  74106. /**
  74107. * An implementation of the Quadratic Error simplification algorithm.
  74108. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  74109. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  74110. * @author RaananW
  74111. */
  74112. var QuadraticErrorSimplification = /** @class */ (function () {
  74113. function QuadraticErrorSimplification(_mesh) {
  74114. this._mesh = _mesh;
  74115. this.syncIterations = 5000;
  74116. this.aggressiveness = 7;
  74117. this.decimationIterations = 100;
  74118. this.boundingBoxEpsilon = BABYLON.Epsilon;
  74119. }
  74120. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  74121. var _this = this;
  74122. this.initDecimatedMesh();
  74123. //iterating through the submeshes array, one after the other.
  74124. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  74125. _this.initWithMesh(loop.index, function () {
  74126. _this.runDecimation(settings, loop.index, function () {
  74127. loop.executeNext();
  74128. });
  74129. }, settings.optimizeMesh);
  74130. }, function () {
  74131. setTimeout(function () {
  74132. successCallback(_this._reconstructedMesh);
  74133. }, 0);
  74134. });
  74135. };
  74136. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  74137. var _this = this;
  74138. var targetCount = ~~(this.triangles.length * settings.quality);
  74139. var deletedTriangles = 0;
  74140. var triangleCount = this.triangles.length;
  74141. var iterationFunction = function (iteration, callback) {
  74142. setTimeout(function () {
  74143. if (iteration % 5 === 0) {
  74144. _this.updateMesh(iteration === 0);
  74145. }
  74146. for (var i = 0; i < _this.triangles.length; ++i) {
  74147. _this.triangles[i].isDirty = false;
  74148. }
  74149. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  74150. var trianglesIterator = function (i) {
  74151. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  74152. var t = _this.triangles[tIdx];
  74153. if (!t)
  74154. return;
  74155. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  74156. return;
  74157. }
  74158. for (var j = 0; j < 3; ++j) {
  74159. if (t.error[j] < threshold) {
  74160. var deleted0 = [];
  74161. var deleted1 = [];
  74162. var v0 = t.vertices[j];
  74163. var v1 = t.vertices[(j + 1) % 3];
  74164. if (v0.isBorder || v1.isBorder)
  74165. continue;
  74166. var p = BABYLON.Vector3.Zero();
  74167. var n = BABYLON.Vector3.Zero();
  74168. var uv = BABYLON.Vector2.Zero();
  74169. var color = new BABYLON.Color4(0, 0, 0, 1);
  74170. _this.calculateError(v0, v1, p, n, uv, color);
  74171. var delTr = new Array();
  74172. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  74173. continue;
  74174. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  74175. continue;
  74176. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  74177. continue;
  74178. var uniqueArray = new Array();
  74179. delTr.forEach(function (deletedT) {
  74180. if (uniqueArray.indexOf(deletedT) === -1) {
  74181. deletedT.deletePending = true;
  74182. uniqueArray.push(deletedT);
  74183. }
  74184. });
  74185. if (uniqueArray.length % 2 !== 0) {
  74186. continue;
  74187. }
  74188. v0.q = v1.q.add(v0.q);
  74189. v0.updatePosition(p);
  74190. var tStart = _this.references.length;
  74191. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  74192. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  74193. var tCount = _this.references.length - tStart;
  74194. if (tCount <= v0.triangleCount) {
  74195. if (tCount) {
  74196. for (var c = 0; c < tCount; c++) {
  74197. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  74198. }
  74199. }
  74200. }
  74201. else {
  74202. v0.triangleStart = tStart;
  74203. }
  74204. v0.triangleCount = tCount;
  74205. break;
  74206. }
  74207. }
  74208. };
  74209. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  74210. }, 0);
  74211. };
  74212. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  74213. if (triangleCount - deletedTriangles <= targetCount)
  74214. loop.breakLoop();
  74215. else {
  74216. iterationFunction(loop.index, function () {
  74217. loop.executeNext();
  74218. });
  74219. }
  74220. }, function () {
  74221. setTimeout(function () {
  74222. //reconstruct this part of the mesh
  74223. _this.reconstructMesh(submeshIndex);
  74224. successCallback();
  74225. }, 0);
  74226. });
  74227. };
  74228. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  74229. var _this = this;
  74230. this.vertices = [];
  74231. this.triangles = [];
  74232. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  74233. var indices = this._mesh.getIndices();
  74234. var submesh = this._mesh.subMeshes[submeshIndex];
  74235. var findInVertices = function (positionToSearch) {
  74236. if (optimizeMesh) {
  74237. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  74238. if (_this.vertices[ii].position.equals(positionToSearch)) {
  74239. return _this.vertices[ii];
  74240. }
  74241. }
  74242. }
  74243. return null;
  74244. };
  74245. var vertexReferences = [];
  74246. var vertexInit = function (i) {
  74247. if (!positionData) {
  74248. return;
  74249. }
  74250. var offset = i + submesh.verticesStart;
  74251. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  74252. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  74253. vertex.originalOffsets.push(offset);
  74254. if (vertex.id === _this.vertices.length) {
  74255. _this.vertices.push(vertex);
  74256. }
  74257. vertexReferences.push(vertex.id);
  74258. };
  74259. //var totalVertices = mesh.getTotalVertices();
  74260. var totalVertices = submesh.verticesCount;
  74261. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  74262. var indicesInit = function (i) {
  74263. if (!indices) {
  74264. return;
  74265. }
  74266. var offset = (submesh.indexStart / 3) + i;
  74267. var pos = (offset * 3);
  74268. var i0 = indices[pos + 0];
  74269. var i1 = indices[pos + 1];
  74270. var i2 = indices[pos + 2];
  74271. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  74272. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  74273. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  74274. var triangle = new DecimationTriangle([v0, v1, v2]);
  74275. triangle.originalOffset = pos;
  74276. _this.triangles.push(triangle);
  74277. };
  74278. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  74279. _this.init(callback);
  74280. });
  74281. });
  74282. };
  74283. QuadraticErrorSimplification.prototype.init = function (callback) {
  74284. var _this = this;
  74285. var triangleInit1 = function (i) {
  74286. var t = _this.triangles[i];
  74287. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  74288. for (var j = 0; j < 3; j++) {
  74289. 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))));
  74290. }
  74291. };
  74292. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  74293. var triangleInit2 = function (i) {
  74294. var t = _this.triangles[i];
  74295. for (var j = 0; j < 3; ++j) {
  74296. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  74297. }
  74298. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  74299. };
  74300. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  74301. callback();
  74302. });
  74303. });
  74304. };
  74305. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  74306. var newTriangles = [];
  74307. var i;
  74308. for (i = 0; i < this.vertices.length; ++i) {
  74309. this.vertices[i].triangleCount = 0;
  74310. }
  74311. var t;
  74312. var j;
  74313. for (i = 0; i < this.triangles.length; ++i) {
  74314. if (!this.triangles[i].deleted) {
  74315. t = this.triangles[i];
  74316. for (j = 0; j < 3; ++j) {
  74317. t.vertices[j].triangleCount = 1;
  74318. }
  74319. newTriangles.push(t);
  74320. }
  74321. }
  74322. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  74323. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  74324. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  74325. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  74326. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  74327. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  74328. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  74329. var vertexCount = 0;
  74330. for (i = 0; i < this.vertices.length; ++i) {
  74331. var vertex = this.vertices[i];
  74332. vertex.id = vertexCount;
  74333. if (vertex.triangleCount) {
  74334. vertex.originalOffsets.forEach(function (originalOffset) {
  74335. if (!normalData) {
  74336. return;
  74337. }
  74338. newPositionData.push(vertex.position.x);
  74339. newPositionData.push(vertex.position.y);
  74340. newPositionData.push(vertex.position.z);
  74341. newNormalData.push(normalData[originalOffset * 3]);
  74342. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  74343. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  74344. if (uvs && uvs.length) {
  74345. newUVsData.push(uvs[(originalOffset * 2)]);
  74346. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  74347. }
  74348. else if (colorsData && colorsData.length) {
  74349. newColorsData.push(colorsData[(originalOffset * 4)]);
  74350. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  74351. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  74352. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  74353. }
  74354. ++vertexCount;
  74355. });
  74356. }
  74357. }
  74358. var startingIndex = this._reconstructedMesh.getTotalIndices();
  74359. var startingVertex = this._reconstructedMesh.getTotalVertices();
  74360. var submeshesArray = this._reconstructedMesh.subMeshes;
  74361. this._reconstructedMesh.subMeshes = [];
  74362. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  74363. var originalIndices = this._mesh.getIndices();
  74364. for (i = 0; i < newTriangles.length; ++i) {
  74365. t = newTriangles[i]; //now get the new referencing point for each vertex
  74366. [0, 1, 2].forEach(function (idx) {
  74367. var id = originalIndices[t.originalOffset + idx];
  74368. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  74369. if (offset < 0)
  74370. offset = 0;
  74371. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  74372. });
  74373. }
  74374. //overwriting the old vertex buffers and indices.
  74375. this._reconstructedMesh.setIndices(newIndicesArray);
  74376. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  74377. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  74378. if (newUVsData.length > 0)
  74379. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  74380. if (newColorsData.length > 0)
  74381. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  74382. //create submesh
  74383. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  74384. if (submeshIndex > 0) {
  74385. this._reconstructedMesh.subMeshes = [];
  74386. submeshesArray.forEach(function (submesh) {
  74387. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  74388. });
  74389. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  74390. }
  74391. };
  74392. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  74393. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  74394. this._reconstructedMesh.material = this._mesh.material;
  74395. this._reconstructedMesh.parent = this._mesh.parent;
  74396. this._reconstructedMesh.isVisible = false;
  74397. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  74398. };
  74399. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  74400. for (var i = 0; i < vertex1.triangleCount; ++i) {
  74401. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  74402. if (t.deleted)
  74403. continue;
  74404. var s = this.references[vertex1.triangleStart + i].vertexId;
  74405. var v1 = t.vertices[(s + 1) % 3];
  74406. var v2 = t.vertices[(s + 2) % 3];
  74407. if ((v1 === vertex2 || v2 === vertex2)) {
  74408. deletedArray[i] = true;
  74409. delTr.push(t);
  74410. continue;
  74411. }
  74412. var d1 = v1.position.subtract(point);
  74413. d1 = d1.normalize();
  74414. var d2 = v2.position.subtract(point);
  74415. d2 = d2.normalize();
  74416. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  74417. return true;
  74418. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  74419. deletedArray[i] = false;
  74420. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  74421. return true;
  74422. }
  74423. return false;
  74424. };
  74425. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  74426. var newDeleted = deletedTriangles;
  74427. for (var i = 0; i < vertex.triangleCount; ++i) {
  74428. var ref = this.references[vertex.triangleStart + i];
  74429. var t = this.triangles[ref.triangleId];
  74430. if (t.deleted)
  74431. continue;
  74432. if (deletedArray[i] && t.deletePending) {
  74433. t.deleted = true;
  74434. newDeleted++;
  74435. continue;
  74436. }
  74437. t.vertices[ref.vertexId] = origVertex;
  74438. t.isDirty = true;
  74439. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  74440. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  74441. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  74442. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  74443. this.references.push(ref);
  74444. }
  74445. return newDeleted;
  74446. };
  74447. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  74448. for (var i = 0; i < this.vertices.length; ++i) {
  74449. var vCount = [];
  74450. var vId = [];
  74451. var v = this.vertices[i];
  74452. var j;
  74453. for (j = 0; j < v.triangleCount; ++j) {
  74454. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  74455. for (var ii = 0; ii < 3; ii++) {
  74456. var ofs = 0;
  74457. var vv = triangle.vertices[ii];
  74458. while (ofs < vCount.length) {
  74459. if (vId[ofs] === vv.id)
  74460. break;
  74461. ++ofs;
  74462. }
  74463. if (ofs === vCount.length) {
  74464. vCount.push(1);
  74465. vId.push(vv.id);
  74466. }
  74467. else {
  74468. vCount[ofs]++;
  74469. }
  74470. }
  74471. }
  74472. for (j = 0; j < vCount.length; ++j) {
  74473. if (vCount[j] === 1) {
  74474. this.vertices[vId[j]].isBorder = true;
  74475. }
  74476. else {
  74477. this.vertices[vId[j]].isBorder = false;
  74478. }
  74479. }
  74480. }
  74481. };
  74482. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  74483. if (identifyBorders === void 0) { identifyBorders = false; }
  74484. var i;
  74485. if (!identifyBorders) {
  74486. var newTrianglesVector = [];
  74487. for (i = 0; i < this.triangles.length; ++i) {
  74488. if (!this.triangles[i].deleted) {
  74489. newTrianglesVector.push(this.triangles[i]);
  74490. }
  74491. }
  74492. this.triangles = newTrianglesVector;
  74493. }
  74494. for (i = 0; i < this.vertices.length; ++i) {
  74495. this.vertices[i].triangleCount = 0;
  74496. this.vertices[i].triangleStart = 0;
  74497. }
  74498. var t;
  74499. var j;
  74500. var v;
  74501. for (i = 0; i < this.triangles.length; ++i) {
  74502. t = this.triangles[i];
  74503. for (j = 0; j < 3; ++j) {
  74504. v = t.vertices[j];
  74505. v.triangleCount++;
  74506. }
  74507. }
  74508. var tStart = 0;
  74509. for (i = 0; i < this.vertices.length; ++i) {
  74510. this.vertices[i].triangleStart = tStart;
  74511. tStart += this.vertices[i].triangleCount;
  74512. this.vertices[i].triangleCount = 0;
  74513. }
  74514. var newReferences = new Array(this.triangles.length * 3);
  74515. for (i = 0; i < this.triangles.length; ++i) {
  74516. t = this.triangles[i];
  74517. for (j = 0; j < 3; ++j) {
  74518. v = t.vertices[j];
  74519. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  74520. v.triangleCount++;
  74521. }
  74522. }
  74523. this.references = newReferences;
  74524. if (identifyBorders) {
  74525. this.identifyBorder();
  74526. }
  74527. };
  74528. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  74529. var x = point.x;
  74530. var y = point.y;
  74531. var z = point.z;
  74532. 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
  74533. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  74534. };
  74535. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  74536. var q = vertex1.q.add(vertex2.q);
  74537. var border = vertex1.isBorder && vertex2.isBorder;
  74538. var error = 0;
  74539. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  74540. if (qDet !== 0 && !border) {
  74541. if (!pointResult) {
  74542. pointResult = BABYLON.Vector3.Zero();
  74543. }
  74544. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  74545. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  74546. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  74547. error = this.vertexError(q, pointResult);
  74548. }
  74549. else {
  74550. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  74551. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  74552. var error1 = this.vertexError(q, vertex1.position);
  74553. var error2 = this.vertexError(q, vertex2.position);
  74554. var error3 = this.vertexError(q, p3);
  74555. error = Math.min(error1, error2, error3);
  74556. if (error === error1) {
  74557. if (pointResult) {
  74558. pointResult.copyFrom(vertex1.position);
  74559. }
  74560. }
  74561. else if (error === error2) {
  74562. if (pointResult) {
  74563. pointResult.copyFrom(vertex2.position);
  74564. }
  74565. }
  74566. else {
  74567. if (pointResult) {
  74568. pointResult.copyFrom(p3);
  74569. }
  74570. }
  74571. }
  74572. return error;
  74573. };
  74574. return QuadraticErrorSimplification;
  74575. }());
  74576. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  74577. })(BABYLON || (BABYLON = {}));
  74578. //# sourceMappingURL=babylon.meshSimplification.js.map
  74579. var BABYLON;
  74580. (function (BABYLON) {
  74581. var Internals;
  74582. (function (Internals) {
  74583. var MeshLODLevel = /** @class */ (function () {
  74584. function MeshLODLevel(distance, mesh) {
  74585. this.distance = distance;
  74586. this.mesh = mesh;
  74587. }
  74588. return MeshLODLevel;
  74589. }());
  74590. Internals.MeshLODLevel = MeshLODLevel;
  74591. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  74592. })(BABYLON || (BABYLON = {}));
  74593. //# sourceMappingURL=babylon.meshLODLevel.js.map
  74594. var BABYLON;
  74595. (function (BABYLON) {
  74596. // Standard optimizations
  74597. var SceneOptimization = /** @class */ (function () {
  74598. function SceneOptimization(priority) {
  74599. if (priority === void 0) { priority = 0; }
  74600. this.priority = priority;
  74601. this.apply = function (scene) {
  74602. return true; // Return true if everything that can be done was applied
  74603. };
  74604. }
  74605. return SceneOptimization;
  74606. }());
  74607. BABYLON.SceneOptimization = SceneOptimization;
  74608. var TextureOptimization = /** @class */ (function (_super) {
  74609. __extends(TextureOptimization, _super);
  74610. function TextureOptimization(priority, maximumSize) {
  74611. if (priority === void 0) { priority = 0; }
  74612. if (maximumSize === void 0) { maximumSize = 1024; }
  74613. var _this = _super.call(this, priority) || this;
  74614. _this.priority = priority;
  74615. _this.maximumSize = maximumSize;
  74616. _this.apply = function (scene) {
  74617. var allDone = true;
  74618. for (var index = 0; index < scene.textures.length; index++) {
  74619. var texture = scene.textures[index];
  74620. if (!texture.canRescale || texture.getContext) {
  74621. continue;
  74622. }
  74623. var currentSize = texture.getSize();
  74624. var maxDimension = Math.max(currentSize.width, currentSize.height);
  74625. if (maxDimension > _this.maximumSize) {
  74626. texture.scale(0.5);
  74627. allDone = false;
  74628. }
  74629. }
  74630. return allDone;
  74631. };
  74632. return _this;
  74633. }
  74634. return TextureOptimization;
  74635. }(SceneOptimization));
  74636. BABYLON.TextureOptimization = TextureOptimization;
  74637. var HardwareScalingOptimization = /** @class */ (function (_super) {
  74638. __extends(HardwareScalingOptimization, _super);
  74639. function HardwareScalingOptimization(priority, maximumScale) {
  74640. if (priority === void 0) { priority = 0; }
  74641. if (maximumScale === void 0) { maximumScale = 2; }
  74642. var _this = _super.call(this, priority) || this;
  74643. _this.priority = priority;
  74644. _this.maximumScale = maximumScale;
  74645. _this._currentScale = 1;
  74646. _this.apply = function (scene) {
  74647. _this._currentScale++;
  74648. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  74649. return _this._currentScale >= _this.maximumScale;
  74650. };
  74651. return _this;
  74652. }
  74653. return HardwareScalingOptimization;
  74654. }(SceneOptimization));
  74655. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  74656. var ShadowsOptimization = /** @class */ (function (_super) {
  74657. __extends(ShadowsOptimization, _super);
  74658. function ShadowsOptimization() {
  74659. var _this = _super !== null && _super.apply(this, arguments) || this;
  74660. _this.apply = function (scene) {
  74661. scene.shadowsEnabled = false;
  74662. return true;
  74663. };
  74664. return _this;
  74665. }
  74666. return ShadowsOptimization;
  74667. }(SceneOptimization));
  74668. BABYLON.ShadowsOptimization = ShadowsOptimization;
  74669. var PostProcessesOptimization = /** @class */ (function (_super) {
  74670. __extends(PostProcessesOptimization, _super);
  74671. function PostProcessesOptimization() {
  74672. var _this = _super !== null && _super.apply(this, arguments) || this;
  74673. _this.apply = function (scene) {
  74674. scene.postProcessesEnabled = false;
  74675. return true;
  74676. };
  74677. return _this;
  74678. }
  74679. return PostProcessesOptimization;
  74680. }(SceneOptimization));
  74681. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  74682. var LensFlaresOptimization = /** @class */ (function (_super) {
  74683. __extends(LensFlaresOptimization, _super);
  74684. function LensFlaresOptimization() {
  74685. var _this = _super !== null && _super.apply(this, arguments) || this;
  74686. _this.apply = function (scene) {
  74687. scene.lensFlaresEnabled = false;
  74688. return true;
  74689. };
  74690. return _this;
  74691. }
  74692. return LensFlaresOptimization;
  74693. }(SceneOptimization));
  74694. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  74695. var ParticlesOptimization = /** @class */ (function (_super) {
  74696. __extends(ParticlesOptimization, _super);
  74697. function ParticlesOptimization() {
  74698. var _this = _super !== null && _super.apply(this, arguments) || this;
  74699. _this.apply = function (scene) {
  74700. scene.particlesEnabled = false;
  74701. return true;
  74702. };
  74703. return _this;
  74704. }
  74705. return ParticlesOptimization;
  74706. }(SceneOptimization));
  74707. BABYLON.ParticlesOptimization = ParticlesOptimization;
  74708. var RenderTargetsOptimization = /** @class */ (function (_super) {
  74709. __extends(RenderTargetsOptimization, _super);
  74710. function RenderTargetsOptimization() {
  74711. var _this = _super !== null && _super.apply(this, arguments) || this;
  74712. _this.apply = function (scene) {
  74713. scene.renderTargetsEnabled = false;
  74714. return true;
  74715. };
  74716. return _this;
  74717. }
  74718. return RenderTargetsOptimization;
  74719. }(SceneOptimization));
  74720. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  74721. var MergeMeshesOptimization = /** @class */ (function (_super) {
  74722. __extends(MergeMeshesOptimization, _super);
  74723. function MergeMeshesOptimization() {
  74724. var _this = _super !== null && _super.apply(this, arguments) || this;
  74725. _this._canBeMerged = function (abstractMesh) {
  74726. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  74727. return false;
  74728. }
  74729. var mesh = abstractMesh;
  74730. if (!mesh.isVisible || !mesh.isEnabled()) {
  74731. return false;
  74732. }
  74733. if (mesh.instances.length > 0) {
  74734. return false;
  74735. }
  74736. if (mesh.skeleton || mesh.hasLODLevels) {
  74737. return false;
  74738. }
  74739. if (mesh.parent) {
  74740. return false;
  74741. }
  74742. return true;
  74743. };
  74744. _this.apply = function (scene, updateSelectionTree) {
  74745. var globalPool = scene.meshes.slice(0);
  74746. var globalLength = globalPool.length;
  74747. for (var index = 0; index < globalLength; index++) {
  74748. var currentPool = new Array();
  74749. var current = globalPool[index];
  74750. // Checks
  74751. if (!_this._canBeMerged(current)) {
  74752. continue;
  74753. }
  74754. currentPool.push(current);
  74755. // Find compatible meshes
  74756. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  74757. var otherMesh = globalPool[subIndex];
  74758. if (!_this._canBeMerged(otherMesh)) {
  74759. continue;
  74760. }
  74761. if (otherMesh.material !== current.material) {
  74762. continue;
  74763. }
  74764. if (otherMesh.checkCollisions !== current.checkCollisions) {
  74765. continue;
  74766. }
  74767. currentPool.push(otherMesh);
  74768. globalLength--;
  74769. globalPool.splice(subIndex, 1);
  74770. subIndex--;
  74771. }
  74772. if (currentPool.length < 2) {
  74773. continue;
  74774. }
  74775. // Merge meshes
  74776. BABYLON.Mesh.MergeMeshes(currentPool);
  74777. }
  74778. if (updateSelectionTree != undefined) {
  74779. if (updateSelectionTree) {
  74780. scene.createOrUpdateSelectionOctree();
  74781. }
  74782. }
  74783. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  74784. scene.createOrUpdateSelectionOctree();
  74785. }
  74786. return true;
  74787. };
  74788. return _this;
  74789. }
  74790. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  74791. get: function () {
  74792. return MergeMeshesOptimization._UpdateSelectionTree;
  74793. },
  74794. set: function (value) {
  74795. MergeMeshesOptimization._UpdateSelectionTree = value;
  74796. },
  74797. enumerable: true,
  74798. configurable: true
  74799. });
  74800. MergeMeshesOptimization._UpdateSelectionTree = false;
  74801. return MergeMeshesOptimization;
  74802. }(SceneOptimization));
  74803. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  74804. // Options
  74805. var SceneOptimizerOptions = /** @class */ (function () {
  74806. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  74807. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  74808. if (trackerDuration === void 0) { trackerDuration = 2000; }
  74809. this.targetFrameRate = targetFrameRate;
  74810. this.trackerDuration = trackerDuration;
  74811. this.optimizations = new Array();
  74812. }
  74813. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  74814. var result = new SceneOptimizerOptions(targetFrameRate);
  74815. var priority = 0;
  74816. result.optimizations.push(new MergeMeshesOptimization(priority));
  74817. result.optimizations.push(new ShadowsOptimization(priority));
  74818. result.optimizations.push(new LensFlaresOptimization(priority));
  74819. // Next priority
  74820. priority++;
  74821. result.optimizations.push(new PostProcessesOptimization(priority));
  74822. result.optimizations.push(new ParticlesOptimization(priority));
  74823. // Next priority
  74824. priority++;
  74825. result.optimizations.push(new TextureOptimization(priority, 1024));
  74826. return result;
  74827. };
  74828. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  74829. var result = new SceneOptimizerOptions(targetFrameRate);
  74830. var priority = 0;
  74831. result.optimizations.push(new MergeMeshesOptimization(priority));
  74832. result.optimizations.push(new ShadowsOptimization(priority));
  74833. result.optimizations.push(new LensFlaresOptimization(priority));
  74834. // Next priority
  74835. priority++;
  74836. result.optimizations.push(new PostProcessesOptimization(priority));
  74837. result.optimizations.push(new ParticlesOptimization(priority));
  74838. // Next priority
  74839. priority++;
  74840. result.optimizations.push(new TextureOptimization(priority, 512));
  74841. // Next priority
  74842. priority++;
  74843. result.optimizations.push(new RenderTargetsOptimization(priority));
  74844. // Next priority
  74845. priority++;
  74846. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  74847. return result;
  74848. };
  74849. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  74850. var result = new SceneOptimizerOptions(targetFrameRate);
  74851. var priority = 0;
  74852. result.optimizations.push(new MergeMeshesOptimization(priority));
  74853. result.optimizations.push(new ShadowsOptimization(priority));
  74854. result.optimizations.push(new LensFlaresOptimization(priority));
  74855. // Next priority
  74856. priority++;
  74857. result.optimizations.push(new PostProcessesOptimization(priority));
  74858. result.optimizations.push(new ParticlesOptimization(priority));
  74859. // Next priority
  74860. priority++;
  74861. result.optimizations.push(new TextureOptimization(priority, 256));
  74862. // Next priority
  74863. priority++;
  74864. result.optimizations.push(new RenderTargetsOptimization(priority));
  74865. // Next priority
  74866. priority++;
  74867. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  74868. return result;
  74869. };
  74870. return SceneOptimizerOptions;
  74871. }());
  74872. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  74873. // Scene optimizer tool
  74874. var SceneOptimizer = /** @class */ (function () {
  74875. function SceneOptimizer() {
  74876. }
  74877. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  74878. // TODO: add an epsilon
  74879. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  74880. if (onSuccess) {
  74881. onSuccess();
  74882. }
  74883. return;
  74884. }
  74885. // Apply current level of optimizations
  74886. var allDone = true;
  74887. var noOptimizationApplied = true;
  74888. for (var index = 0; index < options.optimizations.length; index++) {
  74889. var optimization = options.optimizations[index];
  74890. if (optimization.priority === currentPriorityLevel) {
  74891. noOptimizationApplied = false;
  74892. allDone = allDone && optimization.apply(scene);
  74893. }
  74894. }
  74895. // If no optimization was applied, this is a failure :(
  74896. if (noOptimizationApplied) {
  74897. if (onFailure) {
  74898. onFailure();
  74899. }
  74900. return;
  74901. }
  74902. // If all optimizations were done, move to next level
  74903. if (allDone) {
  74904. currentPriorityLevel++;
  74905. }
  74906. // Let's the system running for a specific amount of time before checking FPS
  74907. scene.executeWhenReady(function () {
  74908. setTimeout(function () {
  74909. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  74910. }, options.trackerDuration);
  74911. });
  74912. };
  74913. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  74914. if (!options) {
  74915. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  74916. }
  74917. // Let's the system running for a specific amount of time before checking FPS
  74918. scene.executeWhenReady(function () {
  74919. setTimeout(function () {
  74920. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  74921. }, options.trackerDuration);
  74922. });
  74923. };
  74924. return SceneOptimizer;
  74925. }());
  74926. BABYLON.SceneOptimizer = SceneOptimizer;
  74927. })(BABYLON || (BABYLON = {}));
  74928. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  74929. var BABYLON;
  74930. (function (BABYLON) {
  74931. var OutlineRenderer = /** @class */ (function () {
  74932. function OutlineRenderer(scene) {
  74933. this.zOffset = 1;
  74934. this._scene = scene;
  74935. }
  74936. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  74937. var _this = this;
  74938. if (useOverlay === void 0) { useOverlay = false; }
  74939. var scene = this._scene;
  74940. var engine = this._scene.getEngine();
  74941. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  74942. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  74943. return;
  74944. }
  74945. var mesh = subMesh.getRenderingMesh();
  74946. var material = subMesh.getMaterial();
  74947. if (!material || !scene.activeCamera) {
  74948. return;
  74949. }
  74950. engine.enableEffect(this._effect);
  74951. // Logarithmic depth
  74952. if (material.useLogarithmicDepth) {
  74953. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  74954. }
  74955. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  74956. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  74957. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  74958. // Bones
  74959. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  74960. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  74961. }
  74962. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  74963. // Alpha test
  74964. if (material && material.needAlphaTesting()) {
  74965. var alphaTexture = material.getAlphaTestTexture();
  74966. if (alphaTexture) {
  74967. this._effect.setTexture("diffuseSampler", alphaTexture);
  74968. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  74969. }
  74970. }
  74971. engine.setZOffset(-this.zOffset);
  74972. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  74973. engine.setZOffset(0);
  74974. };
  74975. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  74976. var defines = [];
  74977. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  74978. var mesh = subMesh.getMesh();
  74979. var material = subMesh.getMaterial();
  74980. if (material) {
  74981. // Alpha test
  74982. if (material.needAlphaTesting()) {
  74983. defines.push("#define ALPHATEST");
  74984. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  74985. attribs.push(BABYLON.VertexBuffer.UVKind);
  74986. defines.push("#define UV1");
  74987. }
  74988. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  74989. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  74990. defines.push("#define UV2");
  74991. }
  74992. }
  74993. //Logarithmic depth
  74994. if (material.useLogarithmicDepth) {
  74995. defines.push("#define LOGARITHMICDEPTH");
  74996. }
  74997. }
  74998. // Bones
  74999. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75000. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  75001. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  75002. if (mesh.numBoneInfluencers > 4) {
  75003. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  75004. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  75005. }
  75006. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  75007. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  75008. }
  75009. else {
  75010. defines.push("#define NUM_BONE_INFLUENCERS 0");
  75011. }
  75012. // Instances
  75013. if (useInstances) {
  75014. defines.push("#define INSTANCES");
  75015. attribs.push("world0");
  75016. attribs.push("world1");
  75017. attribs.push("world2");
  75018. attribs.push("world3");
  75019. }
  75020. // Get correct effect
  75021. var join = defines.join("\n");
  75022. if (this._cachedDefines !== join) {
  75023. this._cachedDefines = join;
  75024. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  75025. }
  75026. return this._effect.isReady();
  75027. };
  75028. return OutlineRenderer;
  75029. }());
  75030. BABYLON.OutlineRenderer = OutlineRenderer;
  75031. })(BABYLON || (BABYLON = {}));
  75032. //# sourceMappingURL=babylon.outlineRenderer.js.map
  75033. var BABYLON;
  75034. (function (BABYLON) {
  75035. var FaceAdjacencies = /** @class */ (function () {
  75036. function FaceAdjacencies() {
  75037. this.edges = new Array();
  75038. this.edgesConnectedCount = 0;
  75039. }
  75040. return FaceAdjacencies;
  75041. }());
  75042. var EdgesRenderer = /** @class */ (function () {
  75043. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  75044. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  75045. if (epsilon === void 0) { epsilon = 0.95; }
  75046. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  75047. this.edgesWidthScalerForOrthographic = 1000.0;
  75048. this.edgesWidthScalerForPerspective = 50.0;
  75049. this._linesPositions = new Array();
  75050. this._linesNormals = new Array();
  75051. this._linesIndices = new Array();
  75052. this._buffers = {};
  75053. this._checkVerticesInsteadOfIndices = false;
  75054. this._source = source;
  75055. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  75056. this._epsilon = epsilon;
  75057. this._prepareRessources();
  75058. this._generateEdgesLines();
  75059. }
  75060. EdgesRenderer.prototype._prepareRessources = function () {
  75061. if (this._lineShader) {
  75062. return;
  75063. }
  75064. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  75065. attributes: ["position", "normal"],
  75066. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  75067. });
  75068. this._lineShader.disableDepthWrite = true;
  75069. this._lineShader.backFaceCulling = false;
  75070. };
  75071. EdgesRenderer.prototype._rebuild = function () {
  75072. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  75073. if (buffer) {
  75074. buffer._rebuild();
  75075. }
  75076. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  75077. if (buffer) {
  75078. buffer._rebuild();
  75079. }
  75080. var scene = this._source.getScene();
  75081. var engine = scene.getEngine();
  75082. this._ib = engine.createIndexBuffer(this._linesIndices);
  75083. };
  75084. EdgesRenderer.prototype.dispose = function () {
  75085. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  75086. if (buffer) {
  75087. buffer.dispose();
  75088. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  75089. }
  75090. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  75091. if (buffer) {
  75092. buffer.dispose();
  75093. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  75094. }
  75095. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  75096. this._lineShader.dispose();
  75097. };
  75098. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  75099. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  75100. return 0;
  75101. }
  75102. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  75103. return 1;
  75104. }
  75105. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  75106. return 2;
  75107. }
  75108. return -1;
  75109. };
  75110. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  75111. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  75112. return 0;
  75113. }
  75114. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  75115. return 1;
  75116. }
  75117. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  75118. return 2;
  75119. }
  75120. return -1;
  75121. };
  75122. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  75123. var needToCreateLine;
  75124. if (edge === undefined) {
  75125. needToCreateLine = true;
  75126. }
  75127. else {
  75128. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  75129. needToCreateLine = dotProduct < this._epsilon;
  75130. }
  75131. if (needToCreateLine) {
  75132. var offset = this._linesPositions.length / 3;
  75133. var normal = p0.subtract(p1);
  75134. normal.normalize();
  75135. // Positions
  75136. this._linesPositions.push(p0.x);
  75137. this._linesPositions.push(p0.y);
  75138. this._linesPositions.push(p0.z);
  75139. this._linesPositions.push(p0.x);
  75140. this._linesPositions.push(p0.y);
  75141. this._linesPositions.push(p0.z);
  75142. this._linesPositions.push(p1.x);
  75143. this._linesPositions.push(p1.y);
  75144. this._linesPositions.push(p1.z);
  75145. this._linesPositions.push(p1.x);
  75146. this._linesPositions.push(p1.y);
  75147. this._linesPositions.push(p1.z);
  75148. // Normals
  75149. this._linesNormals.push(p1.x);
  75150. this._linesNormals.push(p1.y);
  75151. this._linesNormals.push(p1.z);
  75152. this._linesNormals.push(-1);
  75153. this._linesNormals.push(p1.x);
  75154. this._linesNormals.push(p1.y);
  75155. this._linesNormals.push(p1.z);
  75156. this._linesNormals.push(1);
  75157. this._linesNormals.push(p0.x);
  75158. this._linesNormals.push(p0.y);
  75159. this._linesNormals.push(p0.z);
  75160. this._linesNormals.push(-1);
  75161. this._linesNormals.push(p0.x);
  75162. this._linesNormals.push(p0.y);
  75163. this._linesNormals.push(p0.z);
  75164. this._linesNormals.push(1);
  75165. // Indices
  75166. this._linesIndices.push(offset);
  75167. this._linesIndices.push(offset + 1);
  75168. this._linesIndices.push(offset + 2);
  75169. this._linesIndices.push(offset);
  75170. this._linesIndices.push(offset + 2);
  75171. this._linesIndices.push(offset + 3);
  75172. }
  75173. };
  75174. EdgesRenderer.prototype._generateEdgesLines = function () {
  75175. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  75176. var indices = this._source.getIndices();
  75177. if (!indices || !positions) {
  75178. return;
  75179. }
  75180. // First let's find adjacencies
  75181. var adjacencies = new Array();
  75182. var faceNormals = new Array();
  75183. var index;
  75184. var faceAdjacencies;
  75185. // Prepare faces
  75186. for (index = 0; index < indices.length; index += 3) {
  75187. faceAdjacencies = new FaceAdjacencies();
  75188. var p0Index = indices[index];
  75189. var p1Index = indices[index + 1];
  75190. var p2Index = indices[index + 2];
  75191. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  75192. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  75193. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  75194. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  75195. faceNormal.normalize();
  75196. faceNormals.push(faceNormal);
  75197. adjacencies.push(faceAdjacencies);
  75198. }
  75199. // Scan
  75200. for (index = 0; index < adjacencies.length; index++) {
  75201. faceAdjacencies = adjacencies[index];
  75202. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  75203. var otherFaceAdjacencies = adjacencies[otherIndex];
  75204. if (faceAdjacencies.edgesConnectedCount === 3) {
  75205. break;
  75206. }
  75207. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  75208. continue;
  75209. }
  75210. var otherP0 = indices[otherIndex * 3];
  75211. var otherP1 = indices[otherIndex * 3 + 1];
  75212. var otherP2 = indices[otherIndex * 3 + 2];
  75213. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  75214. var otherEdgeIndex = 0;
  75215. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  75216. continue;
  75217. }
  75218. switch (edgeIndex) {
  75219. case 0:
  75220. if (this._checkVerticesInsteadOfIndices) {
  75221. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  75222. }
  75223. else {
  75224. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  75225. }
  75226. break;
  75227. case 1:
  75228. if (this._checkVerticesInsteadOfIndices) {
  75229. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  75230. }
  75231. else {
  75232. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  75233. }
  75234. break;
  75235. case 2:
  75236. if (this._checkVerticesInsteadOfIndices) {
  75237. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  75238. }
  75239. else {
  75240. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  75241. }
  75242. break;
  75243. }
  75244. if (otherEdgeIndex === -1) {
  75245. continue;
  75246. }
  75247. faceAdjacencies.edges[edgeIndex] = otherIndex;
  75248. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  75249. faceAdjacencies.edgesConnectedCount++;
  75250. otherFaceAdjacencies.edgesConnectedCount++;
  75251. if (faceAdjacencies.edgesConnectedCount === 3) {
  75252. break;
  75253. }
  75254. }
  75255. }
  75256. }
  75257. // Create lines
  75258. for (index = 0; index < adjacencies.length; index++) {
  75259. // 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
  75260. var current = adjacencies[index];
  75261. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  75262. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  75263. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  75264. }
  75265. // Merge into a single mesh
  75266. var engine = this._source.getScene().getEngine();
  75267. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  75268. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  75269. this._ib = engine.createIndexBuffer(this._linesIndices);
  75270. this._indicesCount = this._linesIndices.length;
  75271. };
  75272. EdgesRenderer.prototype.render = function () {
  75273. var scene = this._source.getScene();
  75274. if (!this._lineShader.isReady() || !scene.activeCamera) {
  75275. return;
  75276. }
  75277. var engine = scene.getEngine();
  75278. this._lineShader._preBind();
  75279. // VBOs
  75280. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  75281. scene.resetCachedMaterial();
  75282. this._lineShader.setColor4("color", this._source.edgesColor);
  75283. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  75284. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  75285. }
  75286. else {
  75287. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  75288. }
  75289. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  75290. this._lineShader.bind(this._source.getWorldMatrix());
  75291. // Draw order
  75292. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  75293. this._lineShader.unbind();
  75294. engine.setDepthWrite(true);
  75295. };
  75296. return EdgesRenderer;
  75297. }());
  75298. BABYLON.EdgesRenderer = EdgesRenderer;
  75299. })(BABYLON || (BABYLON = {}));
  75300. //# sourceMappingURL=babylon.edgesRenderer.js.map
  75301. var BABYLON;
  75302. (function (BABYLON) {
  75303. /**
  75304. * Special Glow Blur post process only blurring the alpha channel
  75305. * It enforces keeping the most luminous color in the color channel.
  75306. */
  75307. var GlowBlurPostProcess = /** @class */ (function (_super) {
  75308. __extends(GlowBlurPostProcess, _super);
  75309. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  75310. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75311. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  75312. _this.direction = direction;
  75313. _this.kernel = kernel;
  75314. _this.onApplyObservable.add(function (effect) {
  75315. effect.setFloat2("screenSize", _this.width, _this.height);
  75316. effect.setVector2("direction", _this.direction);
  75317. effect.setFloat("blurWidth", _this.kernel);
  75318. });
  75319. return _this;
  75320. }
  75321. return GlowBlurPostProcess;
  75322. }(BABYLON.PostProcess));
  75323. /**
  75324. * The highlight layer Helps adding a glow effect around a mesh.
  75325. *
  75326. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  75327. * glowy meshes to your scene.
  75328. *
  75329. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  75330. */
  75331. var HighlightLayer = /** @class */ (function () {
  75332. /**
  75333. * Instantiates a new highlight Layer and references it to the scene..
  75334. * @param name The name of the layer
  75335. * @param scene The scene to use the layer in
  75336. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  75337. */
  75338. function HighlightLayer(name, scene, options) {
  75339. this.name = name;
  75340. this._vertexBuffers = {};
  75341. this._mainTextureDesiredSize = { width: 0, height: 0 };
  75342. this._meshes = {};
  75343. this._maxSize = 0;
  75344. this._shouldRender = false;
  75345. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  75346. this._excludedMeshes = {};
  75347. /**
  75348. * Specifies whether or not the inner glow is ACTIVE in the layer.
  75349. */
  75350. this.innerGlow = true;
  75351. /**
  75352. * Specifies whether or not the outer glow is ACTIVE in the layer.
  75353. */
  75354. this.outerGlow = true;
  75355. /**
  75356. * Specifies wether the highlight layer is enabled or not.
  75357. */
  75358. this.isEnabled = true;
  75359. /**
  75360. * An event triggered when the highlight layer has been disposed.
  75361. * @type {BABYLON.Observable}
  75362. */
  75363. this.onDisposeObservable = new BABYLON.Observable();
  75364. /**
  75365. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  75366. * @type {BABYLON.Observable}
  75367. */
  75368. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  75369. /**
  75370. * An event triggered when the highlight layer is being blurred.
  75371. * @type {BABYLON.Observable}
  75372. */
  75373. this.onBeforeBlurObservable = new BABYLON.Observable();
  75374. /**
  75375. * An event triggered when the highlight layer has been blurred.
  75376. * @type {BABYLON.Observable}
  75377. */
  75378. this.onAfterBlurObservable = new BABYLON.Observable();
  75379. /**
  75380. * An event triggered when the glowing blurred texture is being merged in the scene.
  75381. * @type {BABYLON.Observable}
  75382. */
  75383. this.onBeforeComposeObservable = new BABYLON.Observable();
  75384. /**
  75385. * An event triggered when the glowing blurred texture has been merged in the scene.
  75386. * @type {BABYLON.Observable}
  75387. */
  75388. this.onAfterComposeObservable = new BABYLON.Observable();
  75389. /**
  75390. * An event triggered when the highlight layer changes its size.
  75391. * @type {BABYLON.Observable}
  75392. */
  75393. this.onSizeChangedObservable = new BABYLON.Observable();
  75394. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  75395. var engine = scene.getEngine();
  75396. this._engine = engine;
  75397. this._maxSize = this._engine.getCaps().maxTextureSize;
  75398. this._scene.highlightLayers.push(this);
  75399. // Warn on stencil.
  75400. if (!this._engine.isStencilEnable) {
  75401. 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 }");
  75402. }
  75403. // Adapt options
  75404. this._options = options || {
  75405. mainTextureRatio: 0.5,
  75406. blurTextureSizeRatio: 0.5,
  75407. blurHorizontalSize: 1.0,
  75408. blurVerticalSize: 1.0,
  75409. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  75410. camera: null
  75411. };
  75412. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  75413. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  75414. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  75415. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  75416. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  75417. // VBO
  75418. var vertices = [];
  75419. vertices.push(1, 1);
  75420. vertices.push(-1, 1);
  75421. vertices.push(-1, -1);
  75422. vertices.push(1, -1);
  75423. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  75424. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  75425. this._createIndexBuffer();
  75426. // Effect
  75427. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  75428. // Render target
  75429. this.setMainTextureSize();
  75430. // Create Textures and post processes
  75431. this.createTextureAndPostProcesses();
  75432. }
  75433. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  75434. /**
  75435. * Gets the horizontal size of the blur.
  75436. */
  75437. get: function () {
  75438. return this._horizontalBlurPostprocess.kernel;
  75439. },
  75440. /**
  75441. * Specifies the horizontal size of the blur.
  75442. */
  75443. set: function (value) {
  75444. this._horizontalBlurPostprocess.kernel = value;
  75445. },
  75446. enumerable: true,
  75447. configurable: true
  75448. });
  75449. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  75450. /**
  75451. * Gets the vertical size of the blur.
  75452. */
  75453. get: function () {
  75454. return this._verticalBlurPostprocess.kernel;
  75455. },
  75456. /**
  75457. * Specifies the vertical size of the blur.
  75458. */
  75459. set: function (value) {
  75460. this._verticalBlurPostprocess.kernel = value;
  75461. },
  75462. enumerable: true,
  75463. configurable: true
  75464. });
  75465. Object.defineProperty(HighlightLayer.prototype, "camera", {
  75466. /**
  75467. * Gets the camera attached to the layer.
  75468. */
  75469. get: function () {
  75470. return this._options.camera;
  75471. },
  75472. enumerable: true,
  75473. configurable: true
  75474. });
  75475. HighlightLayer.prototype._createIndexBuffer = function () {
  75476. var engine = this._scene.getEngine();
  75477. // Indices
  75478. var indices = [];
  75479. indices.push(0);
  75480. indices.push(1);
  75481. indices.push(2);
  75482. indices.push(0);
  75483. indices.push(2);
  75484. indices.push(3);
  75485. this._indexBuffer = engine.createIndexBuffer(indices);
  75486. };
  75487. HighlightLayer.prototype._rebuild = function () {
  75488. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75489. if (vb) {
  75490. vb._rebuild();
  75491. }
  75492. this._createIndexBuffer();
  75493. };
  75494. /**
  75495. * Creates the render target textures and post processes used in the highlight layer.
  75496. */
  75497. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  75498. var _this = this;
  75499. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  75500. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  75501. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  75502. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  75503. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  75504. width: this._mainTextureDesiredSize.width,
  75505. height: this._mainTextureDesiredSize.height
  75506. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  75507. this._mainTexture.activeCamera = this._options.camera;
  75508. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75509. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75510. this._mainTexture.anisotropicFilteringLevel = 1;
  75511. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  75512. this._mainTexture.renderParticles = false;
  75513. this._mainTexture.renderList = null;
  75514. this._mainTexture.ignoreCameraViewport = true;
  75515. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  75516. width: blurTextureWidth,
  75517. height: blurTextureHeight
  75518. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  75519. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75520. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75521. this._blurTexture.anisotropicFilteringLevel = 16;
  75522. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  75523. this._blurTexture.renderParticles = false;
  75524. this._blurTexture.ignoreCameraViewport = true;
  75525. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  75526. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  75527. effect.setTexture("textureSampler", _this._mainTexture);
  75528. });
  75529. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  75530. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  75531. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  75532. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  75533. });
  75534. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  75535. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  75536. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  75537. });
  75538. }
  75539. else {
  75540. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  75541. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  75542. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  75543. });
  75544. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  75545. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  75546. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  75547. });
  75548. }
  75549. this._mainTexture.onAfterUnbindObservable.add(function () {
  75550. _this.onBeforeBlurObservable.notifyObservers(_this);
  75551. var internalTexture = _this._blurTexture.getInternalTexture();
  75552. if (internalTexture) {
  75553. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  75554. }
  75555. _this.onAfterBlurObservable.notifyObservers(_this);
  75556. });
  75557. // Custom render function
  75558. var renderSubMesh = function (subMesh) {
  75559. if (!_this._meshes) {
  75560. return;
  75561. }
  75562. var material = subMesh.getMaterial();
  75563. var mesh = subMesh.getRenderingMesh();
  75564. var scene = _this._scene;
  75565. var engine = scene.getEngine();
  75566. if (!material) {
  75567. return;
  75568. }
  75569. // Do not block in blend mode.
  75570. if (material.needAlphaBlendingForMesh(mesh)) {
  75571. return;
  75572. }
  75573. // Culling
  75574. engine.setState(material.backFaceCulling);
  75575. // Managing instances
  75576. var batch = mesh._getInstancesRenderList(subMesh._id);
  75577. if (batch.mustReturn) {
  75578. return;
  75579. }
  75580. // Excluded Mesh
  75581. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  75582. return;
  75583. }
  75584. ;
  75585. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  75586. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  75587. var emissiveTexture = null;
  75588. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  75589. emissiveTexture = material.emissiveTexture;
  75590. }
  75591. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  75592. engine.enableEffect(_this._glowMapGenerationEffect);
  75593. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  75594. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  75595. if (highlightLayerMesh) {
  75596. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  75597. }
  75598. else {
  75599. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  75600. }
  75601. // Alpha test
  75602. if (material && material.needAlphaTesting()) {
  75603. var alphaTexture = material.getAlphaTestTexture();
  75604. if (alphaTexture) {
  75605. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  75606. var textureMatrix = alphaTexture.getTextureMatrix();
  75607. if (textureMatrix) {
  75608. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  75609. }
  75610. }
  75611. }
  75612. // Glow emissive only
  75613. if (emissiveTexture) {
  75614. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  75615. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  75616. }
  75617. // Bones
  75618. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  75619. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  75620. }
  75621. // Draw
  75622. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  75623. }
  75624. else {
  75625. // Need to reset refresh rate of the shadowMap
  75626. _this._mainTexture.resetRefreshCounter();
  75627. }
  75628. };
  75629. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  75630. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  75631. var index;
  75632. var engine = _this._scene.getEngine();
  75633. if (depthOnlySubMeshes.length) {
  75634. engine.setColorWrite(false);
  75635. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  75636. renderSubMesh(depthOnlySubMeshes.data[index]);
  75637. }
  75638. engine.setColorWrite(true);
  75639. }
  75640. for (index = 0; index < opaqueSubMeshes.length; index++) {
  75641. renderSubMesh(opaqueSubMeshes.data[index]);
  75642. }
  75643. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  75644. renderSubMesh(alphaTestSubMeshes.data[index]);
  75645. }
  75646. for (index = 0; index < transparentSubMeshes.length; index++) {
  75647. renderSubMesh(transparentSubMeshes.data[index]);
  75648. }
  75649. };
  75650. this._mainTexture.onClearObservable.add(function (engine) {
  75651. engine.clear(HighlightLayer.neutralColor, true, true, true);
  75652. });
  75653. };
  75654. /**
  75655. * Checks for the readiness of the element composing the layer.
  75656. * @param subMesh the mesh to check for
  75657. * @param useInstances specify wether or not to use instances to render the mesh
  75658. * @param emissiveTexture the associated emissive texture used to generate the glow
  75659. * @return true if ready otherwise, false
  75660. */
  75661. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  75662. var material = subMesh.getMaterial();
  75663. if (!material) {
  75664. return false;
  75665. }
  75666. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  75667. return false;
  75668. }
  75669. var defines = [];
  75670. var attribs = [BABYLON.VertexBuffer.PositionKind];
  75671. var mesh = subMesh.getMesh();
  75672. var uv1 = false;
  75673. var uv2 = false;
  75674. // Alpha test
  75675. if (material && material.needAlphaTesting()) {
  75676. var alphaTexture = material.getAlphaTestTexture();
  75677. if (alphaTexture) {
  75678. defines.push("#define ALPHATEST");
  75679. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  75680. alphaTexture.coordinatesIndex === 1) {
  75681. defines.push("#define DIFFUSEUV2");
  75682. uv2 = true;
  75683. }
  75684. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  75685. defines.push("#define DIFFUSEUV1");
  75686. uv1 = true;
  75687. }
  75688. }
  75689. }
  75690. // Emissive
  75691. if (emissiveTexture) {
  75692. defines.push("#define EMISSIVE");
  75693. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  75694. emissiveTexture.coordinatesIndex === 1) {
  75695. defines.push("#define EMISSIVEUV2");
  75696. uv2 = true;
  75697. }
  75698. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  75699. defines.push("#define EMISSIVEUV1");
  75700. uv1 = true;
  75701. }
  75702. }
  75703. if (uv1) {
  75704. attribs.push(BABYLON.VertexBuffer.UVKind);
  75705. defines.push("#define UV1");
  75706. }
  75707. if (uv2) {
  75708. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75709. defines.push("#define UV2");
  75710. }
  75711. // Bones
  75712. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75713. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  75714. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  75715. if (mesh.numBoneInfluencers > 4) {
  75716. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  75717. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  75718. }
  75719. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  75720. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  75721. }
  75722. else {
  75723. defines.push("#define NUM_BONE_INFLUENCERS 0");
  75724. }
  75725. // Instances
  75726. if (useInstances) {
  75727. defines.push("#define INSTANCES");
  75728. attribs.push("world0");
  75729. attribs.push("world1");
  75730. attribs.push("world2");
  75731. attribs.push("world3");
  75732. }
  75733. // Get correct effect
  75734. var join = defines.join("\n");
  75735. if (this._cachedDefines !== join) {
  75736. this._cachedDefines = join;
  75737. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  75738. }
  75739. return this._glowMapGenerationEffect.isReady();
  75740. };
  75741. /**
  75742. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  75743. */
  75744. HighlightLayer.prototype.render = function () {
  75745. var currentEffect = this._glowMapMergeEffect;
  75746. // Check
  75747. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  75748. return;
  75749. var engine = this._scene.getEngine();
  75750. this.onBeforeComposeObservable.notifyObservers(this);
  75751. // Render
  75752. engine.enableEffect(currentEffect);
  75753. engine.setState(false);
  75754. // Cache
  75755. var previousStencilBuffer = engine.getStencilBuffer();
  75756. var previousStencilFunction = engine.getStencilFunction();
  75757. var previousStencilMask = engine.getStencilMask();
  75758. var previousStencilOperationPass = engine.getStencilOperationPass();
  75759. var previousStencilOperationFail = engine.getStencilOperationFail();
  75760. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  75761. var previousAlphaMode = engine.getAlphaMode();
  75762. // Texture
  75763. currentEffect.setTexture("textureSampler", this._blurTexture);
  75764. // VBOs
  75765. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  75766. // Stencil operations
  75767. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  75768. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  75769. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  75770. // Draw order
  75771. engine.setAlphaMode(this._options.alphaBlendingMode);
  75772. engine.setStencilMask(0x00);
  75773. engine.setStencilBuffer(true);
  75774. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  75775. if (this.outerGlow) {
  75776. currentEffect.setFloat("offset", 0);
  75777. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  75778. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  75779. }
  75780. if (this.innerGlow) {
  75781. currentEffect.setFloat("offset", 1);
  75782. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  75783. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  75784. }
  75785. // Restore Cache
  75786. engine.setStencilFunction(previousStencilFunction);
  75787. engine.setStencilMask(previousStencilMask);
  75788. engine.setAlphaMode(previousAlphaMode);
  75789. engine.setStencilBuffer(previousStencilBuffer);
  75790. engine.setStencilOperationPass(previousStencilOperationPass);
  75791. engine.setStencilOperationFail(previousStencilOperationFail);
  75792. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  75793. engine._stencilState.reset();
  75794. this.onAfterComposeObservable.notifyObservers(this);
  75795. // Handle size changes.
  75796. var size = this._mainTexture.getSize();
  75797. this.setMainTextureSize();
  75798. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  75799. // Recreate RTT and post processes on size change.
  75800. this.onSizeChangedObservable.notifyObservers(this);
  75801. this.disposeTextureAndPostProcesses();
  75802. this.createTextureAndPostProcesses();
  75803. }
  75804. };
  75805. /**
  75806. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  75807. * @param mesh The mesh to exclude from the highlight layer
  75808. */
  75809. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  75810. if (!this._excludedMeshes) {
  75811. return;
  75812. }
  75813. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  75814. if (!meshExcluded) {
  75815. this._excludedMeshes[mesh.uniqueId] = {
  75816. mesh: mesh,
  75817. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  75818. mesh.getEngine().setStencilBuffer(false);
  75819. }),
  75820. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  75821. mesh.getEngine().setStencilBuffer(true);
  75822. }),
  75823. };
  75824. }
  75825. };
  75826. /**
  75827. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  75828. * @param mesh The mesh to highlight
  75829. */
  75830. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  75831. if (!this._excludedMeshes) {
  75832. return;
  75833. }
  75834. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  75835. if (meshExcluded) {
  75836. if (meshExcluded.beforeRender) {
  75837. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  75838. }
  75839. if (meshExcluded.afterRender) {
  75840. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  75841. }
  75842. }
  75843. this._excludedMeshes[mesh.uniqueId] = null;
  75844. };
  75845. /**
  75846. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  75847. * @param mesh The mesh to highlight
  75848. * @param color The color of the highlight
  75849. * @param glowEmissiveOnly Extract the glow from the emissive texture
  75850. */
  75851. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  75852. var _this = this;
  75853. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  75854. if (!this._meshes) {
  75855. return;
  75856. }
  75857. var meshHighlight = this._meshes[mesh.uniqueId];
  75858. if (meshHighlight) {
  75859. meshHighlight.color = color;
  75860. }
  75861. else {
  75862. this._meshes[mesh.uniqueId] = {
  75863. mesh: mesh,
  75864. color: color,
  75865. // Lambda required for capture due to Observable this context
  75866. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  75867. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  75868. _this.defaultStencilReference(mesh);
  75869. }
  75870. else {
  75871. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  75872. }
  75873. }),
  75874. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  75875. glowEmissiveOnly: glowEmissiveOnly
  75876. };
  75877. }
  75878. this._shouldRender = true;
  75879. };
  75880. /**
  75881. * Remove a mesh from the highlight layer in order to make it stop glowing.
  75882. * @param mesh The mesh to highlight
  75883. */
  75884. HighlightLayer.prototype.removeMesh = function (mesh) {
  75885. if (!this._meshes) {
  75886. return;
  75887. }
  75888. var meshHighlight = this._meshes[mesh.uniqueId];
  75889. if (meshHighlight) {
  75890. if (meshHighlight.observerHighlight) {
  75891. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  75892. }
  75893. if (meshHighlight.observerDefault) {
  75894. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  75895. }
  75896. delete this._meshes[mesh.uniqueId];
  75897. }
  75898. this._shouldRender = false;
  75899. for (var meshHighlightToCheck in this._meshes) {
  75900. if (this._meshes[meshHighlightToCheck]) {
  75901. this._shouldRender = true;
  75902. break;
  75903. }
  75904. }
  75905. };
  75906. /**
  75907. * Returns true if the layer contains information to display, otherwise false.
  75908. */
  75909. HighlightLayer.prototype.shouldRender = function () {
  75910. return this.isEnabled && this._shouldRender;
  75911. };
  75912. /**
  75913. * Sets the main texture desired size which is the closest power of two
  75914. * of the engine canvas size.
  75915. */
  75916. HighlightLayer.prototype.setMainTextureSize = function () {
  75917. if (this._options.mainTextureFixedSize) {
  75918. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  75919. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  75920. }
  75921. else {
  75922. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  75923. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  75924. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  75925. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  75926. }
  75927. };
  75928. /**
  75929. * Force the stencil to the normal expected value for none glowing parts
  75930. */
  75931. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  75932. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  75933. };
  75934. /**
  75935. * Dispose only the render target textures and post process.
  75936. */
  75937. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  75938. this._blurTexture.dispose();
  75939. this._mainTexture.dispose();
  75940. this._downSamplePostprocess.dispose();
  75941. this._horizontalBlurPostprocess.dispose();
  75942. this._verticalBlurPostprocess.dispose();
  75943. };
  75944. /**
  75945. * Dispose the highlight layer and free resources.
  75946. */
  75947. HighlightLayer.prototype.dispose = function () {
  75948. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75949. if (vertexBuffer) {
  75950. vertexBuffer.dispose();
  75951. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  75952. }
  75953. if (this._indexBuffer) {
  75954. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  75955. this._indexBuffer = null;
  75956. }
  75957. // Clean textures and post processes
  75958. this.disposeTextureAndPostProcesses();
  75959. if (this._meshes) {
  75960. // Clean mesh references
  75961. for (var id in this._meshes) {
  75962. var meshHighlight = this._meshes[id];
  75963. if (meshHighlight && meshHighlight.mesh) {
  75964. if (meshHighlight.observerHighlight) {
  75965. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  75966. }
  75967. if (meshHighlight.observerDefault) {
  75968. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  75969. }
  75970. }
  75971. }
  75972. this._meshes = null;
  75973. }
  75974. if (this._excludedMeshes) {
  75975. for (var id in this._excludedMeshes) {
  75976. var meshHighlight = this._excludedMeshes[id];
  75977. if (meshHighlight) {
  75978. if (meshHighlight.beforeRender) {
  75979. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  75980. }
  75981. if (meshHighlight.afterRender) {
  75982. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  75983. }
  75984. }
  75985. }
  75986. this._excludedMeshes = null;
  75987. }
  75988. // Remove from scene
  75989. var index = this._scene.highlightLayers.indexOf(this, 0);
  75990. if (index > -1) {
  75991. this._scene.highlightLayers.splice(index, 1);
  75992. }
  75993. // Callback
  75994. this.onDisposeObservable.notifyObservers(this);
  75995. this.onDisposeObservable.clear();
  75996. this.onBeforeRenderMainTextureObservable.clear();
  75997. this.onBeforeBlurObservable.clear();
  75998. this.onBeforeComposeObservable.clear();
  75999. this.onAfterComposeObservable.clear();
  76000. this.onSizeChangedObservable.clear();
  76001. };
  76002. /**
  76003. * The neutral color used during the preparation of the glow effect.
  76004. * This is black by default as the blend operation is a blend operation.
  76005. */
  76006. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  76007. /**
  76008. * Stencil value used for glowing meshes.
  76009. */
  76010. HighlightLayer.glowingMeshStencilReference = 0x02;
  76011. /**
  76012. * Stencil value used for the other meshes in the scene.
  76013. */
  76014. HighlightLayer.normalMeshStencilReference = 0x01;
  76015. return HighlightLayer;
  76016. }());
  76017. BABYLON.HighlightLayer = HighlightLayer;
  76018. })(BABYLON || (BABYLON = {}));
  76019. //# sourceMappingURL=babylon.highlightlayer.js.map
  76020. var BABYLON;
  76021. (function (BABYLON) {
  76022. var AssetTaskState;
  76023. (function (AssetTaskState) {
  76024. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  76025. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  76026. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  76027. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  76028. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  76029. var AbstractAssetTask = /** @class */ (function () {
  76030. function AbstractAssetTask(name) {
  76031. this.name = name;
  76032. this.isCompleted = false;
  76033. this.taskState = AssetTaskState.INIT;
  76034. }
  76035. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  76036. var _this = this;
  76037. this.taskState = AssetTaskState.RUNNING;
  76038. this.runTask(scene, function () {
  76039. _this.onDoneCallback(onSuccess, onError);
  76040. }, function (msg, exception) {
  76041. _this.onErrorCallback(onError, msg, exception);
  76042. });
  76043. };
  76044. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  76045. throw new Error("runTask is not implemented");
  76046. };
  76047. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  76048. this.taskState = AssetTaskState.ERROR;
  76049. this.errorObject = {
  76050. message: message,
  76051. exception: exception
  76052. };
  76053. if (this.onError) {
  76054. this.onError(this, message, exception);
  76055. }
  76056. onError();
  76057. };
  76058. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  76059. try {
  76060. this.taskState = AssetTaskState.DONE;
  76061. this.isCompleted = true;
  76062. if (this.onSuccess) {
  76063. this.onSuccess(this);
  76064. }
  76065. onSuccess();
  76066. }
  76067. catch (e) {
  76068. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  76069. }
  76070. };
  76071. return AbstractAssetTask;
  76072. }());
  76073. BABYLON.AbstractAssetTask = AbstractAssetTask;
  76074. var AssetsProgressEvent = /** @class */ (function () {
  76075. function AssetsProgressEvent(remainingCount, totalCount, task) {
  76076. this.remainingCount = remainingCount;
  76077. this.totalCount = totalCount;
  76078. this.task = task;
  76079. }
  76080. return AssetsProgressEvent;
  76081. }());
  76082. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  76083. var MeshAssetTask = /** @class */ (function (_super) {
  76084. __extends(MeshAssetTask, _super);
  76085. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  76086. var _this = _super.call(this, name) || this;
  76087. _this.name = name;
  76088. _this.meshesNames = meshesNames;
  76089. _this.rootUrl = rootUrl;
  76090. _this.sceneFilename = sceneFilename;
  76091. return _this;
  76092. }
  76093. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  76094. var _this = this;
  76095. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  76096. _this.loadedMeshes = meshes;
  76097. _this.loadedParticleSystems = particleSystems;
  76098. _this.loadedSkeletons = skeletons;
  76099. onSuccess();
  76100. }, null, function (scene, message, exception) {
  76101. onError(message, exception);
  76102. });
  76103. };
  76104. return MeshAssetTask;
  76105. }(AbstractAssetTask));
  76106. BABYLON.MeshAssetTask = MeshAssetTask;
  76107. var TextFileAssetTask = /** @class */ (function (_super) {
  76108. __extends(TextFileAssetTask, _super);
  76109. function TextFileAssetTask(name, url) {
  76110. var _this = _super.call(this, name) || this;
  76111. _this.name = name;
  76112. _this.url = url;
  76113. return _this;
  76114. }
  76115. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  76116. var _this = this;
  76117. BABYLON.Tools.LoadFile(this.url, function (data) {
  76118. _this.text = data;
  76119. onSuccess();
  76120. }, undefined, scene.database, false, function (request, exception) {
  76121. if (request) {
  76122. onError(request.status + " " + request.statusText, exception);
  76123. }
  76124. });
  76125. };
  76126. return TextFileAssetTask;
  76127. }(AbstractAssetTask));
  76128. BABYLON.TextFileAssetTask = TextFileAssetTask;
  76129. var BinaryFileAssetTask = /** @class */ (function (_super) {
  76130. __extends(BinaryFileAssetTask, _super);
  76131. function BinaryFileAssetTask(name, url) {
  76132. var _this = _super.call(this, name) || this;
  76133. _this.name = name;
  76134. _this.url = url;
  76135. return _this;
  76136. }
  76137. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  76138. var _this = this;
  76139. BABYLON.Tools.LoadFile(this.url, function (data) {
  76140. _this.data = data;
  76141. onSuccess();
  76142. }, undefined, scene.database, true, function (request, exception) {
  76143. if (request) {
  76144. onError(request.status + " " + request.statusText, exception);
  76145. }
  76146. });
  76147. };
  76148. return BinaryFileAssetTask;
  76149. }(AbstractAssetTask));
  76150. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  76151. var ImageAssetTask = /** @class */ (function (_super) {
  76152. __extends(ImageAssetTask, _super);
  76153. function ImageAssetTask(name, url) {
  76154. var _this = _super.call(this, name) || this;
  76155. _this.name = name;
  76156. _this.url = url;
  76157. return _this;
  76158. }
  76159. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  76160. var _this = this;
  76161. var img = new Image();
  76162. BABYLON.Tools.SetCorsBehavior(this.url, img);
  76163. img.onload = function () {
  76164. _this.image = img;
  76165. onSuccess();
  76166. };
  76167. img.onerror = function (err) {
  76168. onError("Error loading image", err);
  76169. };
  76170. img.src = this.url;
  76171. };
  76172. return ImageAssetTask;
  76173. }(AbstractAssetTask));
  76174. BABYLON.ImageAssetTask = ImageAssetTask;
  76175. var TextureAssetTask = /** @class */ (function (_super) {
  76176. __extends(TextureAssetTask, _super);
  76177. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  76178. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  76179. var _this = _super.call(this, name) || this;
  76180. _this.name = name;
  76181. _this.url = url;
  76182. _this.noMipmap = noMipmap;
  76183. _this.invertY = invertY;
  76184. _this.samplingMode = samplingMode;
  76185. return _this;
  76186. }
  76187. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  76188. var onload = function () {
  76189. onSuccess();
  76190. };
  76191. var onerror = function (message, exception) {
  76192. onError(message, exception);
  76193. };
  76194. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  76195. };
  76196. return TextureAssetTask;
  76197. }(AbstractAssetTask));
  76198. BABYLON.TextureAssetTask = TextureAssetTask;
  76199. var CubeTextureAssetTask = /** @class */ (function (_super) {
  76200. __extends(CubeTextureAssetTask, _super);
  76201. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  76202. var _this = _super.call(this, name) || this;
  76203. _this.name = name;
  76204. _this.url = url;
  76205. _this.extensions = extensions;
  76206. _this.noMipmap = noMipmap;
  76207. _this.files = files;
  76208. return _this;
  76209. }
  76210. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  76211. var onload = function () {
  76212. onSuccess();
  76213. };
  76214. var onerror = function (message, exception) {
  76215. onError(message, exception);
  76216. };
  76217. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  76218. };
  76219. return CubeTextureAssetTask;
  76220. }(AbstractAssetTask));
  76221. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  76222. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  76223. __extends(HDRCubeTextureAssetTask, _super);
  76224. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  76225. if (noMipmap === void 0) { noMipmap = false; }
  76226. if (generateHarmonics === void 0) { generateHarmonics = true; }
  76227. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  76228. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  76229. var _this = _super.call(this, name) || this;
  76230. _this.name = name;
  76231. _this.url = url;
  76232. _this.size = size;
  76233. _this.noMipmap = noMipmap;
  76234. _this.generateHarmonics = generateHarmonics;
  76235. _this.useInGammaSpace = useInGammaSpace;
  76236. _this.usePMREMGenerator = usePMREMGenerator;
  76237. return _this;
  76238. }
  76239. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  76240. var onload = function () {
  76241. onSuccess();
  76242. };
  76243. var onerror = function (message, exception) {
  76244. onError(message, exception);
  76245. };
  76246. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  76247. };
  76248. return HDRCubeTextureAssetTask;
  76249. }(AbstractAssetTask));
  76250. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  76251. var AssetsManager = /** @class */ (function () {
  76252. function AssetsManager(scene) {
  76253. this.tasks = new Array();
  76254. this.waitingTasksCount = 0;
  76255. //Observables
  76256. this.onTaskSuccessObservable = new BABYLON.Observable();
  76257. this.onTaskErrorObservable = new BABYLON.Observable();
  76258. this.onTasksDoneObservable = new BABYLON.Observable();
  76259. this.onProgressObservable = new BABYLON.Observable();
  76260. this.useDefaultLoadingScreen = true;
  76261. this._scene = scene;
  76262. }
  76263. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  76264. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  76265. this.tasks.push(task);
  76266. return task;
  76267. };
  76268. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  76269. var task = new TextFileAssetTask(taskName, url);
  76270. this.tasks.push(task);
  76271. return task;
  76272. };
  76273. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  76274. var task = new BinaryFileAssetTask(taskName, url);
  76275. this.tasks.push(task);
  76276. return task;
  76277. };
  76278. AssetsManager.prototype.addImageTask = function (taskName, url) {
  76279. var task = new ImageAssetTask(taskName, url);
  76280. this.tasks.push(task);
  76281. return task;
  76282. };
  76283. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  76284. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  76285. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  76286. this.tasks.push(task);
  76287. return task;
  76288. };
  76289. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  76290. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  76291. this.tasks.push(task);
  76292. return task;
  76293. };
  76294. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  76295. if (noMipmap === void 0) { noMipmap = false; }
  76296. if (generateHarmonics === void 0) { generateHarmonics = true; }
  76297. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  76298. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  76299. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  76300. this.tasks.push(task);
  76301. return task;
  76302. };
  76303. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  76304. this.waitingTasksCount--;
  76305. try {
  76306. if (this.onProgress) {
  76307. this.onProgress(this.waitingTasksCount, this.tasks.length, task);
  76308. }
  76309. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this.waitingTasksCount, this.tasks.length, task));
  76310. }
  76311. catch (e) {
  76312. BABYLON.Tools.Error("Error running progress callbacks.");
  76313. console.log(e);
  76314. }
  76315. if (this.waitingTasksCount === 0) {
  76316. try {
  76317. if (this.onFinish) {
  76318. this.onFinish(this.tasks);
  76319. }
  76320. this.onTasksDoneObservable.notifyObservers(this.tasks);
  76321. }
  76322. catch (e) {
  76323. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  76324. console.log(e);
  76325. }
  76326. this._scene.getEngine().hideLoadingUI();
  76327. }
  76328. };
  76329. AssetsManager.prototype._runTask = function (task) {
  76330. var _this = this;
  76331. var done = function () {
  76332. try {
  76333. if (_this.onTaskSuccess) {
  76334. _this.onTaskSuccess(task);
  76335. }
  76336. _this.onTaskSuccessObservable.notifyObservers(task);
  76337. _this._decreaseWaitingTasksCount(task);
  76338. }
  76339. catch (e) {
  76340. error("Error executing task success callbacks", e);
  76341. }
  76342. };
  76343. var error = function (message, exception) {
  76344. task.errorObject = task.errorObject || {
  76345. message: message,
  76346. exception: exception
  76347. };
  76348. if (_this.onTaskError) {
  76349. _this.onTaskError(task);
  76350. }
  76351. _this.onTaskErrorObservable.notifyObservers(task);
  76352. _this._decreaseWaitingTasksCount(task);
  76353. };
  76354. task.run(this._scene, done, error);
  76355. };
  76356. AssetsManager.prototype.reset = function () {
  76357. this.tasks = new Array();
  76358. return this;
  76359. };
  76360. AssetsManager.prototype.load = function () {
  76361. this.waitingTasksCount = this.tasks.length;
  76362. if (this.waitingTasksCount === 0) {
  76363. if (this.onFinish) {
  76364. this.onFinish(this.tasks);
  76365. }
  76366. this.onTasksDoneObservable.notifyObservers(this.tasks);
  76367. return this;
  76368. }
  76369. if (this.useDefaultLoadingScreen) {
  76370. this._scene.getEngine().displayLoadingUI();
  76371. }
  76372. for (var index = 0; index < this.tasks.length; index++) {
  76373. var task = this.tasks[index];
  76374. this._runTask(task);
  76375. }
  76376. return this;
  76377. };
  76378. return AssetsManager;
  76379. }());
  76380. BABYLON.AssetsManager = AssetsManager;
  76381. })(BABYLON || (BABYLON = {}));
  76382. //# sourceMappingURL=babylon.assetsManager.js.map
  76383. var BABYLON;
  76384. (function (BABYLON) {
  76385. var serializedGeometries = [];
  76386. var serializeGeometry = function (geometry, serializationGeometries) {
  76387. if (serializedGeometries[geometry.id]) {
  76388. return;
  76389. }
  76390. if (geometry.doNotSerialize) {
  76391. return;
  76392. }
  76393. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  76394. serializationGeometries.boxes.push(geometry.serialize());
  76395. }
  76396. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  76397. serializationGeometries.spheres.push(geometry.serialize());
  76398. }
  76399. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  76400. serializationGeometries.cylinders.push(geometry.serialize());
  76401. }
  76402. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  76403. serializationGeometries.toruses.push(geometry.serialize());
  76404. }
  76405. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  76406. serializationGeometries.grounds.push(geometry.serialize());
  76407. }
  76408. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  76409. serializationGeometries.planes.push(geometry.serialize());
  76410. }
  76411. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  76412. serializationGeometries.torusKnots.push(geometry.serialize());
  76413. }
  76414. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  76415. throw new Error("Unknown primitive type");
  76416. }
  76417. else {
  76418. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  76419. }
  76420. serializedGeometries[geometry.id] = true;
  76421. };
  76422. var serializeMesh = function (mesh, serializationScene) {
  76423. var serializationObject = {};
  76424. // Geometry
  76425. var geometry = mesh._geometry;
  76426. if (geometry) {
  76427. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  76428. // 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
  76429. serializeGeometry(geometry, serializationScene.geometries);
  76430. }
  76431. }
  76432. // Custom
  76433. if (mesh.serialize) {
  76434. mesh.serialize(serializationObject);
  76435. }
  76436. return serializationObject;
  76437. };
  76438. var finalizeSingleMesh = function (mesh, serializationObject) {
  76439. //only works if the mesh is already loaded
  76440. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  76441. //serialize material
  76442. if (mesh.material) {
  76443. if (mesh.material instanceof BABYLON.StandardMaterial) {
  76444. serializationObject.materials = serializationObject.materials || [];
  76445. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  76446. serializationObject.materials.push(mesh.material.serialize());
  76447. }
  76448. }
  76449. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  76450. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  76451. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  76452. serializationObject.multiMaterials.push(mesh.material.serialize());
  76453. }
  76454. }
  76455. }
  76456. //serialize geometry
  76457. var geometry = mesh._geometry;
  76458. if (geometry) {
  76459. if (!serializationObject.geometries) {
  76460. serializationObject.geometries = {};
  76461. serializationObject.geometries.boxes = [];
  76462. serializationObject.geometries.spheres = [];
  76463. serializationObject.geometries.cylinders = [];
  76464. serializationObject.geometries.toruses = [];
  76465. serializationObject.geometries.grounds = [];
  76466. serializationObject.geometries.planes = [];
  76467. serializationObject.geometries.torusKnots = [];
  76468. serializationObject.geometries.vertexData = [];
  76469. }
  76470. serializeGeometry(geometry, serializationObject.geometries);
  76471. }
  76472. // Skeletons
  76473. if (mesh.skeleton) {
  76474. serializationObject.skeletons = serializationObject.skeletons || [];
  76475. serializationObject.skeletons.push(mesh.skeleton.serialize());
  76476. }
  76477. //serialize the actual mesh
  76478. serializationObject.meshes = serializationObject.meshes || [];
  76479. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  76480. }
  76481. };
  76482. var SceneSerializer = /** @class */ (function () {
  76483. function SceneSerializer() {
  76484. }
  76485. SceneSerializer.ClearCache = function () {
  76486. serializedGeometries = [];
  76487. };
  76488. SceneSerializer.Serialize = function (scene) {
  76489. var serializationObject = {};
  76490. SceneSerializer.ClearCache();
  76491. // Scene
  76492. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  76493. serializationObject.autoClear = scene.autoClear;
  76494. serializationObject.clearColor = scene.clearColor.asArray();
  76495. serializationObject.ambientColor = scene.ambientColor.asArray();
  76496. serializationObject.gravity = scene.gravity.asArray();
  76497. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  76498. serializationObject.workerCollisions = scene.workerCollisions;
  76499. // Fog
  76500. if (scene.fogMode && scene.fogMode !== 0) {
  76501. serializationObject.fogMode = scene.fogMode;
  76502. serializationObject.fogColor = scene.fogColor.asArray();
  76503. serializationObject.fogStart = scene.fogStart;
  76504. serializationObject.fogEnd = scene.fogEnd;
  76505. serializationObject.fogDensity = scene.fogDensity;
  76506. }
  76507. //Physics
  76508. if (scene.isPhysicsEnabled()) {
  76509. var physicEngine = scene.getPhysicsEngine();
  76510. if (physicEngine) {
  76511. serializationObject.physicsEnabled = true;
  76512. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  76513. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  76514. }
  76515. }
  76516. // Metadata
  76517. if (scene.metadata) {
  76518. serializationObject.metadata = scene.metadata;
  76519. }
  76520. // Morph targets
  76521. serializationObject.morphTargetManagers = [];
  76522. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  76523. var abstractMesh = _a[_i];
  76524. var manager = abstractMesh.morphTargetManager;
  76525. if (manager) {
  76526. serializationObject.morphTargetManagers.push(manager.serialize());
  76527. }
  76528. }
  76529. // Lights
  76530. serializationObject.lights = [];
  76531. var index;
  76532. var light;
  76533. for (index = 0; index < scene.lights.length; index++) {
  76534. light = scene.lights[index];
  76535. if (!light.doNotSerialize) {
  76536. serializationObject.lights.push(light.serialize());
  76537. }
  76538. }
  76539. // Cameras
  76540. serializationObject.cameras = [];
  76541. for (index = 0; index < scene.cameras.length; index++) {
  76542. var camera = scene.cameras[index];
  76543. if (!camera.doNotSerialize) {
  76544. serializationObject.cameras.push(camera.serialize());
  76545. }
  76546. }
  76547. if (scene.activeCamera) {
  76548. serializationObject.activeCameraID = scene.activeCamera.id;
  76549. }
  76550. // Animations
  76551. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  76552. // Materials
  76553. serializationObject.materials = [];
  76554. serializationObject.multiMaterials = [];
  76555. var material;
  76556. for (index = 0; index < scene.materials.length; index++) {
  76557. material = scene.materials[index];
  76558. if (!material.doNotSerialize) {
  76559. serializationObject.materials.push(material.serialize());
  76560. }
  76561. }
  76562. // MultiMaterials
  76563. serializationObject.multiMaterials = [];
  76564. for (index = 0; index < scene.multiMaterials.length; index++) {
  76565. var multiMaterial = scene.multiMaterials[index];
  76566. serializationObject.multiMaterials.push(multiMaterial.serialize());
  76567. }
  76568. // Skeletons
  76569. serializationObject.skeletons = [];
  76570. for (index = 0; index < scene.skeletons.length; index++) {
  76571. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  76572. }
  76573. // Transform nodes
  76574. serializationObject.transformNodes = [];
  76575. for (index = 0; index < scene.transformNodes.length; index++) {
  76576. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  76577. }
  76578. // Geometries
  76579. serializationObject.geometries = {};
  76580. serializationObject.geometries.boxes = [];
  76581. serializationObject.geometries.spheres = [];
  76582. serializationObject.geometries.cylinders = [];
  76583. serializationObject.geometries.toruses = [];
  76584. serializationObject.geometries.grounds = [];
  76585. serializationObject.geometries.planes = [];
  76586. serializationObject.geometries.torusKnots = [];
  76587. serializationObject.geometries.vertexData = [];
  76588. serializedGeometries = [];
  76589. var geometries = scene.getGeometries();
  76590. for (index = 0; index < geometries.length; index++) {
  76591. var geometry = geometries[index];
  76592. if (geometry.isReady()) {
  76593. serializeGeometry(geometry, serializationObject.geometries);
  76594. }
  76595. }
  76596. // Meshes
  76597. serializationObject.meshes = [];
  76598. for (index = 0; index < scene.meshes.length; index++) {
  76599. var abstractMesh = scene.meshes[index];
  76600. if (abstractMesh instanceof BABYLON.Mesh) {
  76601. var mesh = abstractMesh;
  76602. if (!mesh.doNotSerialize) {
  76603. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  76604. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  76605. }
  76606. }
  76607. }
  76608. }
  76609. // Particles Systems
  76610. serializationObject.particleSystems = [];
  76611. for (index = 0; index < scene.particleSystems.length; index++) {
  76612. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  76613. }
  76614. // Lens flares
  76615. serializationObject.lensFlareSystems = [];
  76616. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  76617. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  76618. }
  76619. // Shadows
  76620. serializationObject.shadowGenerators = [];
  76621. for (index = 0; index < scene.lights.length; index++) {
  76622. light = scene.lights[index];
  76623. var shadowGenerator = light.getShadowGenerator();
  76624. if (shadowGenerator) {
  76625. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  76626. }
  76627. }
  76628. // Action Manager
  76629. if (scene.actionManager) {
  76630. serializationObject.actions = scene.actionManager.serialize("scene");
  76631. }
  76632. // Audio
  76633. serializationObject.sounds = [];
  76634. for (index = 0; index < scene.soundTracks.length; index++) {
  76635. var soundtrack = scene.soundTracks[index];
  76636. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  76637. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  76638. }
  76639. }
  76640. return serializationObject;
  76641. };
  76642. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  76643. if (withParents === void 0) { withParents = false; }
  76644. if (withChildren === void 0) { withChildren = false; }
  76645. var serializationObject = {};
  76646. SceneSerializer.ClearCache();
  76647. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  76648. if (withParents || withChildren) {
  76649. //deliberate for loop! not for each, appended should be processed as well.
  76650. for (var i = 0; i < toSerialize.length; ++i) {
  76651. if (withChildren) {
  76652. toSerialize[i].getDescendants().forEach(function (node) {
  76653. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  76654. toSerialize.push(node);
  76655. }
  76656. });
  76657. }
  76658. //make sure the array doesn't contain the object already
  76659. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  76660. toSerialize.push(toSerialize[i].parent);
  76661. }
  76662. }
  76663. }
  76664. toSerialize.forEach(function (mesh) {
  76665. finalizeSingleMesh(mesh, serializationObject);
  76666. });
  76667. return serializationObject;
  76668. };
  76669. return SceneSerializer;
  76670. }());
  76671. BABYLON.SceneSerializer = SceneSerializer;
  76672. })(BABYLON || (BABYLON = {}));
  76673. //# sourceMappingURL=babylon.sceneSerializer.js.map
  76674. var BABYLON;
  76675. (function (BABYLON) {
  76676. var ReflectionProbe = /** @class */ (function () {
  76677. function ReflectionProbe(name, size, scene, generateMipMaps) {
  76678. if (generateMipMaps === void 0) { generateMipMaps = true; }
  76679. var _this = this;
  76680. this.name = name;
  76681. this._viewMatrix = BABYLON.Matrix.Identity();
  76682. this._target = BABYLON.Vector3.Zero();
  76683. this._add = BABYLON.Vector3.Zero();
  76684. this.invertYAxis = false;
  76685. this.position = BABYLON.Vector3.Zero();
  76686. this._scene = scene;
  76687. this._scene.reflectionProbes.push(this);
  76688. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  76689. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  76690. switch (faceIndex) {
  76691. case 0:
  76692. _this._add.copyFromFloats(1, 0, 0);
  76693. break;
  76694. case 1:
  76695. _this._add.copyFromFloats(-1, 0, 0);
  76696. break;
  76697. case 2:
  76698. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  76699. break;
  76700. case 3:
  76701. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  76702. break;
  76703. case 4:
  76704. _this._add.copyFromFloats(0, 0, 1);
  76705. break;
  76706. case 5:
  76707. _this._add.copyFromFloats(0, 0, -1);
  76708. break;
  76709. }
  76710. if (_this._attachedMesh) {
  76711. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  76712. }
  76713. _this.position.addToRef(_this._add, _this._target);
  76714. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  76715. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  76716. scene._forcedViewPosition = _this.position;
  76717. });
  76718. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  76719. scene._forcedViewPosition = null;
  76720. scene.updateTransformMatrix(true);
  76721. });
  76722. if (scene.activeCamera) {
  76723. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  76724. }
  76725. }
  76726. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  76727. get: function () {
  76728. return this._renderTargetTexture.samples;
  76729. },
  76730. set: function (value) {
  76731. this._renderTargetTexture.samples = value;
  76732. },
  76733. enumerable: true,
  76734. configurable: true
  76735. });
  76736. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  76737. get: function () {
  76738. return this._renderTargetTexture.refreshRate;
  76739. },
  76740. set: function (value) {
  76741. this._renderTargetTexture.refreshRate = value;
  76742. },
  76743. enumerable: true,
  76744. configurable: true
  76745. });
  76746. ReflectionProbe.prototype.getScene = function () {
  76747. return this._scene;
  76748. };
  76749. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  76750. get: function () {
  76751. return this._renderTargetTexture;
  76752. },
  76753. enumerable: true,
  76754. configurable: true
  76755. });
  76756. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  76757. get: function () {
  76758. return this._renderTargetTexture.renderList;
  76759. },
  76760. enumerable: true,
  76761. configurable: true
  76762. });
  76763. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  76764. this._attachedMesh = mesh;
  76765. };
  76766. /**
  76767. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  76768. *
  76769. * @param renderingGroupId The rendering group id corresponding to its index
  76770. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  76771. */
  76772. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  76773. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  76774. };
  76775. ReflectionProbe.prototype.dispose = function () {
  76776. var index = this._scene.reflectionProbes.indexOf(this);
  76777. if (index !== -1) {
  76778. // Remove from the scene if found
  76779. this._scene.reflectionProbes.splice(index, 1);
  76780. }
  76781. if (this._renderTargetTexture) {
  76782. this._renderTargetTexture.dispose();
  76783. this._renderTargetTexture = null;
  76784. }
  76785. };
  76786. return ReflectionProbe;
  76787. }());
  76788. BABYLON.ReflectionProbe = ReflectionProbe;
  76789. })(BABYLON || (BABYLON = {}));
  76790. //# sourceMappingURL=babylon.reflectionProbe.js.map
  76791. var BABYLON;
  76792. (function (BABYLON) {
  76793. var Layer = /** @class */ (function () {
  76794. function Layer(name, imgUrl, scene, isBackground, color) {
  76795. this.name = name;
  76796. this.scale = new BABYLON.Vector2(1, 1);
  76797. this.offset = new BABYLON.Vector2(0, 0);
  76798. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  76799. this.layerMask = 0x0FFFFFFF;
  76800. this._vertexBuffers = {};
  76801. // Events
  76802. /**
  76803. * An event triggered when the layer is disposed.
  76804. * @type {BABYLON.Observable}
  76805. */
  76806. this.onDisposeObservable = new BABYLON.Observable();
  76807. /**
  76808. * An event triggered before rendering the scene
  76809. * @type {BABYLON.Observable}
  76810. */
  76811. this.onBeforeRenderObservable = new BABYLON.Observable();
  76812. /**
  76813. * An event triggered after rendering the scene
  76814. * @type {BABYLON.Observable}
  76815. */
  76816. this.onAfterRenderObservable = new BABYLON.Observable();
  76817. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  76818. this.isBackground = isBackground === undefined ? true : isBackground;
  76819. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  76820. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  76821. this._scene.layers.push(this);
  76822. var engine = this._scene.getEngine();
  76823. // VBO
  76824. var vertices = [];
  76825. vertices.push(1, 1);
  76826. vertices.push(-1, 1);
  76827. vertices.push(-1, -1);
  76828. vertices.push(1, -1);
  76829. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  76830. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  76831. this._createIndexBuffer();
  76832. // Effects
  76833. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  76834. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  76835. }
  76836. Object.defineProperty(Layer.prototype, "onDispose", {
  76837. set: function (callback) {
  76838. if (this._onDisposeObserver) {
  76839. this.onDisposeObservable.remove(this._onDisposeObserver);
  76840. }
  76841. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  76842. },
  76843. enumerable: true,
  76844. configurable: true
  76845. });
  76846. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  76847. set: function (callback) {
  76848. if (this._onBeforeRenderObserver) {
  76849. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  76850. }
  76851. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  76852. },
  76853. enumerable: true,
  76854. configurable: true
  76855. });
  76856. Object.defineProperty(Layer.prototype, "onAfterRender", {
  76857. set: function (callback) {
  76858. if (this._onAfterRenderObserver) {
  76859. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  76860. }
  76861. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  76862. },
  76863. enumerable: true,
  76864. configurable: true
  76865. });
  76866. Layer.prototype._createIndexBuffer = function () {
  76867. var engine = this._scene.getEngine();
  76868. // Indices
  76869. var indices = [];
  76870. indices.push(0);
  76871. indices.push(1);
  76872. indices.push(2);
  76873. indices.push(0);
  76874. indices.push(2);
  76875. indices.push(3);
  76876. this._indexBuffer = engine.createIndexBuffer(indices);
  76877. };
  76878. Layer.prototype._rebuild = function () {
  76879. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76880. if (vb) {
  76881. vb._rebuild();
  76882. }
  76883. this._createIndexBuffer();
  76884. };
  76885. Layer.prototype.render = function () {
  76886. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  76887. // Check
  76888. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  76889. return;
  76890. var engine = this._scene.getEngine();
  76891. this.onBeforeRenderObservable.notifyObservers(this);
  76892. // Render
  76893. engine.enableEffect(currentEffect);
  76894. engine.setState(false);
  76895. // Texture
  76896. currentEffect.setTexture("textureSampler", this.texture);
  76897. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  76898. // Color
  76899. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  76900. // Scale / offset
  76901. currentEffect.setVector2("offset", this.offset);
  76902. currentEffect.setVector2("scale", this.scale);
  76903. // VBOs
  76904. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  76905. // Draw order
  76906. if (!this.alphaTest) {
  76907. engine.setAlphaMode(this.alphaBlendingMode);
  76908. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76909. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  76910. }
  76911. else {
  76912. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76913. }
  76914. this.onAfterRenderObservable.notifyObservers(this);
  76915. };
  76916. Layer.prototype.dispose = function () {
  76917. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76918. if (vertexBuffer) {
  76919. vertexBuffer.dispose();
  76920. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  76921. }
  76922. if (this._indexBuffer) {
  76923. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  76924. this._indexBuffer = null;
  76925. }
  76926. if (this.texture) {
  76927. this.texture.dispose();
  76928. this.texture = null;
  76929. }
  76930. // Remove from scene
  76931. var index = this._scene.layers.indexOf(this);
  76932. this._scene.layers.splice(index, 1);
  76933. // Callback
  76934. this.onDisposeObservable.notifyObservers(this);
  76935. this.onDisposeObservable.clear();
  76936. this.onAfterRenderObservable.clear();
  76937. this.onBeforeRenderObservable.clear();
  76938. };
  76939. return Layer;
  76940. }());
  76941. BABYLON.Layer = Layer;
  76942. })(BABYLON || (BABYLON = {}));
  76943. //# sourceMappingURL=babylon.layer.js.map
  76944. var BABYLON;
  76945. (function (BABYLON) {
  76946. var TextureTools = /** @class */ (function () {
  76947. function TextureTools() {
  76948. }
  76949. /**
  76950. * Uses the GPU to create a copy texture rescaled at a given size
  76951. * @param texture Texture to copy from
  76952. * @param width Desired width
  76953. * @param height Desired height
  76954. * @return Generated texture
  76955. */
  76956. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  76957. if (useBilinearMode === void 0) { useBilinearMode = true; }
  76958. var scene = texture.getScene();
  76959. var engine = scene.getEngine();
  76960. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  76961. rtt.wrapU = texture.wrapU;
  76962. rtt.wrapV = texture.wrapV;
  76963. rtt.uOffset = texture.uOffset;
  76964. rtt.vOffset = texture.vOffset;
  76965. rtt.uScale = texture.uScale;
  76966. rtt.vScale = texture.vScale;
  76967. rtt.uAng = texture.uAng;
  76968. rtt.vAng = texture.vAng;
  76969. rtt.wAng = texture.wAng;
  76970. rtt.coordinatesIndex = texture.coordinatesIndex;
  76971. rtt.level = texture.level;
  76972. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  76973. rtt._texture.isReady = false;
  76974. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76975. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76976. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76977. passPostProcess.getEffect().executeWhenCompiled(function () {
  76978. passPostProcess.onApply = function (effect) {
  76979. effect.setTexture("textureSampler", texture);
  76980. };
  76981. var internalTexture = rtt.getInternalTexture();
  76982. if (internalTexture) {
  76983. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  76984. engine.unBindFramebuffer(internalTexture);
  76985. rtt.disposeFramebufferObjects();
  76986. passPostProcess.dispose();
  76987. internalTexture.isReady = true;
  76988. }
  76989. });
  76990. return rtt;
  76991. };
  76992. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  76993. if (!scene._environmentBRDFTexture) {
  76994. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76995. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76996. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76997. scene._environmentBRDFTexture = texture;
  76998. }
  76999. return scene._environmentBRDFTexture;
  77000. };
  77001. 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=";
  77002. return TextureTools;
  77003. }());
  77004. BABYLON.TextureTools = TextureTools;
  77005. })(BABYLON || (BABYLON = {}));
  77006. //# sourceMappingURL=babylon.textureTools.js.map
  77007. var BABYLON;
  77008. (function (BABYLON) {
  77009. var FramingBehavior = /** @class */ (function () {
  77010. function FramingBehavior() {
  77011. this._mode = FramingBehavior.FitFrustumSidesMode;
  77012. this._radiusScale = 1.0;
  77013. this._positionScale = 0.5;
  77014. this._defaultElevation = 0.3;
  77015. this._elevationReturnTime = 1500;
  77016. this._elevationReturnWaitTime = 1000;
  77017. this._zoomStopsAnimation = false;
  77018. this._framingTime = 1500;
  77019. this._isPointerDown = false;
  77020. this._lastInteractionTime = -Infinity;
  77021. // Framing control
  77022. this._animatables = new Array();
  77023. this._betaIsAnimating = false;
  77024. }
  77025. Object.defineProperty(FramingBehavior.prototype, "name", {
  77026. get: function () {
  77027. return "Framing";
  77028. },
  77029. enumerable: true,
  77030. configurable: true
  77031. });
  77032. Object.defineProperty(FramingBehavior.prototype, "mode", {
  77033. /**
  77034. * Gets current mode used by the behavior.
  77035. */
  77036. get: function () {
  77037. return this._mode;
  77038. },
  77039. /**
  77040. * Sets the current mode used by the behavior
  77041. */
  77042. set: function (mode) {
  77043. this._mode = mode;
  77044. },
  77045. enumerable: true,
  77046. configurable: true
  77047. });
  77048. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  77049. /**
  77050. * Gets the scale applied to the radius
  77051. */
  77052. get: function () {
  77053. return this._radiusScale;
  77054. },
  77055. /**
  77056. * Sets the scale applied to the radius (1 by default)
  77057. */
  77058. set: function (radius) {
  77059. this._radiusScale = radius;
  77060. },
  77061. enumerable: true,
  77062. configurable: true
  77063. });
  77064. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  77065. /**
  77066. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  77067. */
  77068. get: function () {
  77069. return this._positionScale;
  77070. },
  77071. /**
  77072. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  77073. */
  77074. set: function (scale) {
  77075. this._positionScale = scale;
  77076. },
  77077. enumerable: true,
  77078. configurable: true
  77079. });
  77080. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  77081. /**
  77082. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  77083. * behaviour is triggered, in radians.
  77084. */
  77085. get: function () {
  77086. return this._defaultElevation;
  77087. },
  77088. /**
  77089. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  77090. * behaviour is triggered, in radians.
  77091. */
  77092. set: function (elevation) {
  77093. this._defaultElevation = elevation;
  77094. },
  77095. enumerable: true,
  77096. configurable: true
  77097. });
  77098. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  77099. /**
  77100. * Gets the time (in milliseconds) taken to return to the default beta position.
  77101. * Negative value indicates camera should not return to default.
  77102. */
  77103. get: function () {
  77104. return this._elevationReturnTime;
  77105. },
  77106. /**
  77107. * Sets the time (in milliseconds) taken to return to the default beta position.
  77108. * Negative value indicates camera should not return to default.
  77109. */
  77110. set: function (speed) {
  77111. this._elevationReturnTime = speed;
  77112. },
  77113. enumerable: true,
  77114. configurable: true
  77115. });
  77116. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  77117. /**
  77118. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  77119. */
  77120. get: function () {
  77121. return this._elevationReturnWaitTime;
  77122. },
  77123. /**
  77124. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  77125. */
  77126. set: function (time) {
  77127. this._elevationReturnWaitTime = time;
  77128. },
  77129. enumerable: true,
  77130. configurable: true
  77131. });
  77132. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  77133. /**
  77134. * Gets the flag that indicates if user zooming should stop animation.
  77135. */
  77136. get: function () {
  77137. return this._zoomStopsAnimation;
  77138. },
  77139. /**
  77140. * Sets the flag that indicates if user zooming should stop animation.
  77141. */
  77142. set: function (flag) {
  77143. this._zoomStopsAnimation = flag;
  77144. },
  77145. enumerable: true,
  77146. configurable: true
  77147. });
  77148. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  77149. /**
  77150. * Gets the transition time when framing the mesh, in milliseconds
  77151. */
  77152. get: function () {
  77153. return this._framingTime;
  77154. },
  77155. /**
  77156. * Sets the transition time when framing the mesh, in milliseconds
  77157. */
  77158. set: function (time) {
  77159. this._framingTime = time;
  77160. },
  77161. enumerable: true,
  77162. configurable: true
  77163. });
  77164. FramingBehavior.prototype.init = function () {
  77165. // Do notihng
  77166. };
  77167. FramingBehavior.prototype.attach = function (camera) {
  77168. var _this = this;
  77169. this._attachedCamera = camera;
  77170. var scene = this._attachedCamera.getScene();
  77171. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  77172. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  77173. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  77174. _this._isPointerDown = true;
  77175. return;
  77176. }
  77177. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  77178. _this._isPointerDown = false;
  77179. }
  77180. });
  77181. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  77182. if (mesh) {
  77183. _this.zoomOnMesh(mesh);
  77184. }
  77185. });
  77186. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  77187. // Stop the animation if there is user interaction and the animation should stop for this interaction
  77188. _this._applyUserInteraction();
  77189. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  77190. // back to the default position after a given timeout
  77191. _this._maintainCameraAboveGround();
  77192. });
  77193. };
  77194. FramingBehavior.prototype.detach = function () {
  77195. if (!this._attachedCamera) {
  77196. return;
  77197. }
  77198. var scene = this._attachedCamera.getScene();
  77199. if (this._onPrePointerObservableObserver) {
  77200. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  77201. }
  77202. if (this._onAfterCheckInputsObserver) {
  77203. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  77204. }
  77205. if (this._onMeshTargetChangedObserver) {
  77206. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  77207. }
  77208. this._attachedCamera = null;
  77209. };
  77210. /**
  77211. * Targets the given mesh and updates zoom level accordingly.
  77212. * @param mesh The mesh to target.
  77213. * @param radius Optional. If a cached radius position already exists, overrides default.
  77214. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  77215. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  77216. * @param onAnimationEnd Callback triggered at the end of the framing animation
  77217. */
  77218. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  77219. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  77220. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  77221. mesh.computeWorldMatrix(true);
  77222. var boundingBox = mesh.getBoundingInfo().boundingBox;
  77223. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  77224. };
  77225. /**
  77226. * Targets the given mesh with its children and updates zoom level accordingly.
  77227. * @param mesh The mesh to target.
  77228. * @param radius Optional. If a cached radius position already exists, overrides default.
  77229. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  77230. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  77231. * @param onAnimationEnd Callback triggered at the end of the framing animation
  77232. */
  77233. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  77234. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  77235. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  77236. mesh.computeWorldMatrix(true);
  77237. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  77238. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  77239. };
  77240. /**
  77241. * Targets the given meshes with their children and updates zoom level accordingly.
  77242. * @param meshes The mesh to target.
  77243. * @param radius Optional. If a cached radius position already exists, overrides default.
  77244. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  77245. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  77246. * @param onAnimationEnd Callback triggered at the end of the framing animation
  77247. */
  77248. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  77249. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  77250. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  77251. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  77252. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  77253. for (var i = 0; i < meshes.length; i++) {
  77254. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  77255. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  77256. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  77257. }
  77258. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  77259. };
  77260. /**
  77261. * Targets the given mesh and updates zoom level accordingly.
  77262. * @param mesh The mesh to target.
  77263. * @param radius Optional. If a cached radius position already exists, overrides default.
  77264. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  77265. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  77266. * @param onAnimationEnd Callback triggered at the end of the framing animation
  77267. */
  77268. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  77269. var _this = this;
  77270. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  77271. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  77272. var zoomTarget;
  77273. if (!this._attachedCamera) {
  77274. return;
  77275. }
  77276. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  77277. var bottom = minimumWorld.y;
  77278. var top = maximumWorld.y;
  77279. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  77280. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  77281. if (focusOnOriginXZ) {
  77282. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  77283. }
  77284. else {
  77285. var centerWorld = minimumWorld.add(radiusWorld);
  77286. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  77287. }
  77288. if (!this._vectorTransition) {
  77289. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  77290. }
  77291. this._betaIsAnimating = true;
  77292. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  77293. if (animatable) {
  77294. this._animatables.push(animatable);
  77295. }
  77296. // sets the radius and lower radius bounds
  77297. // Small delta ensures camera is not always at lower zoom limit.
  77298. var radius = 0;
  77299. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  77300. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  77301. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  77302. radius = position;
  77303. }
  77304. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  77305. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  77306. if (this._attachedCamera.lowerRadiusLimit === null) {
  77307. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  77308. }
  77309. }
  77310. // Set sensibilities
  77311. var extend = maximumWorld.subtract(minimumWorld).length();
  77312. this._attachedCamera.panningSensibility = 5000 / extend;
  77313. this._attachedCamera.wheelPrecision = 100 / radius;
  77314. // transition to new radius
  77315. if (!this._radiusTransition) {
  77316. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  77317. }
  77318. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  77319. if (onAnimationEnd) {
  77320. onAnimationEnd();
  77321. }
  77322. if (_this._attachedCamera) {
  77323. _this._attachedCamera.storeState();
  77324. }
  77325. });
  77326. if (animatable) {
  77327. this._animatables.push(animatable);
  77328. }
  77329. };
  77330. /**
  77331. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  77332. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  77333. * frustum width.
  77334. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  77335. * to fully enclose the mesh in the viewing frustum.
  77336. */
  77337. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  77338. var size = maximumWorld.subtract(minimumWorld);
  77339. var boxVectorGlobalDiagonal = size.length();
  77340. var frustumSlope = this._getFrustumSlope();
  77341. // Formula for setting distance
  77342. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  77343. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  77344. // Horizon distance
  77345. var radius = radiusWithoutFraming * this._radiusScale;
  77346. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  77347. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  77348. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  77349. var camera = this._attachedCamera;
  77350. if (!camera) {
  77351. return 0;
  77352. }
  77353. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  77354. // Don't exceed the requested limit
  77355. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  77356. }
  77357. // Don't exceed the upper radius limit
  77358. if (camera.upperRadiusLimit) {
  77359. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  77360. }
  77361. return distance;
  77362. };
  77363. /**
  77364. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  77365. * is automatically returned to its default position (expected to be above ground plane).
  77366. */
  77367. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  77368. var _this = this;
  77369. if (this._elevationReturnTime < 0) {
  77370. return;
  77371. }
  77372. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  77373. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  77374. var limitBeta = Math.PI * 0.5;
  77375. // Bring the camera back up if below the ground plane
  77376. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  77377. this._betaIsAnimating = true;
  77378. //Transition to new position
  77379. this.stopAllAnimations();
  77380. if (!this._betaTransition) {
  77381. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  77382. }
  77383. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  77384. _this._clearAnimationLocks();
  77385. _this.stopAllAnimations();
  77386. });
  77387. if (animatabe) {
  77388. this._animatables.push(animatabe);
  77389. }
  77390. }
  77391. };
  77392. /**
  77393. * Returns the frustum slope based on the canvas ratio and camera FOV
  77394. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  77395. */
  77396. FramingBehavior.prototype._getFrustumSlope = function () {
  77397. // Calculate the viewport ratio
  77398. // Aspect Ratio is Height/Width.
  77399. var camera = this._attachedCamera;
  77400. if (!camera) {
  77401. return BABYLON.Vector2.Zero();
  77402. }
  77403. var engine = camera.getScene().getEngine();
  77404. var aspectRatio = engine.getAspectRatio(camera);
  77405. // Camera FOV is the vertical field of view (top-bottom) in radians.
  77406. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  77407. var frustumSlopeY = Math.tan(camera.fov / 2);
  77408. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  77409. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  77410. // along the forward vector.
  77411. var frustumSlopeX = frustumSlopeY * aspectRatio;
  77412. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  77413. };
  77414. /**
  77415. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  77416. */
  77417. FramingBehavior.prototype._clearAnimationLocks = function () {
  77418. this._betaIsAnimating = false;
  77419. };
  77420. /**
  77421. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  77422. */
  77423. FramingBehavior.prototype._applyUserInteraction = function () {
  77424. if (this.isUserIsMoving) {
  77425. this._lastInteractionTime = BABYLON.Tools.Now;
  77426. this.stopAllAnimations();
  77427. this._clearAnimationLocks();
  77428. }
  77429. };
  77430. /**
  77431. * Stops and removes all animations that have been applied to the camera
  77432. */
  77433. FramingBehavior.prototype.stopAllAnimations = function () {
  77434. if (this._attachedCamera) {
  77435. this._attachedCamera.animations = [];
  77436. }
  77437. while (this._animatables.length) {
  77438. if (this._animatables[0]) {
  77439. this._animatables[0].onAnimationEnd = null;
  77440. this._animatables[0].stop();
  77441. }
  77442. this._animatables.shift();
  77443. }
  77444. };
  77445. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  77446. /**
  77447. * Gets a value indicating if the user is moving the camera
  77448. */
  77449. get: function () {
  77450. if (!this._attachedCamera) {
  77451. return false;
  77452. }
  77453. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  77454. this._attachedCamera.inertialBetaOffset !== 0 ||
  77455. this._attachedCamera.inertialRadiusOffset !== 0 ||
  77456. this._attachedCamera.inertialPanningX !== 0 ||
  77457. this._attachedCamera.inertialPanningY !== 0 ||
  77458. this._isPointerDown;
  77459. },
  77460. enumerable: true,
  77461. configurable: true
  77462. });
  77463. /**
  77464. * The easing function used by animations
  77465. */
  77466. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  77467. /**
  77468. * The easing mode used by animations
  77469. */
  77470. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  77471. // Statics
  77472. /**
  77473. * The camera can move all the way towards the mesh.
  77474. */
  77475. FramingBehavior.IgnoreBoundsSizeMode = 0;
  77476. /**
  77477. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  77478. */
  77479. FramingBehavior.FitFrustumSidesMode = 1;
  77480. return FramingBehavior;
  77481. }());
  77482. BABYLON.FramingBehavior = FramingBehavior;
  77483. })(BABYLON || (BABYLON = {}));
  77484. //# sourceMappingURL=babylon.framingBehavior.js.map
  77485. var BABYLON;
  77486. (function (BABYLON) {
  77487. /**
  77488. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  77489. */
  77490. var BouncingBehavior = /** @class */ (function () {
  77491. function BouncingBehavior() {
  77492. /**
  77493. * The duration of the animation, in milliseconds
  77494. */
  77495. this.transitionDuration = 450;
  77496. /**
  77497. * Length of the distance animated by the transition when lower radius is reached
  77498. */
  77499. this.lowerRadiusTransitionRange = 2;
  77500. /**
  77501. * Length of the distance animated by the transition when upper radius is reached
  77502. */
  77503. this.upperRadiusTransitionRange = -2;
  77504. this._autoTransitionRange = false;
  77505. // Animations
  77506. this._radiusIsAnimating = false;
  77507. this._radiusBounceTransition = null;
  77508. this._animatables = new Array();
  77509. }
  77510. Object.defineProperty(BouncingBehavior.prototype, "name", {
  77511. get: function () {
  77512. return "Bouncing";
  77513. },
  77514. enumerable: true,
  77515. configurable: true
  77516. });
  77517. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  77518. /**
  77519. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  77520. */
  77521. get: function () {
  77522. return this._autoTransitionRange;
  77523. },
  77524. /**
  77525. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  77526. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  77527. */
  77528. set: function (value) {
  77529. var _this = this;
  77530. if (this._autoTransitionRange === value) {
  77531. return;
  77532. }
  77533. this._autoTransitionRange = value;
  77534. var camera = this._attachedCamera;
  77535. if (!camera) {
  77536. return;
  77537. }
  77538. if (value) {
  77539. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  77540. if (!mesh) {
  77541. return;
  77542. }
  77543. mesh.computeWorldMatrix(true);
  77544. var diagonal = mesh.getBoundingInfo().diagonalLength;
  77545. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  77546. _this.upperRadiusTransitionRange = diagonal * 0.05;
  77547. });
  77548. }
  77549. else if (this._onMeshTargetChangedObserver) {
  77550. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  77551. }
  77552. },
  77553. enumerable: true,
  77554. configurable: true
  77555. });
  77556. BouncingBehavior.prototype.init = function () {
  77557. // Do notihng
  77558. };
  77559. BouncingBehavior.prototype.attach = function (camera) {
  77560. var _this = this;
  77561. this._attachedCamera = camera;
  77562. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  77563. if (!_this._attachedCamera) {
  77564. return;
  77565. }
  77566. // Add the bounce animation to the lower radius limit
  77567. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  77568. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  77569. }
  77570. // Add the bounce animation to the upper radius limit
  77571. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  77572. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  77573. }
  77574. });
  77575. };
  77576. BouncingBehavior.prototype.detach = function () {
  77577. if (!this._attachedCamera) {
  77578. return;
  77579. }
  77580. if (this._onAfterCheckInputsObserver) {
  77581. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  77582. }
  77583. if (this._onMeshTargetChangedObserver) {
  77584. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  77585. }
  77586. this._attachedCamera = null;
  77587. };
  77588. /**
  77589. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  77590. * @param radiusLimit The limit to check against.
  77591. * @return Bool to indicate if at limit.
  77592. */
  77593. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  77594. if (!this._attachedCamera) {
  77595. return false;
  77596. }
  77597. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  77598. return true;
  77599. }
  77600. return false;
  77601. };
  77602. /**
  77603. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  77604. * @param radiusDelta The delta by which to animate to. Can be negative.
  77605. */
  77606. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  77607. var _this = this;
  77608. if (!this._attachedCamera) {
  77609. return;
  77610. }
  77611. if (!this._radiusBounceTransition) {
  77612. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  77613. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  77614. }
  77615. // Prevent zoom until bounce has completed
  77616. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  77617. this._attachedCamera.wheelPrecision = Infinity;
  77618. this._attachedCamera.inertialRadiusOffset = 0;
  77619. // Animate to the radius limit
  77620. this.stopAllAnimations();
  77621. this._radiusIsAnimating = true;
  77622. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  77623. if (animatable) {
  77624. this._animatables.push(animatable);
  77625. }
  77626. };
  77627. /**
  77628. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  77629. */
  77630. BouncingBehavior.prototype._clearAnimationLocks = function () {
  77631. this._radiusIsAnimating = false;
  77632. if (this._attachedCamera) {
  77633. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  77634. }
  77635. };
  77636. /**
  77637. * Stops and removes all animations that have been applied to the camera
  77638. */
  77639. BouncingBehavior.prototype.stopAllAnimations = function () {
  77640. if (this._attachedCamera) {
  77641. this._attachedCamera.animations = [];
  77642. }
  77643. while (this._animatables.length) {
  77644. this._animatables[0].onAnimationEnd = null;
  77645. this._animatables[0].stop();
  77646. this._animatables.shift();
  77647. }
  77648. };
  77649. /**
  77650. * The easing function used by animations
  77651. */
  77652. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  77653. /**
  77654. * The easing mode used by animations
  77655. */
  77656. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  77657. return BouncingBehavior;
  77658. }());
  77659. BABYLON.BouncingBehavior = BouncingBehavior;
  77660. })(BABYLON || (BABYLON = {}));
  77661. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  77662. var BABYLON;
  77663. (function (BABYLON) {
  77664. var AutoRotationBehavior = /** @class */ (function () {
  77665. function AutoRotationBehavior() {
  77666. this._zoomStopsAnimation = false;
  77667. this._idleRotationSpeed = 0.05;
  77668. this._idleRotationWaitTime = 2000;
  77669. this._idleRotationSpinupTime = 2000;
  77670. this._isPointerDown = false;
  77671. this._lastFrameTime = null;
  77672. this._lastInteractionTime = -Infinity;
  77673. this._cameraRotationSpeed = 0;
  77674. this._lastFrameRadius = 0;
  77675. }
  77676. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  77677. get: function () {
  77678. return "AutoRotation";
  77679. },
  77680. enumerable: true,
  77681. configurable: true
  77682. });
  77683. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  77684. /**
  77685. * Gets the flag that indicates if user zooming should stop animation.
  77686. */
  77687. get: function () {
  77688. return this._zoomStopsAnimation;
  77689. },
  77690. /**
  77691. * Sets the flag that indicates if user zooming should stop animation.
  77692. */
  77693. set: function (flag) {
  77694. this._zoomStopsAnimation = flag;
  77695. },
  77696. enumerable: true,
  77697. configurable: true
  77698. });
  77699. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  77700. /**
  77701. * Gets the default speed at which the camera rotates around the model.
  77702. */
  77703. get: function () {
  77704. return this._idleRotationSpeed;
  77705. },
  77706. /**
  77707. * Sets the default speed at which the camera rotates around the model.
  77708. */
  77709. set: function (speed) {
  77710. this._idleRotationSpeed = speed;
  77711. },
  77712. enumerable: true,
  77713. configurable: true
  77714. });
  77715. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  77716. /**
  77717. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  77718. */
  77719. get: function () {
  77720. return this._idleRotationWaitTime;
  77721. },
  77722. /**
  77723. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  77724. */
  77725. set: function (time) {
  77726. this._idleRotationWaitTime = time;
  77727. },
  77728. enumerable: true,
  77729. configurable: true
  77730. });
  77731. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  77732. /**
  77733. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  77734. */
  77735. get: function () {
  77736. return this._idleRotationSpinupTime;
  77737. },
  77738. /**
  77739. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  77740. */
  77741. set: function (time) {
  77742. this._idleRotationSpinupTime = time;
  77743. },
  77744. enumerable: true,
  77745. configurable: true
  77746. });
  77747. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  77748. /**
  77749. * Gets a value indicating if the camera is currently rotating because of this behavior
  77750. */
  77751. get: function () {
  77752. return Math.abs(this._cameraRotationSpeed) > 0;
  77753. },
  77754. enumerable: true,
  77755. configurable: true
  77756. });
  77757. AutoRotationBehavior.prototype.init = function () {
  77758. // Do notihng
  77759. };
  77760. AutoRotationBehavior.prototype.attach = function (camera) {
  77761. var _this = this;
  77762. this._attachedCamera = camera;
  77763. var scene = this._attachedCamera.getScene();
  77764. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  77765. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  77766. _this._isPointerDown = true;
  77767. return;
  77768. }
  77769. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  77770. _this._isPointerDown = false;
  77771. }
  77772. });
  77773. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  77774. var now = BABYLON.Tools.Now;
  77775. var dt = 0;
  77776. if (_this._lastFrameTime != null) {
  77777. dt = now - _this._lastFrameTime;
  77778. }
  77779. _this._lastFrameTime = now;
  77780. // Stop the animation if there is user interaction and the animation should stop for this interaction
  77781. _this._applyUserInteraction();
  77782. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  77783. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  77784. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  77785. // Step camera rotation by rotation speed
  77786. if (_this._attachedCamera) {
  77787. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  77788. }
  77789. });
  77790. };
  77791. AutoRotationBehavior.prototype.detach = function () {
  77792. if (!this._attachedCamera) {
  77793. return;
  77794. }
  77795. var scene = this._attachedCamera.getScene();
  77796. if (this._onPrePointerObservableObserver) {
  77797. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  77798. }
  77799. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  77800. this._attachedCamera = null;
  77801. };
  77802. /**
  77803. * Returns true if user is scrolling.
  77804. * @return true if user is scrolling.
  77805. */
  77806. AutoRotationBehavior.prototype._userIsZooming = function () {
  77807. if (!this._attachedCamera) {
  77808. return false;
  77809. }
  77810. return this._attachedCamera.inertialRadiusOffset !== 0;
  77811. };
  77812. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  77813. if (!this._attachedCamera) {
  77814. return false;
  77815. }
  77816. var zoomHasHitLimit = false;
  77817. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  77818. zoomHasHitLimit = true;
  77819. }
  77820. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  77821. this._lastFrameRadius = this._attachedCamera.radius;
  77822. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  77823. };
  77824. /**
  77825. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  77826. */
  77827. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  77828. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  77829. this._lastInteractionTime = BABYLON.Tools.Now;
  77830. }
  77831. };
  77832. // Tools
  77833. AutoRotationBehavior.prototype._userIsMoving = function () {
  77834. if (!this._attachedCamera) {
  77835. return false;
  77836. }
  77837. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  77838. this._attachedCamera.inertialBetaOffset !== 0 ||
  77839. this._attachedCamera.inertialRadiusOffset !== 0 ||
  77840. this._attachedCamera.inertialPanningX !== 0 ||
  77841. this._attachedCamera.inertialPanningY !== 0 ||
  77842. this._isPointerDown;
  77843. };
  77844. return AutoRotationBehavior;
  77845. }());
  77846. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  77847. })(BABYLON || (BABYLON = {}));
  77848. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  77849. var BABYLON;
  77850. (function (BABYLON) {
  77851. /**
  77852. * This class can be used to get instrumentation data from a Babylon engine
  77853. */
  77854. var EngineInstrumentation = /** @class */ (function () {
  77855. function EngineInstrumentation(engine) {
  77856. this.engine = engine;
  77857. this._captureGPUFrameTime = false;
  77858. this._gpuFrameTime = new BABYLON.PerfCounter();
  77859. this._captureShaderCompilationTime = false;
  77860. this._shaderCompilationTime = new BABYLON.PerfCounter();
  77861. // Observers
  77862. this._onBeginFrameObserver = null;
  77863. this._onEndFrameObserver = null;
  77864. this._onBeforeShaderCompilationObserver = null;
  77865. this._onAfterShaderCompilationObserver = null;
  77866. }
  77867. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  77868. // Properties
  77869. /**
  77870. * Gets the perf counter used for GPU frame time
  77871. */
  77872. get: function () {
  77873. return this._gpuFrameTime;
  77874. },
  77875. enumerable: true,
  77876. configurable: true
  77877. });
  77878. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  77879. /**
  77880. * Gets the GPU frame time capture status
  77881. */
  77882. get: function () {
  77883. return this._captureGPUFrameTime;
  77884. },
  77885. /**
  77886. * Enable or disable the GPU frame time capture
  77887. */
  77888. set: function (value) {
  77889. var _this = this;
  77890. if (value === this._captureGPUFrameTime) {
  77891. return;
  77892. }
  77893. this._captureGPUFrameTime = value;
  77894. if (value) {
  77895. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  77896. if (!_this._gpuFrameTimeToken) {
  77897. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  77898. }
  77899. });
  77900. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  77901. if (!_this._gpuFrameTimeToken) {
  77902. return;
  77903. }
  77904. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  77905. if (time > -1) {
  77906. _this._gpuFrameTimeToken = null;
  77907. _this._gpuFrameTime.fetchNewFrame();
  77908. _this._gpuFrameTime.addCount(time, true);
  77909. }
  77910. });
  77911. }
  77912. else {
  77913. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  77914. this._onBeginFrameObserver = null;
  77915. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  77916. this._onEndFrameObserver = null;
  77917. }
  77918. },
  77919. enumerable: true,
  77920. configurable: true
  77921. });
  77922. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  77923. /**
  77924. * Gets the perf counter used for shader compilation time
  77925. */
  77926. get: function () {
  77927. return this._shaderCompilationTime;
  77928. },
  77929. enumerable: true,
  77930. configurable: true
  77931. });
  77932. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  77933. /**
  77934. * Gets the shader compilation time capture status
  77935. */
  77936. get: function () {
  77937. return this._captureShaderCompilationTime;
  77938. },
  77939. /**
  77940. * Enable or disable the shader compilation time capture
  77941. */
  77942. set: function (value) {
  77943. var _this = this;
  77944. if (value === this._captureShaderCompilationTime) {
  77945. return;
  77946. }
  77947. this._captureShaderCompilationTime = value;
  77948. if (value) {
  77949. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  77950. _this._shaderCompilationTime.fetchNewFrame();
  77951. _this._shaderCompilationTime.beginMonitoring();
  77952. });
  77953. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  77954. _this._shaderCompilationTime.endMonitoring();
  77955. });
  77956. }
  77957. else {
  77958. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  77959. this._onBeforeShaderCompilationObserver = null;
  77960. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  77961. this._onAfterShaderCompilationObserver = null;
  77962. }
  77963. },
  77964. enumerable: true,
  77965. configurable: true
  77966. });
  77967. EngineInstrumentation.prototype.dispose = function () {
  77968. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  77969. this._onBeginFrameObserver = null;
  77970. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  77971. this._onEndFrameObserver = null;
  77972. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  77973. this._onBeforeShaderCompilationObserver = null;
  77974. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  77975. this._onAfterShaderCompilationObserver = null;
  77976. this.engine = null;
  77977. };
  77978. return EngineInstrumentation;
  77979. }());
  77980. BABYLON.EngineInstrumentation = EngineInstrumentation;
  77981. })(BABYLON || (BABYLON = {}));
  77982. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  77983. var BABYLON;
  77984. (function (BABYLON) {
  77985. /**
  77986. * This class can be used to get instrumentation data from a Babylon engine
  77987. */
  77988. var SceneInstrumentation = /** @class */ (function () {
  77989. function SceneInstrumentation(scene) {
  77990. var _this = this;
  77991. this.scene = scene;
  77992. this._captureActiveMeshesEvaluationTime = false;
  77993. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  77994. this._captureRenderTargetsRenderTime = false;
  77995. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  77996. this._captureFrameTime = false;
  77997. this._frameTime = new BABYLON.PerfCounter();
  77998. this._captureRenderTime = false;
  77999. this._renderTime = new BABYLON.PerfCounter();
  78000. this._captureInterFrameTime = false;
  78001. this._interFrameTime = new BABYLON.PerfCounter();
  78002. this._captureParticlesRenderTime = false;
  78003. this._particlesRenderTime = new BABYLON.PerfCounter();
  78004. this._captureSpritesRenderTime = false;
  78005. this._spritesRenderTime = new BABYLON.PerfCounter();
  78006. this._capturePhysicsTime = false;
  78007. this._physicsTime = new BABYLON.PerfCounter();
  78008. this._captureAnimationsTime = false;
  78009. this._animationsTime = new BABYLON.PerfCounter();
  78010. // Observers
  78011. this._onBeforeActiveMeshesEvaluationObserver = null;
  78012. this._onAfterActiveMeshesEvaluationObserver = null;
  78013. this._onBeforeRenderTargetsRenderObserver = null;
  78014. this._onAfterRenderTargetsRenderObserver = null;
  78015. this._onAfterRenderObserver = null;
  78016. this._onBeforeDrawPhaseObserver = null;
  78017. this._onAfterDrawPhaseObserver = null;
  78018. this._onBeforeAnimationsObserver = null;
  78019. this._onBeforeParticlesRenderingObserver = null;
  78020. this._onAfterParticlesRenderingObserver = null;
  78021. this._onBeforeSpritesRenderingObserver = null;
  78022. this._onAfterSpritesRenderingObserver = null;
  78023. this._onBeforePhysicsObserver = null;
  78024. this._onAfterPhysicsObserver = null;
  78025. this._onAfterAnimationsObserver = null;
  78026. // Before render
  78027. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  78028. if (_this._captureActiveMeshesEvaluationTime) {
  78029. _this._activeMeshesEvaluationTime.fetchNewFrame();
  78030. }
  78031. if (_this._captureRenderTargetsRenderTime) {
  78032. _this._renderTargetsRenderTime.fetchNewFrame();
  78033. }
  78034. if (_this._captureFrameTime) {
  78035. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  78036. _this._frameTime.beginMonitoring();
  78037. }
  78038. if (_this._captureInterFrameTime) {
  78039. _this._interFrameTime.endMonitoring();
  78040. }
  78041. if (_this._captureParticlesRenderTime) {
  78042. _this._particlesRenderTime.fetchNewFrame();
  78043. }
  78044. if (_this._captureSpritesRenderTime) {
  78045. _this._spritesRenderTime.fetchNewFrame();
  78046. }
  78047. if (_this._captureAnimationsTime) {
  78048. _this._animationsTime.beginMonitoring();
  78049. }
  78050. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  78051. });
  78052. // After render
  78053. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  78054. if (_this._captureFrameTime) {
  78055. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  78056. _this._frameTime.endMonitoring();
  78057. }
  78058. if (_this._captureRenderTime) {
  78059. _this._renderTime.endMonitoring(false);
  78060. }
  78061. if (_this._captureInterFrameTime) {
  78062. _this._interFrameTime.beginMonitoring();
  78063. }
  78064. });
  78065. }
  78066. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  78067. // Properties
  78068. /**
  78069. * Gets the perf counter used for active meshes evaluation time
  78070. */
  78071. get: function () {
  78072. return this._activeMeshesEvaluationTime;
  78073. },
  78074. enumerable: true,
  78075. configurable: true
  78076. });
  78077. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  78078. /**
  78079. * Gets the active meshes evaluation time capture status
  78080. */
  78081. get: function () {
  78082. return this._captureActiveMeshesEvaluationTime;
  78083. },
  78084. /**
  78085. * Enable or disable the active meshes evaluation time capture
  78086. */
  78087. set: function (value) {
  78088. var _this = this;
  78089. if (value === this._captureActiveMeshesEvaluationTime) {
  78090. return;
  78091. }
  78092. this._captureActiveMeshesEvaluationTime = value;
  78093. if (value) {
  78094. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  78095. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  78096. _this._activeMeshesEvaluationTime.beginMonitoring();
  78097. });
  78098. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  78099. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  78100. _this._activeMeshesEvaluationTime.endMonitoring();
  78101. });
  78102. }
  78103. else {
  78104. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  78105. this._onBeforeActiveMeshesEvaluationObserver = null;
  78106. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  78107. this._onAfterActiveMeshesEvaluationObserver = null;
  78108. }
  78109. },
  78110. enumerable: true,
  78111. configurable: true
  78112. });
  78113. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  78114. /**
  78115. * Gets the perf counter used for render targets render time
  78116. */
  78117. get: function () {
  78118. return this._renderTargetsRenderTime;
  78119. },
  78120. enumerable: true,
  78121. configurable: true
  78122. });
  78123. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  78124. /**
  78125. * Gets the render targets render time capture status
  78126. */
  78127. get: function () {
  78128. return this._captureRenderTargetsRenderTime;
  78129. },
  78130. /**
  78131. * Enable or disable the render targets render time capture
  78132. */
  78133. set: function (value) {
  78134. var _this = this;
  78135. if (value === this._captureRenderTargetsRenderTime) {
  78136. return;
  78137. }
  78138. this._captureRenderTargetsRenderTime = value;
  78139. if (value) {
  78140. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  78141. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  78142. _this._renderTargetsRenderTime.beginMonitoring();
  78143. });
  78144. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  78145. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  78146. _this._renderTargetsRenderTime.endMonitoring(false);
  78147. });
  78148. }
  78149. else {
  78150. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  78151. this._onBeforeRenderTargetsRenderObserver = null;
  78152. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  78153. this._onAfterRenderTargetsRenderObserver = null;
  78154. }
  78155. },
  78156. enumerable: true,
  78157. configurable: true
  78158. });
  78159. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  78160. /**
  78161. * Gets the perf counter used for particles render time
  78162. */
  78163. get: function () {
  78164. return this._particlesRenderTime;
  78165. },
  78166. enumerable: true,
  78167. configurable: true
  78168. });
  78169. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  78170. /**
  78171. * Gets the particles render time capture status
  78172. */
  78173. get: function () {
  78174. return this._captureParticlesRenderTime;
  78175. },
  78176. /**
  78177. * Enable or disable the particles render time capture
  78178. */
  78179. set: function (value) {
  78180. var _this = this;
  78181. if (value === this._captureParticlesRenderTime) {
  78182. return;
  78183. }
  78184. this._captureParticlesRenderTime = value;
  78185. if (value) {
  78186. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  78187. BABYLON.Tools.StartPerformanceCounter("Particles");
  78188. _this._particlesRenderTime.beginMonitoring();
  78189. });
  78190. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  78191. BABYLON.Tools.EndPerformanceCounter("Particles");
  78192. _this._particlesRenderTime.endMonitoring(false);
  78193. });
  78194. }
  78195. else {
  78196. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  78197. this._onBeforeParticlesRenderingObserver = null;
  78198. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  78199. this._onAfterParticlesRenderingObserver = null;
  78200. }
  78201. },
  78202. enumerable: true,
  78203. configurable: true
  78204. });
  78205. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  78206. /**
  78207. * Gets the perf counter used for sprites render time
  78208. */
  78209. get: function () {
  78210. return this._spritesRenderTime;
  78211. },
  78212. enumerable: true,
  78213. configurable: true
  78214. });
  78215. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  78216. /**
  78217. * Gets the sprites render time capture status
  78218. */
  78219. get: function () {
  78220. return this._captureSpritesRenderTime;
  78221. },
  78222. /**
  78223. * Enable or disable the sprites render time capture
  78224. */
  78225. set: function (value) {
  78226. var _this = this;
  78227. if (value === this._captureSpritesRenderTime) {
  78228. return;
  78229. }
  78230. this._captureSpritesRenderTime = value;
  78231. if (value) {
  78232. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  78233. BABYLON.Tools.StartPerformanceCounter("Sprites");
  78234. _this._spritesRenderTime.beginMonitoring();
  78235. });
  78236. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  78237. BABYLON.Tools.EndPerformanceCounter("Sprites");
  78238. _this._spritesRenderTime.endMonitoring(false);
  78239. });
  78240. }
  78241. else {
  78242. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  78243. this._onBeforeSpritesRenderingObserver = null;
  78244. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  78245. this._onAfterSpritesRenderingObserver = null;
  78246. }
  78247. },
  78248. enumerable: true,
  78249. configurable: true
  78250. });
  78251. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  78252. /**
  78253. * Gets the perf counter used for physics time
  78254. */
  78255. get: function () {
  78256. return this._physicsTime;
  78257. },
  78258. enumerable: true,
  78259. configurable: true
  78260. });
  78261. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  78262. /**
  78263. * Gets the physics time capture status
  78264. */
  78265. get: function () {
  78266. return this._capturePhysicsTime;
  78267. },
  78268. /**
  78269. * Enable or disable the physics time capture
  78270. */
  78271. set: function (value) {
  78272. var _this = this;
  78273. if (value === this._capturePhysicsTime) {
  78274. return;
  78275. }
  78276. this._capturePhysicsTime = value;
  78277. if (value) {
  78278. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  78279. BABYLON.Tools.StartPerformanceCounter("Physics");
  78280. _this._physicsTime.beginMonitoring();
  78281. });
  78282. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  78283. BABYLON.Tools.EndPerformanceCounter("Physics");
  78284. _this._physicsTime.endMonitoring();
  78285. });
  78286. }
  78287. else {
  78288. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  78289. this._onBeforePhysicsObserver = null;
  78290. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  78291. this._onAfterPhysicsObserver = null;
  78292. }
  78293. },
  78294. enumerable: true,
  78295. configurable: true
  78296. });
  78297. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  78298. /**
  78299. * Gets the perf counter used for animations time
  78300. */
  78301. get: function () {
  78302. return this._animationsTime;
  78303. },
  78304. enumerable: true,
  78305. configurable: true
  78306. });
  78307. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  78308. /**
  78309. * Gets the animations time capture status
  78310. */
  78311. get: function () {
  78312. return this._captureAnimationsTime;
  78313. },
  78314. /**
  78315. * Enable or disable the animations time capture
  78316. */
  78317. set: function (value) {
  78318. var _this = this;
  78319. if (value === this._captureAnimationsTime) {
  78320. return;
  78321. }
  78322. this._captureAnimationsTime = value;
  78323. if (value) {
  78324. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  78325. _this._animationsTime.endMonitoring();
  78326. });
  78327. }
  78328. else {
  78329. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  78330. this._onAfterAnimationsObserver = null;
  78331. }
  78332. },
  78333. enumerable: true,
  78334. configurable: true
  78335. });
  78336. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  78337. /**
  78338. * Gets the perf counter used for frame time capture
  78339. */
  78340. get: function () {
  78341. return this._frameTime;
  78342. },
  78343. enumerable: true,
  78344. configurable: true
  78345. });
  78346. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  78347. /**
  78348. * Gets the frame time capture status
  78349. */
  78350. get: function () {
  78351. return this._captureFrameTime;
  78352. },
  78353. /**
  78354. * Enable or disable the frame time capture
  78355. */
  78356. set: function (value) {
  78357. this._captureFrameTime = value;
  78358. },
  78359. enumerable: true,
  78360. configurable: true
  78361. });
  78362. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  78363. /**
  78364. * Gets the perf counter used for inter-frames time capture
  78365. */
  78366. get: function () {
  78367. return this._interFrameTime;
  78368. },
  78369. enumerable: true,
  78370. configurable: true
  78371. });
  78372. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  78373. /**
  78374. * Gets the inter-frames time capture status
  78375. */
  78376. get: function () {
  78377. return this._captureInterFrameTime;
  78378. },
  78379. /**
  78380. * Enable or disable the inter-frames time capture
  78381. */
  78382. set: function (value) {
  78383. this._captureInterFrameTime = value;
  78384. },
  78385. enumerable: true,
  78386. configurable: true
  78387. });
  78388. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  78389. /**
  78390. * Gets the perf counter used for render time capture
  78391. */
  78392. get: function () {
  78393. return this._renderTime;
  78394. },
  78395. enumerable: true,
  78396. configurable: true
  78397. });
  78398. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  78399. /**
  78400. * Gets the render time capture status
  78401. */
  78402. get: function () {
  78403. return this._captureRenderTime;
  78404. },
  78405. /**
  78406. * Enable or disable the render time capture
  78407. */
  78408. set: function (value) {
  78409. var _this = this;
  78410. if (value === this._captureRenderTime) {
  78411. return;
  78412. }
  78413. this._captureRenderTime = value;
  78414. if (value) {
  78415. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  78416. _this._renderTime.beginMonitoring();
  78417. BABYLON.Tools.StartPerformanceCounter("Main render");
  78418. });
  78419. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  78420. _this._renderTime.endMonitoring(false);
  78421. BABYLON.Tools.EndPerformanceCounter("Main render");
  78422. });
  78423. }
  78424. else {
  78425. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  78426. this._onBeforeDrawPhaseObserver = null;
  78427. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  78428. this._onAfterDrawPhaseObserver = null;
  78429. }
  78430. },
  78431. enumerable: true,
  78432. configurable: true
  78433. });
  78434. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  78435. /**
  78436. * Gets the perf counter used for frame time capture
  78437. */
  78438. get: function () {
  78439. return this.scene.getEngine()._drawCalls;
  78440. },
  78441. enumerable: true,
  78442. configurable: true
  78443. });
  78444. SceneInstrumentation.prototype.dispose = function () {
  78445. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  78446. this._onAfterRenderObserver = null;
  78447. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  78448. this._onBeforeActiveMeshesEvaluationObserver = null;
  78449. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  78450. this._onAfterActiveMeshesEvaluationObserver = null;
  78451. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  78452. this._onBeforeRenderTargetsRenderObserver = null;
  78453. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  78454. this._onAfterRenderTargetsRenderObserver = null;
  78455. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  78456. this._onBeforeAnimationsObserver = null;
  78457. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  78458. this._onBeforeParticlesRenderingObserver = null;
  78459. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  78460. this._onAfterParticlesRenderingObserver = null;
  78461. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  78462. this._onBeforeSpritesRenderingObserver = null;
  78463. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  78464. this._onAfterSpritesRenderingObserver = null;
  78465. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  78466. this._onBeforeDrawPhaseObserver = null;
  78467. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  78468. this._onAfterDrawPhaseObserver = null;
  78469. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  78470. this._onBeforePhysicsObserver = null;
  78471. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  78472. this._onAfterPhysicsObserver = null;
  78473. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  78474. this._onAfterAnimationsObserver = null;
  78475. this.scene = null;
  78476. };
  78477. return SceneInstrumentation;
  78478. }());
  78479. BABYLON.SceneInstrumentation = SceneInstrumentation;
  78480. })(BABYLON || (BABYLON = {}));
  78481. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  78482. var BABYLON;
  78483. (function (BABYLON) {
  78484. var _TimeToken = /** @class */ (function () {
  78485. function _TimeToken() {
  78486. this._timeElapsedQueryEnded = false;
  78487. }
  78488. return _TimeToken;
  78489. }());
  78490. BABYLON._TimeToken = _TimeToken;
  78491. })(BABYLON || (BABYLON = {}));
  78492. //# sourceMappingURL=babylon.timeToken.js.map
  78493. var BABYLON;
  78494. (function (BABYLON) {
  78495. /**
  78496. * Background material defines definition.
  78497. */
  78498. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  78499. __extends(BackgroundMaterialDefines, _super);
  78500. /**
  78501. * Constructor of the defines.
  78502. */
  78503. function BackgroundMaterialDefines() {
  78504. var _this = _super.call(this) || this;
  78505. /**
  78506. * True if the diffuse texture is in use.
  78507. */
  78508. _this.DIFFUSE = false;
  78509. /**
  78510. * The direct UV channel to use.
  78511. */
  78512. _this.DIFFUSEDIRECTUV = 0;
  78513. /**
  78514. * True if the diffuse texture is in gamma space.
  78515. */
  78516. _this.GAMMADIFFUSE = false;
  78517. /**
  78518. * True if the diffuse texture has opacity in the alpha channel.
  78519. */
  78520. _this.DIFFUSEHASALPHA = false;
  78521. /**
  78522. * True if you want the material to fade to transparent at grazing angle.
  78523. */
  78524. _this.OPACITYFRESNEL = false;
  78525. /**
  78526. * True if an extra blur needs to be added in the reflection.
  78527. */
  78528. _this.REFLECTIONBLUR = false;
  78529. /**
  78530. * True if you want the material to fade to reflection at grazing angle.
  78531. */
  78532. _this.REFLECTIONFRESNEL = false;
  78533. /**
  78534. * True if you want the material to falloff as far as you move away from the scene center.
  78535. */
  78536. _this.REFLECTIONFALLOFF = false;
  78537. /**
  78538. * False if the current Webgl implementation does not support the texture lod extension.
  78539. */
  78540. _this.TEXTURELODSUPPORT = false;
  78541. /**
  78542. * True to ensure the data are premultiplied.
  78543. */
  78544. _this.PREMULTIPLYALPHA = false;
  78545. /**
  78546. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  78547. */
  78548. _this.USERGBCOLOR = false;
  78549. /**
  78550. * True to add noise in order to reduce the banding effect.
  78551. */
  78552. _this.NOISE = false;
  78553. // Image Processing Configuration.
  78554. _this.IMAGEPROCESSING = false;
  78555. _this.VIGNETTE = false;
  78556. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  78557. _this.VIGNETTEBLENDMODEOPAQUE = false;
  78558. _this.TONEMAPPING = false;
  78559. _this.CONTRAST = false;
  78560. _this.COLORCURVES = false;
  78561. _this.COLORGRADING = false;
  78562. _this.COLORGRADING3D = false;
  78563. _this.SAMPLER3DGREENDEPTH = false;
  78564. _this.SAMPLER3DBGRMAP = false;
  78565. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  78566. _this.EXPOSURE = false;
  78567. // Reflection.
  78568. _this.REFLECTION = false;
  78569. _this.REFLECTIONMAP_3D = false;
  78570. _this.REFLECTIONMAP_SPHERICAL = false;
  78571. _this.REFLECTIONMAP_PLANAR = false;
  78572. _this.REFLECTIONMAP_CUBIC = false;
  78573. _this.REFLECTIONMAP_PROJECTION = false;
  78574. _this.REFLECTIONMAP_SKYBOX = false;
  78575. _this.REFLECTIONMAP_EXPLICIT = false;
  78576. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  78577. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  78578. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  78579. _this.INVERTCUBICMAP = false;
  78580. _this.REFLECTIONMAP_OPPOSITEZ = false;
  78581. _this.LODINREFLECTIONALPHA = false;
  78582. _this.GAMMAREFLECTION = false;
  78583. // Default BJS.
  78584. _this.MAINUV1 = false;
  78585. _this.MAINUV2 = false;
  78586. _this.UV1 = false;
  78587. _this.UV2 = false;
  78588. _this.CLIPPLANE = false;
  78589. _this.POINTSIZE = false;
  78590. _this.FOG = false;
  78591. _this.NORMAL = false;
  78592. _this.NUM_BONE_INFLUENCERS = 0;
  78593. _this.BonesPerMesh = 0;
  78594. _this.INSTANCES = false;
  78595. _this.SHADOWFLOAT = false;
  78596. _this.rebuild();
  78597. return _this;
  78598. }
  78599. return BackgroundMaterialDefines;
  78600. }(BABYLON.MaterialDefines));
  78601. /**
  78602. * Background material used to create an efficient environement around your scene.
  78603. */
  78604. var BackgroundMaterial = /** @class */ (function (_super) {
  78605. __extends(BackgroundMaterial, _super);
  78606. /**
  78607. * constructor
  78608. * @param name The name of the material
  78609. * @param scene The scene to add the material to
  78610. */
  78611. function BackgroundMaterial(name, scene) {
  78612. var _this = _super.call(this, name, scene) || this;
  78613. _this.primaryColor = BABYLON.Color3.White();
  78614. _this.primaryLevel = 1;
  78615. _this.secondaryColor = BABYLON.Color3.Gray();
  78616. _this.secondaryLevel = 1;
  78617. _this.tertiaryColor = BABYLON.Color3.Black();
  78618. _this.tertiaryLevel = 1;
  78619. _this.reflectionTexture = null;
  78620. _this.reflectionBlur = 0;
  78621. _this.diffuseTexture = null;
  78622. /**
  78623. * Specify the list of lights casting shadow on the material.
  78624. * All scene shadow lights will be included if null.
  78625. */
  78626. _this._shadowLights = null;
  78627. _this.shadowLights = null;
  78628. _this.shadowBlurScale = 1;
  78629. _this.shadowLevel = 0;
  78630. _this.sceneCenter = BABYLON.Vector3.Zero();
  78631. _this.opacityFresnel = true;
  78632. _this.reflectionFresnel = false;
  78633. _this.reflectionFalloffDistance = 0.0;
  78634. _this.reflectionAmount = 1.0;
  78635. _this.reflectionReflectance0 = 0.05;
  78636. _this.reflectionReflectance90 = 0.5;
  78637. _this.useRGBColor = true;
  78638. _this.enableNoise = false;
  78639. /**
  78640. * Number of Simultaneous lights allowed on the material.
  78641. */
  78642. _this._maxSimultaneousLights = 4;
  78643. _this.maxSimultaneousLights = 4;
  78644. /**
  78645. * Keep track of the image processing observer to allow dispose and replace.
  78646. */
  78647. _this._imageProcessingObserver = null;
  78648. // Temp values kept as cache in the material.
  78649. _this._renderTargets = new BABYLON.SmartArray(16);
  78650. _this._reflectionControls = BABYLON.Vector4.Zero();
  78651. // Setup the default processing configuration to the scene.
  78652. _this._attachImageProcessingConfiguration(null);
  78653. _this.getRenderTargetTextures = function () {
  78654. _this._renderTargets.reset();
  78655. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  78656. _this._renderTargets.push(_this._diffuseTexture);
  78657. }
  78658. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  78659. _this._renderTargets.push(_this._reflectionTexture);
  78660. }
  78661. return _this._renderTargets;
  78662. };
  78663. return _this;
  78664. }
  78665. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  78666. /**
  78667. * Sets the reflection reflectance fresnel values according to the default standard
  78668. * empirically know to work well :-)
  78669. */
  78670. set: function (value) {
  78671. var reflectionWeight = value;
  78672. if (reflectionWeight < 0.5) {
  78673. reflectionWeight = reflectionWeight * 2.0;
  78674. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 * reflectionWeight;
  78675. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 * reflectionWeight;
  78676. }
  78677. else {
  78678. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  78679. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 + (1.0 - BackgroundMaterial.standardReflectance0) * reflectionWeight;
  78680. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 + (1.0 - BackgroundMaterial.standardReflectance90) * reflectionWeight;
  78681. }
  78682. },
  78683. enumerable: true,
  78684. configurable: true
  78685. });
  78686. /**
  78687. * Attaches a new image processing configuration to the PBR Material.
  78688. * @param configuration (if null the scene configuration will be use)
  78689. */
  78690. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  78691. var _this = this;
  78692. if (configuration === this._imageProcessingConfiguration) {
  78693. return;
  78694. }
  78695. // Detaches observer.
  78696. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  78697. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  78698. }
  78699. // Pick the scene configuration if needed.
  78700. if (!configuration) {
  78701. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  78702. }
  78703. else {
  78704. this._imageProcessingConfiguration = configuration;
  78705. }
  78706. // Attaches observer.
  78707. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  78708. _this._markAllSubMeshesAsImageProcessingDirty();
  78709. });
  78710. };
  78711. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  78712. /**
  78713. * Gets the image processing configuration used either in this material.
  78714. */
  78715. get: function () {
  78716. return this._imageProcessingConfiguration;
  78717. },
  78718. /**
  78719. * Sets the Default image processing configuration used either in the this material.
  78720. *
  78721. * If sets to null, the scene one is in use.
  78722. */
  78723. set: function (value) {
  78724. this._attachImageProcessingConfiguration(value);
  78725. // Ensure the effect will be rebuilt.
  78726. this._markAllSubMeshesAsTexturesDirty();
  78727. },
  78728. enumerable: true,
  78729. configurable: true
  78730. });
  78731. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  78732. /**
  78733. * Gets wether the color curves effect is enabled.
  78734. */
  78735. get: function () {
  78736. return this.imageProcessingConfiguration.colorCurvesEnabled;
  78737. },
  78738. /**
  78739. * Sets wether the color curves effect is enabled.
  78740. */
  78741. set: function (value) {
  78742. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  78743. },
  78744. enumerable: true,
  78745. configurable: true
  78746. });
  78747. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  78748. /**
  78749. * Gets wether the color grading effect is enabled.
  78750. */
  78751. get: function () {
  78752. return this.imageProcessingConfiguration.colorGradingEnabled;
  78753. },
  78754. /**
  78755. * Gets wether the color grading effect is enabled.
  78756. */
  78757. set: function (value) {
  78758. this.imageProcessingConfiguration.colorGradingEnabled = value;
  78759. },
  78760. enumerable: true,
  78761. configurable: true
  78762. });
  78763. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  78764. /**
  78765. * Gets wether tonemapping is enabled or not.
  78766. */
  78767. get: function () {
  78768. return this._imageProcessingConfiguration.toneMappingEnabled;
  78769. },
  78770. /**
  78771. * Sets wether tonemapping is enabled or not
  78772. */
  78773. set: function (value) {
  78774. this._imageProcessingConfiguration.toneMappingEnabled = value;
  78775. },
  78776. enumerable: true,
  78777. configurable: true
  78778. });
  78779. ;
  78780. ;
  78781. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  78782. /**
  78783. * The camera exposure used on this material.
  78784. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  78785. * This corresponds to a photographic exposure.
  78786. */
  78787. get: function () {
  78788. return this._imageProcessingConfiguration.exposure;
  78789. },
  78790. /**
  78791. * The camera exposure used on this material.
  78792. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  78793. * This corresponds to a photographic exposure.
  78794. */
  78795. set: function (value) {
  78796. this._imageProcessingConfiguration.exposure = value;
  78797. },
  78798. enumerable: true,
  78799. configurable: true
  78800. });
  78801. ;
  78802. ;
  78803. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  78804. /**
  78805. * Gets The camera contrast used on this material.
  78806. */
  78807. get: function () {
  78808. return this._imageProcessingConfiguration.contrast;
  78809. },
  78810. /**
  78811. * Sets The camera contrast used on this material.
  78812. */
  78813. set: function (value) {
  78814. this._imageProcessingConfiguration.contrast = value;
  78815. },
  78816. enumerable: true,
  78817. configurable: true
  78818. });
  78819. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  78820. /**
  78821. * Gets the Color Grading 2D Lookup Texture.
  78822. */
  78823. get: function () {
  78824. return this._imageProcessingConfiguration.colorGradingTexture;
  78825. },
  78826. /**
  78827. * Sets the Color Grading 2D Lookup Texture.
  78828. */
  78829. set: function (value) {
  78830. this.imageProcessingConfiguration.colorGradingTexture = value;
  78831. },
  78832. enumerable: true,
  78833. configurable: true
  78834. });
  78835. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  78836. /**
  78837. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  78838. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  78839. * 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;
  78840. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  78841. */
  78842. get: function () {
  78843. return this.imageProcessingConfiguration.colorCurves;
  78844. },
  78845. /**
  78846. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  78847. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  78848. * 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;
  78849. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  78850. */
  78851. set: function (value) {
  78852. this.imageProcessingConfiguration.colorCurves = value;
  78853. },
  78854. enumerable: true,
  78855. configurable: true
  78856. });
  78857. /**
  78858. * The entire material has been created in order to prevent overdraw.
  78859. * @returns false
  78860. */
  78861. BackgroundMaterial.prototype.needAlphaTesting = function () {
  78862. return true;
  78863. };
  78864. /**
  78865. * The entire material has been created in order to prevent overdraw.
  78866. * @returns true if blending is enable
  78867. */
  78868. BackgroundMaterial.prototype.needAlphaBlending = function () {
  78869. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  78870. };
  78871. /**
  78872. * Checks wether the material is ready to be rendered for a given mesh.
  78873. * @param mesh The mesh to render
  78874. * @param subMesh The submesh to check against
  78875. * @param useInstances Specify wether or not the material is used with instances
  78876. */
  78877. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  78878. var _this = this;
  78879. if (useInstances === void 0) { useInstances = false; }
  78880. if (subMesh.effect && this.isFrozen) {
  78881. if (this._wasPreviouslyReady) {
  78882. return true;
  78883. }
  78884. }
  78885. if (!subMesh._materialDefines) {
  78886. subMesh._materialDefines = new BackgroundMaterialDefines();
  78887. }
  78888. var scene = this.getScene();
  78889. var defines = subMesh._materialDefines;
  78890. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  78891. if (defines._renderId === scene.getRenderId()) {
  78892. return true;
  78893. }
  78894. }
  78895. var engine = scene.getEngine();
  78896. // Lights
  78897. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  78898. defines._needNormals = true;
  78899. // Textures
  78900. if (defines._areTexturesDirty) {
  78901. defines._needUVs = false;
  78902. if (scene.texturesEnabled) {
  78903. if (scene.getEngine().getCaps().textureLOD) {
  78904. defines.TEXTURELODSUPPORT = true;
  78905. }
  78906. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  78907. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  78908. return false;
  78909. }
  78910. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  78911. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  78912. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  78913. defines.OPACITYFRESNEL = this._opacityFresnel;
  78914. }
  78915. else {
  78916. defines.DIFFUSE = false;
  78917. defines.DIFFUSEHASALPHA = false;
  78918. defines.GAMMADIFFUSE = false;
  78919. defines.OPACITYFRESNEL = false;
  78920. }
  78921. var reflectionTexture = this._reflectionTexture;
  78922. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  78923. if (!reflectionTexture.isReadyOrNotBlocking()) {
  78924. return false;
  78925. }
  78926. defines.REFLECTION = true;
  78927. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  78928. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  78929. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  78930. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  78931. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  78932. defines.INVERTCUBICMAP = true;
  78933. }
  78934. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  78935. switch (reflectionTexture.coordinatesMode) {
  78936. case BABYLON.Texture.CUBIC_MODE:
  78937. case BABYLON.Texture.INVCUBIC_MODE:
  78938. defines.REFLECTIONMAP_CUBIC = true;
  78939. break;
  78940. case BABYLON.Texture.EXPLICIT_MODE:
  78941. defines.REFLECTIONMAP_EXPLICIT = true;
  78942. break;
  78943. case BABYLON.Texture.PLANAR_MODE:
  78944. defines.REFLECTIONMAP_PLANAR = true;
  78945. break;
  78946. case BABYLON.Texture.PROJECTION_MODE:
  78947. defines.REFLECTIONMAP_PROJECTION = true;
  78948. break;
  78949. case BABYLON.Texture.SKYBOX_MODE:
  78950. defines.REFLECTIONMAP_SKYBOX = true;
  78951. break;
  78952. case BABYLON.Texture.SPHERICAL_MODE:
  78953. defines.REFLECTIONMAP_SPHERICAL = true;
  78954. break;
  78955. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  78956. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  78957. break;
  78958. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  78959. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  78960. break;
  78961. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  78962. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  78963. break;
  78964. }
  78965. if (this.reflectionFresnel) {
  78966. defines.REFLECTIONFRESNEL = true;
  78967. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  78968. this._reflectionControls.x = this.reflectionAmount;
  78969. this._reflectionControls.y = this.reflectionReflectance0;
  78970. this._reflectionControls.z = this.reflectionReflectance90;
  78971. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  78972. }
  78973. else {
  78974. defines.REFLECTIONFRESNEL = false;
  78975. defines.REFLECTIONFALLOFF = false;
  78976. }
  78977. }
  78978. else {
  78979. defines.REFLECTION = false;
  78980. defines.REFLECTIONFALLOFF = false;
  78981. defines.REFLECTIONBLUR = false;
  78982. defines.REFLECTIONMAP_3D = false;
  78983. defines.REFLECTIONMAP_SPHERICAL = false;
  78984. defines.REFLECTIONMAP_PLANAR = false;
  78985. defines.REFLECTIONMAP_CUBIC = false;
  78986. defines.REFLECTIONMAP_PROJECTION = false;
  78987. defines.REFLECTIONMAP_SKYBOX = false;
  78988. defines.REFLECTIONMAP_EXPLICIT = false;
  78989. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  78990. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  78991. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  78992. defines.INVERTCUBICMAP = false;
  78993. defines.REFLECTIONMAP_OPPOSITEZ = false;
  78994. defines.LODINREFLECTIONALPHA = false;
  78995. defines.GAMMAREFLECTION = false;
  78996. }
  78997. }
  78998. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  78999. defines.USERGBCOLOR = this._useRGBColor;
  79000. defines.NOISE = this._enableNoise;
  79001. }
  79002. if (defines._areImageProcessingDirty) {
  79003. if (!this._imageProcessingConfiguration.isReady()) {
  79004. return false;
  79005. }
  79006. this._imageProcessingConfiguration.prepareDefines(defines);
  79007. }
  79008. // Misc.
  79009. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, defines);
  79010. // Values that need to be evaluated on every frame
  79011. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, false);
  79012. // Attribs
  79013. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  79014. if (mesh) {
  79015. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  79016. mesh.createNormals(true);
  79017. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  79018. }
  79019. }
  79020. }
  79021. // Get correct effect
  79022. if (defines.isDirty) {
  79023. defines.markAsProcessed();
  79024. scene.resetCachedMaterial();
  79025. // Fallbacks
  79026. var fallbacks = new BABYLON.EffectFallbacks();
  79027. if (defines.FOG) {
  79028. fallbacks.addFallback(0, "FOG");
  79029. }
  79030. if (defines.POINTSIZE) {
  79031. fallbacks.addFallback(1, "POINTSIZE");
  79032. }
  79033. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  79034. if (defines.NUM_BONE_INFLUENCERS > 0) {
  79035. fallbacks.addCPUSkinningFallback(0, mesh);
  79036. }
  79037. //Attributes
  79038. var attribs = [BABYLON.VertexBuffer.PositionKind];
  79039. if (defines.NORMAL) {
  79040. attribs.push(BABYLON.VertexBuffer.NormalKind);
  79041. }
  79042. if (defines.UV1) {
  79043. attribs.push(BABYLON.VertexBuffer.UVKind);
  79044. }
  79045. if (defines.UV2) {
  79046. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  79047. }
  79048. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  79049. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  79050. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  79051. "vFogInfos", "vFogColor", "pointSize",
  79052. "vClipPlane", "mBones",
  79053. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  79054. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  79055. "shadowLevel", "alpha",
  79056. "vBackgroundCenter", "vReflectionControl",
  79057. "vDiffuseInfos", "diffuseMatrix",
  79058. ];
  79059. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  79060. var uniformBuffers = ["Material", "Scene"];
  79061. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  79062. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  79063. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  79064. uniformsNames: uniforms,
  79065. uniformBuffersNames: uniformBuffers,
  79066. samplers: samplers,
  79067. defines: defines,
  79068. maxSimultaneousLights: this._maxSimultaneousLights
  79069. });
  79070. var onCompiled = function (effect) {
  79071. if (_this.onCompiled) {
  79072. _this.onCompiled(effect);
  79073. }
  79074. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  79075. };
  79076. var join = defines.toString();
  79077. subMesh.setEffect(scene.getEngine().createEffect("background", {
  79078. attributes: attribs,
  79079. uniformsNames: uniforms,
  79080. uniformBuffersNames: uniformBuffers,
  79081. samplers: samplers,
  79082. defines: join,
  79083. fallbacks: fallbacks,
  79084. onCompiled: onCompiled,
  79085. onError: this.onError,
  79086. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  79087. }, engine), defines);
  79088. this.buildUniformLayout();
  79089. }
  79090. if (!subMesh.effect || !subMesh.effect.isReady()) {
  79091. return false;
  79092. }
  79093. defines._renderId = scene.getRenderId();
  79094. this._wasPreviouslyReady = true;
  79095. return true;
  79096. };
  79097. /**
  79098. * Build the uniform buffer used in the material.
  79099. */
  79100. BackgroundMaterial.prototype.buildUniformLayout = function () {
  79101. // Order is important !
  79102. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  79103. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  79104. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  79105. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  79106. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  79107. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  79108. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  79109. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  79110. this._uniformBuffer.addUniform("pointSize", 1);
  79111. this._uniformBuffer.addUniform("shadowLevel", 1);
  79112. this._uniformBuffer.addUniform("alpha", 1);
  79113. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  79114. this._uniformBuffer.addUniform("vReflectionControl", 4);
  79115. this._uniformBuffer.create();
  79116. };
  79117. /**
  79118. * Unbind the material.
  79119. */
  79120. BackgroundMaterial.prototype.unbind = function () {
  79121. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  79122. this._uniformBuffer.setTexture("diffuseSampler", null);
  79123. }
  79124. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  79125. this._uniformBuffer.setTexture("reflectionSampler", null);
  79126. }
  79127. _super.prototype.unbind.call(this);
  79128. };
  79129. /**
  79130. * Bind only the world matrix to the material.
  79131. * @param world The world matrix to bind.
  79132. */
  79133. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  79134. this._activeEffect.setMatrix("world", world);
  79135. };
  79136. /**
  79137. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  79138. * @param world The world matrix to bind.
  79139. * @param subMesh The submesh to bind for.
  79140. */
  79141. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  79142. var scene = this.getScene();
  79143. var defines = subMesh._materialDefines;
  79144. if (!defines) {
  79145. return;
  79146. }
  79147. var effect = subMesh.effect;
  79148. if (!effect) {
  79149. return;
  79150. }
  79151. this._activeEffect = effect;
  79152. // Matrices
  79153. this.bindOnlyWorldMatrix(world);
  79154. // Bones
  79155. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  79156. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  79157. if (mustRebind) {
  79158. this._uniformBuffer.bindToEffect(effect, "Material");
  79159. this.bindViewProjection(effect);
  79160. var reflectionTexture = this._reflectionTexture;
  79161. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  79162. // Texture uniforms
  79163. if (scene.texturesEnabled) {
  79164. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  79165. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  79166. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  79167. }
  79168. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  79169. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  79170. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  79171. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  79172. }
  79173. }
  79174. if (this.shadowLevel > 0) {
  79175. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  79176. }
  79177. this._uniformBuffer.updateFloat("alpha", this.alpha);
  79178. // Point size
  79179. if (this.pointsCloud) {
  79180. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  79181. }
  79182. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  79183. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  79184. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  79185. }
  79186. // Textures
  79187. if (scene.texturesEnabled) {
  79188. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  79189. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  79190. }
  79191. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  79192. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  79193. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  79194. }
  79195. else if (!defines.REFLECTIONBLUR) {
  79196. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  79197. }
  79198. else {
  79199. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  79200. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  79201. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  79202. }
  79203. if (defines.REFLECTIONFRESNEL) {
  79204. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  79205. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  79206. }
  79207. }
  79208. }
  79209. // Clip plane
  79210. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  79211. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  79212. }
  79213. if (mustRebind || !this.isFrozen) {
  79214. if (scene.lightsEnabled) {
  79215. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  79216. }
  79217. // View
  79218. this.bindView(effect);
  79219. // Fog
  79220. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  79221. // image processing
  79222. this._imageProcessingConfiguration.bind(this._activeEffect);
  79223. }
  79224. this._uniformBuffer.update();
  79225. this._afterBind(mesh);
  79226. };
  79227. /**
  79228. * Dispose the material.
  79229. * @forceDisposeEffect Force disposal of the associated effect.
  79230. * @forceDisposeTextures Force disposal of the associated textures.
  79231. */
  79232. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  79233. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  79234. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  79235. if (forceDisposeTextures) {
  79236. if (this.diffuseTexture) {
  79237. this.diffuseTexture.dispose();
  79238. }
  79239. if (this.reflectionTexture) {
  79240. this.reflectionTexture.dispose();
  79241. }
  79242. }
  79243. this._renderTargets.dispose();
  79244. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  79245. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  79246. }
  79247. _super.prototype.dispose.call(this, forceDisposeEffect);
  79248. };
  79249. /**
  79250. * Clones the material.
  79251. * @name The cloned name.
  79252. * @returns The cloned material.
  79253. */
  79254. BackgroundMaterial.prototype.clone = function (name) {
  79255. var _this = this;
  79256. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  79257. };
  79258. /**
  79259. * Serializes the current material to its JSON representation.
  79260. * @returns The JSON representation.
  79261. */
  79262. BackgroundMaterial.prototype.serialize = function () {
  79263. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  79264. serializationObject.customType = "BABYLON.BackgroundMaterial";
  79265. return serializationObject;
  79266. };
  79267. /**
  79268. * Gets the class name of the material
  79269. * @returns "BackgroundMaterial"
  79270. */
  79271. BackgroundMaterial.prototype.getClassName = function () {
  79272. return "BackgroundMaterial";
  79273. };
  79274. /**
  79275. * Parse a JSON input to create back a background material.
  79276. * @param source
  79277. * @param scene
  79278. * @param rootUrl
  79279. * @returns the instantiated BackgroundMaterial.
  79280. */
  79281. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  79282. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  79283. };
  79284. /**
  79285. * Standard reflectance value at parallel view angle.
  79286. */
  79287. BackgroundMaterial.standardReflectance0 = 0.05;
  79288. /**
  79289. * Standard reflectance value at grazing angle.
  79290. */
  79291. BackgroundMaterial.standardReflectance90 = 0.5;
  79292. __decorate([
  79293. BABYLON.serializeAsColor3()
  79294. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  79295. __decorate([
  79296. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  79297. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  79298. __decorate([
  79299. BABYLON.serialize()
  79300. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  79301. __decorate([
  79302. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  79303. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  79304. __decorate([
  79305. BABYLON.serializeAsColor3()
  79306. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  79307. __decorate([
  79308. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  79309. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  79310. __decorate([
  79311. BABYLON.serialize()
  79312. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  79313. __decorate([
  79314. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  79315. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  79316. __decorate([
  79317. BABYLON.serializeAsColor3()
  79318. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  79319. __decorate([
  79320. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  79321. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  79322. __decorate([
  79323. BABYLON.serialize()
  79324. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  79325. __decorate([
  79326. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  79327. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  79328. __decorate([
  79329. BABYLON.serializeAsTexture()
  79330. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  79331. __decorate([
  79332. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79333. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  79334. __decorate([
  79335. BABYLON.serialize()
  79336. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  79337. __decorate([
  79338. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79339. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  79340. __decorate([
  79341. BABYLON.serializeAsTexture()
  79342. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  79343. __decorate([
  79344. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79345. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  79346. __decorate([
  79347. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79348. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  79349. __decorate([
  79350. BABYLON.serialize()
  79351. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  79352. __decorate([
  79353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79354. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  79355. __decorate([
  79356. BABYLON.serialize()
  79357. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  79358. __decorate([
  79359. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79360. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  79361. __decorate([
  79362. BABYLON.serializeAsVector3()
  79363. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  79364. __decorate([
  79365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79366. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  79367. __decorate([
  79368. BABYLON.serialize()
  79369. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  79370. __decorate([
  79371. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79372. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  79373. __decorate([
  79374. BABYLON.serialize()
  79375. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  79376. __decorate([
  79377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79378. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  79379. __decorate([
  79380. BABYLON.serialize()
  79381. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  79382. __decorate([
  79383. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79384. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  79385. __decorate([
  79386. BABYLON.serialize()
  79387. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  79388. __decorate([
  79389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79390. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  79391. __decorate([
  79392. BABYLON.serialize()
  79393. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  79394. __decorate([
  79395. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79396. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  79397. __decorate([
  79398. BABYLON.serialize()
  79399. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  79400. __decorate([
  79401. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79402. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  79403. __decorate([
  79404. BABYLON.serialize()
  79405. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  79406. __decorate([
  79407. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79408. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  79409. __decorate([
  79410. BABYLON.serialize()
  79411. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  79412. __decorate([
  79413. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79414. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  79415. __decorate([
  79416. BABYLON.serialize()
  79417. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  79418. __decorate([
  79419. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79420. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  79421. __decorate([
  79422. BABYLON.serializeAsImageProcessingConfiguration()
  79423. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  79424. return BackgroundMaterial;
  79425. }(BABYLON.PushMaterial));
  79426. BABYLON.BackgroundMaterial = BackgroundMaterial;
  79427. })(BABYLON || (BABYLON = {}));
  79428. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  79429. var __assign = (this && this.__assign) || Object.assign || function(t) {
  79430. for (var s, i = 1, n = arguments.length; i < n; i++) {
  79431. s = arguments[i];
  79432. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  79433. t[p] = s[p];
  79434. }
  79435. return t;
  79436. };
  79437. var BABYLON;
  79438. (function (BABYLON) {
  79439. /**
  79440. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  79441. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  79442. * It also helps with the default setup of your imageProcessing configuration.
  79443. */
  79444. var EnvironmentHelper = /** @class */ (function () {
  79445. /**
  79446. * constructor
  79447. * @param options
  79448. * @param scene The scene to add the material to
  79449. */
  79450. function EnvironmentHelper(options, scene) {
  79451. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  79452. this._scene = scene;
  79453. this._setupBackground();
  79454. this._setupImageProcessing();
  79455. }
  79456. /**
  79457. * Creates the default options for the helper.
  79458. */
  79459. EnvironmentHelper._getDefaultOptions = function () {
  79460. return {
  79461. createGround: true,
  79462. groundSize: 15,
  79463. groundTexture: this._groundTextureCDNUrl,
  79464. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  79465. groundOpacity: 0.9,
  79466. enableGroundShadow: true,
  79467. groundShadowLevel: 0.5,
  79468. enableGroundMirror: false,
  79469. groundMirrorSizeRatio: 0.3,
  79470. groundMirrorBlurKernel: 64,
  79471. groundMirrorAmount: 1,
  79472. groundMirrorFresnelWeight: 1,
  79473. groundMirrorFallOffDistance: 0,
  79474. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  79475. createSkybox: true,
  79476. skyboxSize: 20,
  79477. skyboxTexture: this._skyboxTextureCDNUrl,
  79478. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  79479. backgroundYRotation: 0,
  79480. sizeAuto: true,
  79481. rootPosition: BABYLON.Vector3.Zero(),
  79482. setupImageProcessing: true,
  79483. environmentTexture: this._environmentTextureCDNUrl,
  79484. cameraExposure: 0.8,
  79485. cameraContrast: 1.2,
  79486. toneMappingEnabled: true,
  79487. };
  79488. };
  79489. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  79490. /**
  79491. * Gets the root mesh created by the helper.
  79492. */
  79493. get: function () {
  79494. return this._rootMesh;
  79495. },
  79496. enumerable: true,
  79497. configurable: true
  79498. });
  79499. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  79500. /**
  79501. * Gets the skybox created by the helper.
  79502. */
  79503. get: function () {
  79504. return this._skybox;
  79505. },
  79506. enumerable: true,
  79507. configurable: true
  79508. });
  79509. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  79510. /**
  79511. * Gets the skybox texture created by the helper.
  79512. */
  79513. get: function () {
  79514. return this._skyboxTexture;
  79515. },
  79516. enumerable: true,
  79517. configurable: true
  79518. });
  79519. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  79520. /**
  79521. * Gets the skybox material created by the helper.
  79522. */
  79523. get: function () {
  79524. return this._skyboxMaterial;
  79525. },
  79526. enumerable: true,
  79527. configurable: true
  79528. });
  79529. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  79530. /**
  79531. * Gets the ground mesh created by the helper.
  79532. */
  79533. get: function () {
  79534. return this._ground;
  79535. },
  79536. enumerable: true,
  79537. configurable: true
  79538. });
  79539. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  79540. /**
  79541. * Gets the ground texture created by the helper.
  79542. */
  79543. get: function () {
  79544. return this._groundTexture;
  79545. },
  79546. enumerable: true,
  79547. configurable: true
  79548. });
  79549. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  79550. /**
  79551. * Gets the ground mirror created by the helper.
  79552. */
  79553. get: function () {
  79554. return this._groundMirror;
  79555. },
  79556. enumerable: true,
  79557. configurable: true
  79558. });
  79559. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  79560. /**
  79561. * Gets the ground mirror render list to helps pushing the meshes
  79562. * you wish in the ground reflection.
  79563. */
  79564. get: function () {
  79565. if (this._groundMirror) {
  79566. return this._groundMirror.renderList;
  79567. }
  79568. return null;
  79569. },
  79570. enumerable: true,
  79571. configurable: true
  79572. });
  79573. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  79574. /**
  79575. * Gets the ground material created by the helper.
  79576. */
  79577. get: function () {
  79578. return this._groundMaterial;
  79579. },
  79580. enumerable: true,
  79581. configurable: true
  79582. });
  79583. /**
  79584. * Updates the background according to the new options
  79585. * @param options
  79586. */
  79587. EnvironmentHelper.prototype.updateOptions = function (options) {
  79588. var newOptions = __assign({}, this._options, options);
  79589. if (this._ground && !newOptions.createGround) {
  79590. this._ground.dispose();
  79591. this._ground = null;
  79592. }
  79593. if (this._groundMaterial && !newOptions.createGround) {
  79594. this._groundMaterial.dispose();
  79595. this._groundMaterial = null;
  79596. }
  79597. if (this._groundTexture) {
  79598. if (this._options.groundTexture != newOptions.groundTexture) {
  79599. this._groundTexture.dispose();
  79600. this._groundTexture = null;
  79601. }
  79602. }
  79603. if (this._skybox && !newOptions.createSkybox) {
  79604. this._skybox.dispose();
  79605. this._skybox = null;
  79606. }
  79607. if (this._skyboxMaterial && !newOptions.createSkybox) {
  79608. this._skyboxMaterial.dispose();
  79609. this._skyboxMaterial = null;
  79610. }
  79611. if (this._skyboxTexture) {
  79612. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  79613. this._skyboxTexture.dispose();
  79614. this._skyboxTexture = null;
  79615. }
  79616. }
  79617. if (this._groundMirror && !newOptions.enableGroundMirror) {
  79618. this._groundMirror.dispose();
  79619. this._groundMirror = null;
  79620. }
  79621. if (this._scene.environmentTexture) {
  79622. if (this._options.environmentTexture != newOptions.environmentTexture) {
  79623. this._scene.environmentTexture.dispose();
  79624. }
  79625. }
  79626. this._options = newOptions;
  79627. this._setupBackground();
  79628. this._setupImageProcessing();
  79629. };
  79630. /**
  79631. * Sets the primary color of all the available elements.
  79632. * @param color
  79633. */
  79634. EnvironmentHelper.prototype.setMainColor = function (color) {
  79635. if (this.groundMaterial) {
  79636. this.groundMaterial.primaryColor = color;
  79637. }
  79638. if (this.skyboxMaterial) {
  79639. this.skyboxMaterial.primaryColor = color;
  79640. }
  79641. if (this.groundMirror) {
  79642. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  79643. }
  79644. };
  79645. /**
  79646. * Setup the image processing according to the specified options.
  79647. */
  79648. EnvironmentHelper.prototype._setupImageProcessing = function () {
  79649. if (this._options.setupImageProcessing) {
  79650. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  79651. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  79652. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  79653. this._setupEnvironmentTexture();
  79654. }
  79655. };
  79656. /**
  79657. * Setup the environment texture according to the specified options.
  79658. */
  79659. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  79660. if (this._scene.environmentTexture) {
  79661. return;
  79662. }
  79663. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  79664. this._scene.environmentTexture = this._options.environmentTexture;
  79665. return;
  79666. }
  79667. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  79668. this._scene.environmentTexture = environmentTexture;
  79669. };
  79670. /**
  79671. * Setup the background according to the specified options.
  79672. */
  79673. EnvironmentHelper.prototype._setupBackground = function () {
  79674. if (!this._rootMesh) {
  79675. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  79676. }
  79677. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  79678. var sceneSize = this._getSceneSize();
  79679. if (this._options.createGround) {
  79680. this._setupGround(sceneSize);
  79681. this._setupGroundMaterial();
  79682. this._setupGroundDiffuseTexture();
  79683. if (this._options.enableGroundMirror) {
  79684. this._setupGroundMirrorTexture(sceneSize);
  79685. }
  79686. this._setupMirrorInGroundMaterial();
  79687. }
  79688. if (this._options.createSkybox) {
  79689. this._setupSkybox(sceneSize);
  79690. this._setupSkyboxMaterial();
  79691. this._setupSkyboxReflectionTexture();
  79692. }
  79693. this._rootMesh.position.x = sceneSize.rootPosition.x;
  79694. this._rootMesh.position.z = sceneSize.rootPosition.z;
  79695. this._rootMesh.position.y = sceneSize.rootPosition.y;
  79696. };
  79697. /**
  79698. * Get the scene sizes according to the setup.
  79699. */
  79700. EnvironmentHelper.prototype._getSceneSize = function () {
  79701. var groundSize = this._options.groundSize;
  79702. var skyboxSize = this._options.skyboxSize;
  79703. var rootPosition = this._options.rootPosition;
  79704. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  79705. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  79706. }
  79707. var sceneExtends = this._scene.getWorldExtends();
  79708. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  79709. var bias = 0.0001;
  79710. if (this._options.sizeAuto) {
  79711. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  79712. this._scene.activeCamera.upperRadiusLimit) {
  79713. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  79714. }
  79715. if (this._scene.activeCamera) {
  79716. bias = (this._scene.activeCamera.maxZ - this._scene.activeCamera.minZ) / 10000;
  79717. }
  79718. var sceneDiagonalLenght = sceneDiagonal.length();
  79719. if (sceneDiagonalLenght > groundSize) {
  79720. groundSize = sceneDiagonalLenght * 2;
  79721. }
  79722. // 10 % bigger.
  79723. groundSize *= 1.1;
  79724. skyboxSize *= 1.5;
  79725. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  79726. rootPosition.y = sceneExtends.min.y - bias;
  79727. }
  79728. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  79729. };
  79730. /**
  79731. * Setup the ground according to the specified options.
  79732. */
  79733. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  79734. var _this = this;
  79735. if (!this._ground) {
  79736. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  79737. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  79738. this._ground.parent = this._rootMesh;
  79739. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  79740. }
  79741. this._ground.receiveShadows = this._options.enableGroundShadow;
  79742. };
  79743. /**
  79744. * Setup the ground material according to the specified options.
  79745. */
  79746. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  79747. if (!this._groundMaterial) {
  79748. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  79749. }
  79750. this._groundMaterial.alpha = this._options.groundOpacity;
  79751. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  79752. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  79753. this._groundMaterial.primaryLevel = 1;
  79754. this._groundMaterial.primaryColor = this._options.groundColor;
  79755. this._groundMaterial.secondaryLevel = 0;
  79756. this._groundMaterial.tertiaryLevel = 0;
  79757. this._groundMaterial.useRGBColor = false;
  79758. this._groundMaterial.enableNoise = true;
  79759. if (this._ground) {
  79760. this._ground.material = this._groundMaterial;
  79761. }
  79762. };
  79763. /**
  79764. * Setup the ground diffuse texture according to the specified options.
  79765. */
  79766. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  79767. if (!this._groundMaterial) {
  79768. return;
  79769. }
  79770. if (this._groundTexture) {
  79771. return;
  79772. }
  79773. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  79774. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  79775. return;
  79776. }
  79777. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  79778. diffuseTexture.gammaSpace = false;
  79779. diffuseTexture.hasAlpha = true;
  79780. this._groundMaterial.diffuseTexture = diffuseTexture;
  79781. };
  79782. /**
  79783. * Setup the ground mirror texture according to the specified options.
  79784. */
  79785. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  79786. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79787. if (!this._groundMirror) {
  79788. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  79789. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  79790. this._groundMirror.anisotropicFilteringLevel = 1;
  79791. this._groundMirror.wrapU = wrapping;
  79792. this._groundMirror.wrapV = wrapping;
  79793. this._groundMirror.gammaSpace = false;
  79794. if (this._groundMirror.renderList) {
  79795. for (var i = 0; i < this._scene.meshes.length; i++) {
  79796. var mesh = this._scene.meshes[i];
  79797. if (mesh !== this._ground &&
  79798. mesh !== this._skybox &&
  79799. mesh !== this._rootMesh) {
  79800. this._groundMirror.renderList.push(mesh);
  79801. }
  79802. }
  79803. }
  79804. }
  79805. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  79806. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  79807. };
  79808. /**
  79809. * Setup the ground to receive the mirror texture.
  79810. */
  79811. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  79812. if (this._groundMaterial) {
  79813. this._groundMaterial.reflectionTexture = this._groundMirror;
  79814. this._groundMaterial.reflectionFresnel = true;
  79815. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  79816. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  79817. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  79818. }
  79819. };
  79820. /**
  79821. * Setup the skybox according to the specified options.
  79822. */
  79823. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  79824. var _this = this;
  79825. if (!this._skybox) {
  79826. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  79827. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  79828. }
  79829. this._skybox.parent = this._rootMesh;
  79830. };
  79831. /**
  79832. * Setup the skybox material according to the specified options.
  79833. */
  79834. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  79835. if (!this._skybox) {
  79836. return;
  79837. }
  79838. if (!this._skyboxMaterial) {
  79839. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  79840. }
  79841. this._skyboxMaterial.useRGBColor = false;
  79842. this._skyboxMaterial.primaryLevel = 1;
  79843. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  79844. this._skyboxMaterial.secondaryLevel = 0;
  79845. this._skyboxMaterial.tertiaryLevel = 0;
  79846. this._skyboxMaterial.enableNoise = true;
  79847. this._skybox.material = this._skyboxMaterial;
  79848. };
  79849. /**
  79850. * Setup the skybox reflection texture according to the specified options.
  79851. */
  79852. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  79853. if (!this._skyboxMaterial) {
  79854. return;
  79855. }
  79856. if (this._skyboxTexture) {
  79857. return;
  79858. }
  79859. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  79860. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  79861. return;
  79862. }
  79863. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  79864. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  79865. this._skyboxTexture.gammaSpace = false;
  79866. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  79867. };
  79868. /**
  79869. * Dispose all the elements created by the Helper.
  79870. */
  79871. EnvironmentHelper.prototype.dispose = function () {
  79872. if (this._groundMaterial) {
  79873. this._groundMaterial.dispose(true, true);
  79874. }
  79875. if (this._skyboxMaterial) {
  79876. this._skyboxMaterial.dispose(true, true);
  79877. }
  79878. this._rootMesh.dispose(false);
  79879. };
  79880. /**
  79881. * Default ground texture URL.
  79882. */
  79883. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  79884. /**
  79885. * Default skybox texture URL.
  79886. */
  79887. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  79888. /**
  79889. * Default environment texture URL.
  79890. */
  79891. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  79892. return EnvironmentHelper;
  79893. }());
  79894. BABYLON.EnvironmentHelper = EnvironmentHelper;
  79895. })(BABYLON || (BABYLON = {}));
  79896. //# sourceMappingURL=babylon.environmentHelper.js.map
  79897. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\ngl_FragColor=color;\n}","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=abs(texture2D(textureSampler,vUV).r);\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,1.0);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb=dither(vPositionW.xy,color.rgb);\n#endif\ngl_FragColor=color;\n}"};
  79898. 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};"};
  79899. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  79900. var BABYLON;
  79901. (function (BABYLON) {
  79902. var GridMaterialDefines = /** @class */ (function (_super) {
  79903. __extends(GridMaterialDefines, _super);
  79904. function GridMaterialDefines() {
  79905. var _this = _super.call(this) || this;
  79906. _this.TRANSPARENT = false;
  79907. _this.FOG = false;
  79908. _this.PREMULTIPLYALPHA = false;
  79909. _this.rebuild();
  79910. return _this;
  79911. }
  79912. return GridMaterialDefines;
  79913. }(BABYLON.MaterialDefines));
  79914. /**
  79915. * The grid materials allows you to wrap any shape with a grid.
  79916. * Colors are customizable.
  79917. */
  79918. var GridMaterial = /** @class */ (function (_super) {
  79919. __extends(GridMaterial, _super);
  79920. /**
  79921. * constructor
  79922. * @param name The name given to the material in order to identify it afterwards.
  79923. * @param scene The scene the material is used in.
  79924. */
  79925. function GridMaterial(name, scene) {
  79926. var _this = _super.call(this, name, scene) || this;
  79927. /**
  79928. * Main color of the grid (e.g. between lines)
  79929. */
  79930. _this.mainColor = BABYLON.Color3.Black();
  79931. /**
  79932. * Color of the grid lines.
  79933. */
  79934. _this.lineColor = BABYLON.Color3.Teal();
  79935. /**
  79936. * The scale of the grid compared to unit.
  79937. */
  79938. _this.gridRatio = 1.0;
  79939. /**
  79940. * Allows setting an offset for the grid lines.
  79941. */
  79942. _this.gridOffset = BABYLON.Vector3.Zero();
  79943. /**
  79944. * The frequency of thicker lines.
  79945. */
  79946. _this.majorUnitFrequency = 10;
  79947. /**
  79948. * The visibility of minor units in the grid.
  79949. */
  79950. _this.minorUnitVisibility = 0.33;
  79951. /**
  79952. * The grid opacity outside of the lines.
  79953. */
  79954. _this.opacity = 1.0;
  79955. /**
  79956. * Determine RBG output is premultiplied by alpha value.
  79957. */
  79958. _this.preMultiplyAlpha = false;
  79959. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  79960. return _this;
  79961. }
  79962. /**
  79963. * Returns wehter or not the grid requires alpha blending.
  79964. */
  79965. GridMaterial.prototype.needAlphaBlending = function () {
  79966. return this.opacity < 1.0;
  79967. };
  79968. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  79969. return this.needAlphaBlending();
  79970. };
  79971. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  79972. if (this.isFrozen) {
  79973. if (this._wasPreviouslyReady && subMesh.effect) {
  79974. return true;
  79975. }
  79976. }
  79977. if (!subMesh._materialDefines) {
  79978. subMesh._materialDefines = new GridMaterialDefines();
  79979. }
  79980. var defines = subMesh._materialDefines;
  79981. var scene = this.getScene();
  79982. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  79983. if (this._renderId === scene.getRenderId()) {
  79984. return true;
  79985. }
  79986. }
  79987. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  79988. defines.TRANSPARENT = !defines.TRANSPARENT;
  79989. defines.markAsUnprocessed();
  79990. }
  79991. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  79992. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  79993. defines.markAsUnprocessed();
  79994. }
  79995. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines);
  79996. // Get correct effect
  79997. if (defines.isDirty) {
  79998. defines.markAsProcessed();
  79999. scene.resetCachedMaterial();
  80000. // Attributes
  80001. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  80002. // Defines
  80003. var join = defines.toString();
  80004. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  80005. }
  80006. if (!subMesh.effect || !subMesh.effect.isReady()) {
  80007. return false;
  80008. }
  80009. this._renderId = scene.getRenderId();
  80010. this._wasPreviouslyReady = true;
  80011. return true;
  80012. };
  80013. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  80014. var scene = this.getScene();
  80015. var defines = subMesh._materialDefines;
  80016. if (!defines) {
  80017. return;
  80018. }
  80019. var effect = subMesh.effect;
  80020. if (!effect) {
  80021. return;
  80022. }
  80023. this._activeEffect = effect;
  80024. // Matrices
  80025. this.bindOnlyWorldMatrix(world);
  80026. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  80027. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  80028. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  80029. // Uniforms
  80030. if (this._mustRebind(scene, effect)) {
  80031. this._activeEffect.setColor3("mainColor", this.mainColor);
  80032. this._activeEffect.setColor3("lineColor", this.lineColor);
  80033. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  80034. this._gridControl.x = this.gridRatio;
  80035. this._gridControl.y = Math.round(this.majorUnitFrequency);
  80036. this._gridControl.z = this.minorUnitVisibility;
  80037. this._gridControl.w = this.opacity;
  80038. this._activeEffect.setVector4("gridControl", this._gridControl);
  80039. }
  80040. // Fog
  80041. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  80042. this._afterBind(mesh, this._activeEffect);
  80043. };
  80044. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  80045. _super.prototype.dispose.call(this, forceDisposeEffect);
  80046. };
  80047. GridMaterial.prototype.clone = function (name) {
  80048. var _this = this;
  80049. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  80050. };
  80051. GridMaterial.prototype.serialize = function () {
  80052. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  80053. serializationObject.customType = "BABYLON.GridMaterial";
  80054. return serializationObject;
  80055. };
  80056. GridMaterial.prototype.getClassName = function () {
  80057. return "GridMaterial";
  80058. };
  80059. GridMaterial.Parse = function (source, scene, rootUrl) {
  80060. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  80061. };
  80062. __decorate([
  80063. BABYLON.serializeAsColor3()
  80064. ], GridMaterial.prototype, "mainColor", void 0);
  80065. __decorate([
  80066. BABYLON.serializeAsColor3()
  80067. ], GridMaterial.prototype, "lineColor", void 0);
  80068. __decorate([
  80069. BABYLON.serialize()
  80070. ], GridMaterial.prototype, "gridRatio", void 0);
  80071. __decorate([
  80072. BABYLON.serializeAsColor3()
  80073. ], GridMaterial.prototype, "gridOffset", void 0);
  80074. __decorate([
  80075. BABYLON.serialize()
  80076. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  80077. __decorate([
  80078. BABYLON.serialize()
  80079. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  80080. __decorate([
  80081. BABYLON.serialize()
  80082. ], GridMaterial.prototype, "opacity", void 0);
  80083. __decorate([
  80084. BABYLON.serialize()
  80085. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  80086. return GridMaterial;
  80087. }(BABYLON.PushMaterial));
  80088. BABYLON.GridMaterial = GridMaterial;
  80089. })(BABYLON || (BABYLON = {}));
  80090. //# sourceMappingURL=babylon.gridmaterial.js.map
  80091. BABYLON.Effect.ShadersStore['gridVertexShader'] = "precision highp float;\n\nattribute vec3 position;\nattribute vec3 normal;\n\nuniform mat4 projection;\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 worldView;\n\n#ifdef TRANSPARENT\nvarying vec4 vCameraSpacePosition;\n#endif\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include<fogVertexDeclaration>\nvoid main(void) {\n#ifdef FOG\nvec4 worldPos=world*vec4(position,1.0);\n#endif\n#include<fogVertex>\nvec4 cameraSpacePosition=worldView*vec4(position,1.0);\ngl_Position=projection*cameraSpacePosition;\n#ifdef TRANSPARENT\nvCameraSpacePosition=cameraSpacePosition;\n#endif\nvPosition=position;\nvNormal=normal;\n}";
  80092. BABYLON.Effect.ShadersStore['gridPixelShader'] = "#extension GL_OES_standard_derivatives : enable\n#define SQRT2 1.41421356\n#define PI 3.14159\nprecision highp float;\nuniform vec3 mainColor;\nuniform vec3 lineColor;\nuniform vec4 gridControl;\nuniform vec3 gridOffset;\n\n#ifdef TRANSPARENT\nvarying vec4 vCameraSpacePosition;\n#endif\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include<fogFragmentDeclaration>\nfloat getVisibility(float position) {\n\nfloat majorGridFrequency=gridControl.y;\nif (floor(position+0.5) == floor(position/majorGridFrequency+0.5)*majorGridFrequency)\n{\nreturn 1.0;\n} \nreturn gridControl.z;\n}\nfloat getAnisotropicAttenuation(float differentialLength) {\nconst float maxNumberOfLines=10.0;\nreturn clamp(1.0/(differentialLength+1.0)-1.0/maxNumberOfLines,0.0,1.0);\n}\nfloat isPointOnLine(float position,float differentialLength) {\nfloat fractionPartOfPosition=position-floor(position+0.5); \nfractionPartOfPosition/=differentialLength; \nfractionPartOfPosition=clamp(fractionPartOfPosition,-1.,1.);\nfloat result=0.5+0.5*cos(fractionPartOfPosition*PI); \nreturn result; \n}\nfloat contributionOnAxis(float position) {\nfloat differentialLength=length(vec2(dFdx(position),dFdy(position)));\ndifferentialLength*=SQRT2; \n\nfloat result=isPointOnLine(position,differentialLength);\n\nfloat visibility=getVisibility(position);\nresult*=visibility;\n\nfloat anisotropicAttenuation=getAnisotropicAttenuation(differentialLength);\nresult*=anisotropicAttenuation;\nreturn result;\n}\nfloat normalImpactOnAxis(float x) {\nfloat normalImpact=clamp(1.0-3.0*abs(x*x*x),0.0,1.0);\nreturn normalImpact;\n}\nvoid main(void) {\n\nfloat gridRatio=gridControl.x;\nvec3 gridPos=(vPosition+gridOffset)/gridRatio;\n\nfloat x=contributionOnAxis(gridPos.x);\nfloat y=contributionOnAxis(gridPos.y);\nfloat z=contributionOnAxis(gridPos.z);\n\nvec3 normal=normalize(vNormal);\nx*=normalImpactOnAxis(normal.x);\ny*=normalImpactOnAxis(normal.y);\nz*=normalImpactOnAxis(normal.z);\n\nfloat grid=clamp(x+y+z,0.,1.);\n\nvec3 color=mix(mainColor,lineColor,grid);\n#ifdef FOG\n#include<fogFragment>\n#endif\n#ifdef TRANSPARENT\nfloat distanceToFragment=length(vCameraSpacePosition.xyz);\nfloat cameraPassThrough=clamp(distanceToFragment-0.25,0.0,1.0);\nfloat opacity=clamp(grid,0.08,cameraPassThrough*gridControl.w*grid);\ngl_FragColor=vec4(color.rgb,opacity);\n#ifdef PREMULTIPLYALPHA\ngl_FragColor.rgb*=opacity;\n#endif\n#else\n\ngl_FragColor=vec4(color.rgb,1.0);\n#endif\n}";
  80093. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  80094. var BABYLON;
  80095. (function (BABYLON) {
  80096. var GLTFLoaderCoordinateSystemMode;
  80097. (function (GLTFLoaderCoordinateSystemMode) {
  80098. /**
  80099. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  80100. */
  80101. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  80102. /**
  80103. * Sets the useRightHandedSystem flag on the scene.
  80104. */
  80105. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  80106. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  80107. var GLTFLoaderAnimationStartMode;
  80108. (function (GLTFLoaderAnimationStartMode) {
  80109. /**
  80110. * No animation will start.
  80111. */
  80112. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  80113. /**
  80114. * The first animation will start.
  80115. */
  80116. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  80117. /**
  80118. * All animations will start.
  80119. */
  80120. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  80121. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  80122. var GLTFFileLoader = /** @class */ (function () {
  80123. function GLTFFileLoader() {
  80124. // #endregion
  80125. // #region V2 options
  80126. /**
  80127. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  80128. */
  80129. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  80130. /**
  80131. * The animation start mode (NONE, FIRST, ALL).
  80132. */
  80133. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  80134. /**
  80135. * Set to true to compile materials before raising the success callback.
  80136. */
  80137. this.compileMaterials = false;
  80138. /**
  80139. * Set to true to also compile materials with clip planes.
  80140. */
  80141. this.useClipPlane = false;
  80142. /**
  80143. * Set to true to compile shadow generators before raising the success callback.
  80144. */
  80145. this.compileShadowGenerators = false;
  80146. this.name = "gltf";
  80147. this.extensions = {
  80148. ".gltf": { isBinary: false },
  80149. ".glb": { isBinary: true }
  80150. };
  80151. }
  80152. /**
  80153. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  80154. */
  80155. GLTFFileLoader.prototype.dispose = function () {
  80156. if (this._loader) {
  80157. this._loader.dispose();
  80158. }
  80159. };
  80160. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  80161. try {
  80162. var loaderData = GLTFFileLoader._parse(data);
  80163. if (this.onParsed) {
  80164. this.onParsed(loaderData);
  80165. }
  80166. this._loader = this._getLoader(loaderData);
  80167. this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  80168. }
  80169. catch (e) {
  80170. if (onError) {
  80171. onError(e.message, e);
  80172. }
  80173. else {
  80174. BABYLON.Tools.Error(e.message);
  80175. }
  80176. }
  80177. };
  80178. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  80179. try {
  80180. var loaderData = GLTFFileLoader._parse(data);
  80181. if (this.onParsed) {
  80182. this.onParsed(loaderData);
  80183. }
  80184. this._loader = this._getLoader(loaderData);
  80185. this._loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  80186. }
  80187. catch (e) {
  80188. if (onError) {
  80189. onError(e.message, e);
  80190. }
  80191. else {
  80192. BABYLON.Tools.Error(e.message);
  80193. }
  80194. }
  80195. };
  80196. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  80197. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  80198. };
  80199. GLTFFileLoader.prototype.createPlugin = function () {
  80200. return new GLTFFileLoader();
  80201. };
  80202. GLTFFileLoader._parse = function (data) {
  80203. if (data instanceof ArrayBuffer) {
  80204. return GLTFFileLoader._parseBinary(data);
  80205. }
  80206. return {
  80207. json: JSON.parse(data),
  80208. bin: null
  80209. };
  80210. };
  80211. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  80212. var loaderVersion = { major: 2, minor: 0 };
  80213. var asset = loaderData.json.asset || {};
  80214. var version = GLTFFileLoader._parseVersion(asset.version);
  80215. if (!version) {
  80216. throw new Error("Invalid version: " + asset.version);
  80217. }
  80218. if (asset.minVersion !== undefined) {
  80219. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  80220. if (!minVersion) {
  80221. throw new Error("Invalid minimum version: " + asset.minVersion);
  80222. }
  80223. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  80224. throw new Error("Incompatible minimum version: " + asset.minVersion);
  80225. }
  80226. }
  80227. var createLoaders = {
  80228. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  80229. 2: GLTFFileLoader.CreateGLTFLoaderV2
  80230. };
  80231. var createLoader = createLoaders[version.major];
  80232. if (!createLoader) {
  80233. throw new Error("Unsupported version: " + asset.version);
  80234. }
  80235. return createLoader(this);
  80236. };
  80237. GLTFFileLoader._parseBinary = function (data) {
  80238. var Binary = {
  80239. Magic: 0x46546C67
  80240. };
  80241. var binaryReader = new BinaryReader(data);
  80242. var magic = binaryReader.readUint32();
  80243. if (magic !== Binary.Magic) {
  80244. throw new Error("Unexpected magic: " + magic);
  80245. }
  80246. var version = binaryReader.readUint32();
  80247. switch (version) {
  80248. case 1: return GLTFFileLoader._parseV1(binaryReader);
  80249. case 2: return GLTFFileLoader._parseV2(binaryReader);
  80250. }
  80251. throw new Error("Unsupported version: " + version);
  80252. };
  80253. GLTFFileLoader._parseV1 = function (binaryReader) {
  80254. var ContentFormat = {
  80255. JSON: 0
  80256. };
  80257. var length = binaryReader.readUint32();
  80258. if (length != binaryReader.getLength()) {
  80259. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  80260. }
  80261. var contentLength = binaryReader.readUint32();
  80262. var contentFormat = binaryReader.readUint32();
  80263. var content;
  80264. switch (contentFormat) {
  80265. case ContentFormat.JSON: {
  80266. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  80267. break;
  80268. }
  80269. default: {
  80270. throw new Error("Unexpected content format: " + contentFormat);
  80271. }
  80272. }
  80273. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  80274. var body = binaryReader.readUint8Array(bytesRemaining);
  80275. return {
  80276. json: content,
  80277. bin: body
  80278. };
  80279. };
  80280. GLTFFileLoader._parseV2 = function (binaryReader) {
  80281. var ChunkFormat = {
  80282. JSON: 0x4E4F534A,
  80283. BIN: 0x004E4942
  80284. };
  80285. var length = binaryReader.readUint32();
  80286. if (length !== binaryReader.getLength()) {
  80287. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  80288. }
  80289. // JSON chunk
  80290. var chunkLength = binaryReader.readUint32();
  80291. var chunkFormat = binaryReader.readUint32();
  80292. if (chunkFormat !== ChunkFormat.JSON) {
  80293. throw new Error("First chunk format is not JSON");
  80294. }
  80295. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  80296. // Look for BIN chunk
  80297. var bin = null;
  80298. while (binaryReader.getPosition() < binaryReader.getLength()) {
  80299. var chunkLength_1 = binaryReader.readUint32();
  80300. var chunkFormat_1 = binaryReader.readUint32();
  80301. switch (chunkFormat_1) {
  80302. case ChunkFormat.JSON: {
  80303. throw new Error("Unexpected JSON chunk");
  80304. }
  80305. case ChunkFormat.BIN: {
  80306. bin = binaryReader.readUint8Array(chunkLength_1);
  80307. break;
  80308. }
  80309. default: {
  80310. // ignore unrecognized chunkFormat
  80311. binaryReader.skipBytes(chunkLength_1);
  80312. break;
  80313. }
  80314. }
  80315. }
  80316. return {
  80317. json: json,
  80318. bin: bin
  80319. };
  80320. };
  80321. GLTFFileLoader._parseVersion = function (version) {
  80322. if (version === "1.0" || version === "1.0.1") {
  80323. return {
  80324. major: 1,
  80325. minor: 0
  80326. };
  80327. }
  80328. var match = (version + "").match(/^(\d+)\.(\d+)/);
  80329. if (!match) {
  80330. return null;
  80331. }
  80332. return {
  80333. major: parseInt(match[1]),
  80334. minor: parseInt(match[2])
  80335. };
  80336. };
  80337. GLTFFileLoader._compareVersion = function (a, b) {
  80338. if (a.major > b.major)
  80339. return 1;
  80340. if (a.major < b.major)
  80341. return -1;
  80342. if (a.minor > b.minor)
  80343. return 1;
  80344. if (a.minor < b.minor)
  80345. return -1;
  80346. return 0;
  80347. };
  80348. GLTFFileLoader._decodeBufferToText = function (buffer) {
  80349. var result = "";
  80350. var length = buffer.byteLength;
  80351. for (var i = 0; i < length; i++) {
  80352. result += String.fromCharCode(buffer[i]);
  80353. }
  80354. return result;
  80355. };
  80356. // #endregion
  80357. // #region V1 options
  80358. GLTFFileLoader.IncrementalLoading = true;
  80359. GLTFFileLoader.HomogeneousCoordinates = false;
  80360. return GLTFFileLoader;
  80361. }());
  80362. BABYLON.GLTFFileLoader = GLTFFileLoader;
  80363. var BinaryReader = /** @class */ (function () {
  80364. function BinaryReader(arrayBuffer) {
  80365. this._arrayBuffer = arrayBuffer;
  80366. this._dataView = new DataView(arrayBuffer);
  80367. this._byteOffset = 0;
  80368. }
  80369. BinaryReader.prototype.getPosition = function () {
  80370. return this._byteOffset;
  80371. };
  80372. BinaryReader.prototype.getLength = function () {
  80373. return this._arrayBuffer.byteLength;
  80374. };
  80375. BinaryReader.prototype.readUint32 = function () {
  80376. var value = this._dataView.getUint32(this._byteOffset, true);
  80377. this._byteOffset += 4;
  80378. return value;
  80379. };
  80380. BinaryReader.prototype.readUint8Array = function (length) {
  80381. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  80382. this._byteOffset += length;
  80383. return value;
  80384. };
  80385. BinaryReader.prototype.skipBytes = function (length) {
  80386. this._byteOffset += length;
  80387. };
  80388. return BinaryReader;
  80389. }());
  80390. if (BABYLON.SceneLoader) {
  80391. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  80392. }
  80393. })(BABYLON || (BABYLON = {}));
  80394. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  80395. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  80396. var BABYLON;
  80397. (function (BABYLON) {
  80398. var GLTF1;
  80399. (function (GLTF1) {
  80400. /**
  80401. * Enums
  80402. */
  80403. var EComponentType;
  80404. (function (EComponentType) {
  80405. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  80406. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  80407. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  80408. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  80409. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  80410. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  80411. var EShaderType;
  80412. (function (EShaderType) {
  80413. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  80414. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  80415. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  80416. var EParameterType;
  80417. (function (EParameterType) {
  80418. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  80419. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  80420. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  80421. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  80422. EParameterType[EParameterType["INT"] = 5124] = "INT";
  80423. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  80424. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  80425. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  80426. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  80427. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  80428. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  80429. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  80430. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  80431. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  80432. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  80433. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  80434. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  80435. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  80436. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  80437. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  80438. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  80439. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  80440. var ETextureWrapMode;
  80441. (function (ETextureWrapMode) {
  80442. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  80443. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  80444. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  80445. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  80446. var ETextureFilterType;
  80447. (function (ETextureFilterType) {
  80448. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  80449. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  80450. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  80451. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  80452. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  80453. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  80454. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  80455. var ETextureFormat;
  80456. (function (ETextureFormat) {
  80457. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  80458. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  80459. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  80460. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  80461. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  80462. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  80463. var ECullingType;
  80464. (function (ECullingType) {
  80465. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  80466. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  80467. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  80468. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  80469. var EBlendingFunction;
  80470. (function (EBlendingFunction) {
  80471. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  80472. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  80473. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  80474. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  80475. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  80476. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  80477. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  80478. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  80479. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  80480. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  80481. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  80482. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  80483. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  80484. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  80485. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  80486. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  80487. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  80488. })(BABYLON || (BABYLON = {}));
  80489. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  80490. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  80491. var BABYLON;
  80492. (function (BABYLON) {
  80493. var GLTF1;
  80494. (function (GLTF1) {
  80495. /**
  80496. * Tokenizer. Used for shaders compatibility
  80497. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  80498. */
  80499. var ETokenType;
  80500. (function (ETokenType) {
  80501. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  80502. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  80503. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  80504. })(ETokenType || (ETokenType = {}));
  80505. var Tokenizer = /** @class */ (function () {
  80506. function Tokenizer(toParse) {
  80507. this._pos = 0;
  80508. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  80509. this._toParse = toParse;
  80510. this._maxPos = toParse.length;
  80511. }
  80512. Tokenizer.prototype.getNextToken = function () {
  80513. if (this.isEnd())
  80514. return ETokenType.END_OF_INPUT;
  80515. this.currentString = this.read();
  80516. this.currentToken = ETokenType.UNKNOWN;
  80517. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  80518. this.currentToken = ETokenType.IDENTIFIER;
  80519. this.currentIdentifier = this.currentString;
  80520. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  80521. this.currentIdentifier += this.currentString;
  80522. this.forward();
  80523. }
  80524. }
  80525. return this.currentToken;
  80526. };
  80527. Tokenizer.prototype.peek = function () {
  80528. return this._toParse[this._pos];
  80529. };
  80530. Tokenizer.prototype.read = function () {
  80531. return this._toParse[this._pos++];
  80532. };
  80533. Tokenizer.prototype.forward = function () {
  80534. this._pos++;
  80535. };
  80536. Tokenizer.prototype.isEnd = function () {
  80537. return this._pos >= this._maxPos;
  80538. };
  80539. return Tokenizer;
  80540. }());
  80541. /**
  80542. * Values
  80543. */
  80544. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  80545. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  80546. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  80547. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  80548. /**
  80549. * Parse
  80550. */
  80551. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  80552. for (var buf in parsedBuffers) {
  80553. var parsedBuffer = parsedBuffers[buf];
  80554. gltfRuntime.buffers[buf] = parsedBuffer;
  80555. gltfRuntime.buffersCount++;
  80556. }
  80557. };
  80558. var parseShaders = function (parsedShaders, gltfRuntime) {
  80559. for (var sha in parsedShaders) {
  80560. var parsedShader = parsedShaders[sha];
  80561. gltfRuntime.shaders[sha] = parsedShader;
  80562. gltfRuntime.shaderscount++;
  80563. }
  80564. };
  80565. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  80566. for (var object in parsedObjects) {
  80567. var parsedObject = parsedObjects[object];
  80568. gltfRuntime[runtimeProperty][object] = parsedObject;
  80569. }
  80570. };
  80571. /**
  80572. * Utils
  80573. */
  80574. var normalizeUVs = function (buffer) {
  80575. if (!buffer) {
  80576. return;
  80577. }
  80578. for (var i = 0; i < buffer.length / 2; i++) {
  80579. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  80580. }
  80581. };
  80582. var getAttribute = function (attributeParameter) {
  80583. if (attributeParameter.semantic === "NORMAL") {
  80584. return "normal";
  80585. }
  80586. else if (attributeParameter.semantic === "POSITION") {
  80587. return "position";
  80588. }
  80589. else if (attributeParameter.semantic === "JOINT") {
  80590. return "matricesIndices";
  80591. }
  80592. else if (attributeParameter.semantic === "WEIGHT") {
  80593. return "matricesWeights";
  80594. }
  80595. else if (attributeParameter.semantic === "COLOR") {
  80596. return "color";
  80597. }
  80598. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  80599. var channel = Number(attributeParameter.semantic.split("_")[1]);
  80600. return "uv" + (channel === 0 ? "" : channel + 1);
  80601. }
  80602. return null;
  80603. };
  80604. /**
  80605. * Loads and creates animations
  80606. */
  80607. var loadAnimations = function (gltfRuntime) {
  80608. for (var anim in gltfRuntime.animations) {
  80609. var animation = gltfRuntime.animations[anim];
  80610. if (!animation.channels || !animation.samplers) {
  80611. continue;
  80612. }
  80613. var lastAnimation = null;
  80614. for (var i = 0; i < animation.channels.length; i++) {
  80615. // Get parameters and load buffers
  80616. var channel = animation.channels[i];
  80617. var sampler = animation.samplers[channel.sampler];
  80618. if (!sampler) {
  80619. continue;
  80620. }
  80621. var inputData = null;
  80622. var outputData = null;
  80623. if (animation.parameters) {
  80624. inputData = animation.parameters[sampler.input];
  80625. outputData = animation.parameters[sampler.output];
  80626. }
  80627. else {
  80628. inputData = sampler.input;
  80629. outputData = sampler.output;
  80630. }
  80631. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  80632. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  80633. var targetID = channel.target.id;
  80634. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  80635. if (targetNode === null) {
  80636. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  80637. }
  80638. if (targetNode === null) {
  80639. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  80640. continue;
  80641. }
  80642. var isBone = targetNode instanceof BABYLON.Bone;
  80643. // Get target path (position, rotation or scaling)
  80644. var targetPath = channel.target.path;
  80645. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  80646. if (targetPathIndex !== -1) {
  80647. targetPath = babylonAnimationPaths[targetPathIndex];
  80648. }
  80649. // Determine animation type
  80650. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  80651. if (!isBone) {
  80652. if (targetPath === "rotationQuaternion") {
  80653. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  80654. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  80655. }
  80656. else {
  80657. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  80658. }
  80659. }
  80660. // Create animation and key frames
  80661. var babylonAnimation = null;
  80662. var keys = [];
  80663. var arrayOffset = 0;
  80664. var modifyKey = false;
  80665. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  80666. babylonAnimation = lastAnimation;
  80667. modifyKey = true;
  80668. }
  80669. if (!modifyKey) {
  80670. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  80671. }
  80672. // For each frame
  80673. for (var j = 0; j < bufferInput.length; j++) {
  80674. var value = null;
  80675. if (targetPath === "rotationQuaternion") {
  80676. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  80677. arrayOffset += 4;
  80678. }
  80679. else {
  80680. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  80681. arrayOffset += 3;
  80682. }
  80683. if (isBone) {
  80684. var bone = targetNode;
  80685. var translation = BABYLON.Vector3.Zero();
  80686. var rotationQuaternion = new BABYLON.Quaternion();
  80687. var scaling = BABYLON.Vector3.Zero();
  80688. // Warning on decompose
  80689. var mat = bone.getBaseMatrix();
  80690. if (modifyKey && lastAnimation) {
  80691. mat = lastAnimation.getKeys()[j].value;
  80692. }
  80693. mat.decompose(scaling, rotationQuaternion, translation);
  80694. if (targetPath === "position") {
  80695. translation = value;
  80696. }
  80697. else if (targetPath === "rotationQuaternion") {
  80698. rotationQuaternion = value;
  80699. }
  80700. else {
  80701. scaling = value;
  80702. }
  80703. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  80704. }
  80705. if (!modifyKey) {
  80706. keys.push({
  80707. frame: bufferInput[j],
  80708. value: value
  80709. });
  80710. }
  80711. else if (lastAnimation) {
  80712. lastAnimation.getKeys()[j].value = value;
  80713. }
  80714. }
  80715. // Finish
  80716. if (!modifyKey && babylonAnimation) {
  80717. babylonAnimation.setKeys(keys);
  80718. targetNode.animations.push(babylonAnimation);
  80719. }
  80720. lastAnimation = babylonAnimation;
  80721. gltfRuntime.scene.stopAnimation(targetNode);
  80722. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  80723. }
  80724. }
  80725. };
  80726. /**
  80727. * Returns the bones transformation matrix
  80728. */
  80729. var configureBoneTransformation = function (node) {
  80730. var mat = null;
  80731. if (node.translation || node.rotation || node.scale) {
  80732. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  80733. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  80734. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  80735. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  80736. }
  80737. else {
  80738. mat = BABYLON.Matrix.FromArray(node.matrix);
  80739. }
  80740. return mat;
  80741. };
  80742. /**
  80743. * Returns the parent bone
  80744. */
  80745. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  80746. // Try to find
  80747. for (var i = 0; i < newSkeleton.bones.length; i++) {
  80748. if (newSkeleton.bones[i].name === jointName) {
  80749. return newSkeleton.bones[i];
  80750. }
  80751. }
  80752. // Not found, search in gltf nodes
  80753. var nodes = gltfRuntime.nodes;
  80754. for (var nde in nodes) {
  80755. var node = nodes[nde];
  80756. if (!node.jointName) {
  80757. continue;
  80758. }
  80759. var children = node.children;
  80760. for (var i = 0; i < children.length; i++) {
  80761. var child = gltfRuntime.nodes[children[i]];
  80762. if (!child.jointName) {
  80763. continue;
  80764. }
  80765. if (child.jointName === jointName) {
  80766. var mat = configureBoneTransformation(node);
  80767. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  80768. bone.id = nde;
  80769. return bone;
  80770. }
  80771. }
  80772. }
  80773. return null;
  80774. };
  80775. /**
  80776. * Returns the appropriate root node
  80777. */
  80778. var getNodeToRoot = function (nodesToRoot, id) {
  80779. for (var i = 0; i < nodesToRoot.length; i++) {
  80780. var nodeToRoot = nodesToRoot[i];
  80781. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  80782. var child = nodeToRoot.node.children[j];
  80783. if (child === id) {
  80784. return nodeToRoot.bone;
  80785. }
  80786. }
  80787. }
  80788. return null;
  80789. };
  80790. /**
  80791. * Returns the node with the joint name
  80792. */
  80793. var getJointNode = function (gltfRuntime, jointName) {
  80794. var nodes = gltfRuntime.nodes;
  80795. var node = nodes[jointName];
  80796. if (node) {
  80797. return {
  80798. node: node,
  80799. id: jointName
  80800. };
  80801. }
  80802. for (var nde in nodes) {
  80803. node = nodes[nde];
  80804. if (node.jointName === jointName) {
  80805. return {
  80806. node: node,
  80807. id: nde
  80808. };
  80809. }
  80810. }
  80811. return null;
  80812. };
  80813. /**
  80814. * Checks if a nodes is in joints
  80815. */
  80816. var nodeIsInJoints = function (skins, id) {
  80817. for (var i = 0; i < skins.jointNames.length; i++) {
  80818. if (skins.jointNames[i] === id) {
  80819. return true;
  80820. }
  80821. }
  80822. return false;
  80823. };
  80824. /**
  80825. * Fills the nodes to root for bones and builds hierarchy
  80826. */
  80827. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  80828. // Creates nodes for root
  80829. for (var nde in gltfRuntime.nodes) {
  80830. var node = gltfRuntime.nodes[nde];
  80831. var id = nde;
  80832. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  80833. continue;
  80834. }
  80835. // Create node to root bone
  80836. var mat = configureBoneTransformation(node);
  80837. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  80838. bone.id = id;
  80839. nodesToRoot.push({ bone: bone, node: node, id: id });
  80840. }
  80841. // Parenting
  80842. for (var i = 0; i < nodesToRoot.length; i++) {
  80843. var nodeToRoot = nodesToRoot[i];
  80844. var children = nodeToRoot.node.children;
  80845. for (var j = 0; j < children.length; j++) {
  80846. var child = null;
  80847. for (var k = 0; k < nodesToRoot.length; k++) {
  80848. if (nodesToRoot[k].id === children[j]) {
  80849. child = nodesToRoot[k];
  80850. break;
  80851. }
  80852. }
  80853. if (child) {
  80854. child.bone._parent = nodeToRoot.bone;
  80855. nodeToRoot.bone.children.push(child.bone);
  80856. }
  80857. }
  80858. }
  80859. };
  80860. /**
  80861. * Imports a skeleton
  80862. */
  80863. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  80864. if (!newSkeleton) {
  80865. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  80866. }
  80867. if (!skins.babylonSkeleton) {
  80868. return newSkeleton;
  80869. }
  80870. // Find the root bones
  80871. var nodesToRoot = [];
  80872. var nodesToRootToAdd = [];
  80873. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  80874. newSkeleton.bones = [];
  80875. // Joints
  80876. for (var i = 0; i < skins.jointNames.length; i++) {
  80877. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  80878. if (!jointNode) {
  80879. continue;
  80880. }
  80881. var node = jointNode.node;
  80882. if (!node) {
  80883. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  80884. continue;
  80885. }
  80886. var id = jointNode.id;
  80887. // Optimize, if the bone already exists...
  80888. var existingBone = gltfRuntime.scene.getBoneByID(id);
  80889. if (existingBone) {
  80890. newSkeleton.bones.push(existingBone);
  80891. continue;
  80892. }
  80893. // Search for parent bone
  80894. var foundBone = false;
  80895. var parentBone = null;
  80896. for (var j = 0; j < i; j++) {
  80897. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  80898. if (!jointNode_1) {
  80899. continue;
  80900. }
  80901. var joint = jointNode_1.node;
  80902. if (!joint) {
  80903. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  80904. continue;
  80905. }
  80906. var children = joint.children;
  80907. if (!children) {
  80908. continue;
  80909. }
  80910. foundBone = false;
  80911. for (var k = 0; k < children.length; k++) {
  80912. if (children[k] === id) {
  80913. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  80914. foundBone = true;
  80915. break;
  80916. }
  80917. }
  80918. if (foundBone) {
  80919. break;
  80920. }
  80921. }
  80922. // Create bone
  80923. var mat = configureBoneTransformation(node);
  80924. if (!parentBone && nodesToRoot.length > 0) {
  80925. parentBone = getNodeToRoot(nodesToRoot, id);
  80926. if (parentBone) {
  80927. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  80928. nodesToRootToAdd.push(parentBone);
  80929. }
  80930. }
  80931. }
  80932. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  80933. bone.id = id;
  80934. }
  80935. // Polish
  80936. var bones = newSkeleton.bones;
  80937. newSkeleton.bones = [];
  80938. for (var i = 0; i < skins.jointNames.length; i++) {
  80939. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  80940. if (!jointNode) {
  80941. continue;
  80942. }
  80943. for (var j = 0; j < bones.length; j++) {
  80944. if (bones[j].id === jointNode.id) {
  80945. newSkeleton.bones.push(bones[j]);
  80946. break;
  80947. }
  80948. }
  80949. }
  80950. newSkeleton.prepare();
  80951. // Finish
  80952. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  80953. newSkeleton.bones.push(nodesToRootToAdd[i]);
  80954. }
  80955. return newSkeleton;
  80956. };
  80957. /**
  80958. * Imports a mesh and its geometries
  80959. */
  80960. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  80961. if (!newMesh) {
  80962. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  80963. newMesh.id = id;
  80964. }
  80965. if (!node.babylonNode) {
  80966. return newMesh;
  80967. }
  80968. var subMaterials = [];
  80969. var vertexData = new BABYLON.VertexData();
  80970. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  80971. var verticesStarts = new Array();
  80972. var verticesCounts = new Array();
  80973. var indexStarts = new Array();
  80974. var indexCounts = new Array();
  80975. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  80976. var meshID = meshes[meshIndex];
  80977. var mesh = gltfRuntime.meshes[meshID];
  80978. if (!mesh) {
  80979. continue;
  80980. }
  80981. // Positions, normals and UVs
  80982. for (var i = 0; i < mesh.primitives.length; i++) {
  80983. // Temporary vertex data
  80984. var tempVertexData = new BABYLON.VertexData();
  80985. var primitive = mesh.primitives[i];
  80986. if (primitive.mode !== 4) {
  80987. // continue;
  80988. }
  80989. var attributes = primitive.attributes;
  80990. var accessor = null;
  80991. var buffer = null;
  80992. // Set positions, normal and uvs
  80993. for (var semantic in attributes) {
  80994. // Link accessor and buffer view
  80995. accessor = gltfRuntime.accessors[attributes[semantic]];
  80996. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  80997. if (semantic === "NORMAL") {
  80998. tempVertexData.normals = new Float32Array(buffer.length);
  80999. tempVertexData.normals.set(buffer);
  81000. }
  81001. else if (semantic === "POSITION") {
  81002. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  81003. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  81004. for (var j = 0; j < buffer.length; j += 4) {
  81005. tempVertexData.positions[j] = buffer[j];
  81006. tempVertexData.positions[j + 1] = buffer[j + 1];
  81007. tempVertexData.positions[j + 2] = buffer[j + 2];
  81008. }
  81009. }
  81010. else {
  81011. tempVertexData.positions = new Float32Array(buffer.length);
  81012. tempVertexData.positions.set(buffer);
  81013. }
  81014. verticesCounts.push(tempVertexData.positions.length);
  81015. }
  81016. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  81017. var channel = Number(semantic.split("_")[1]);
  81018. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  81019. var uvs = new Float32Array(buffer.length);
  81020. uvs.set(buffer);
  81021. normalizeUVs(uvs);
  81022. tempVertexData.set(uvs, uvKind);
  81023. }
  81024. else if (semantic === "JOINT") {
  81025. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  81026. tempVertexData.matricesIndices.set(buffer);
  81027. }
  81028. else if (semantic === "WEIGHT") {
  81029. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  81030. tempVertexData.matricesWeights.set(buffer);
  81031. }
  81032. else if (semantic === "COLOR") {
  81033. tempVertexData.colors = new Float32Array(buffer.length);
  81034. tempVertexData.colors.set(buffer);
  81035. }
  81036. }
  81037. // Indices
  81038. accessor = gltfRuntime.accessors[primitive.indices];
  81039. if (accessor) {
  81040. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  81041. tempVertexData.indices = new Int32Array(buffer.length);
  81042. tempVertexData.indices.set(buffer);
  81043. indexCounts.push(tempVertexData.indices.length);
  81044. }
  81045. else {
  81046. // Set indices on the fly
  81047. var indices = [];
  81048. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  81049. indices.push(j);
  81050. }
  81051. tempVertexData.indices = new Int32Array(indices);
  81052. indexCounts.push(tempVertexData.indices.length);
  81053. }
  81054. vertexData.merge(tempVertexData);
  81055. // Sub material
  81056. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  81057. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  81058. // Update vertices start and index start
  81059. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  81060. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  81061. }
  81062. }
  81063. var material;
  81064. if (subMaterials.length > 1) {
  81065. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  81066. material.subMaterials = subMaterials;
  81067. }
  81068. else {
  81069. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  81070. }
  81071. if (subMaterials.length === 1) {
  81072. material = subMaterials[0];
  81073. }
  81074. if (!newMesh.material) {
  81075. newMesh.material = material;
  81076. }
  81077. // Apply geometry
  81078. geometry.setAllVerticesData(vertexData, false);
  81079. newMesh.computeWorldMatrix(true);
  81080. // Apply submeshes
  81081. newMesh.subMeshes = [];
  81082. var index = 0;
  81083. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  81084. var meshID = meshes[meshIndex];
  81085. var mesh = gltfRuntime.meshes[meshID];
  81086. if (!mesh) {
  81087. continue;
  81088. }
  81089. for (var i = 0; i < mesh.primitives.length; i++) {
  81090. if (mesh.primitives[i].mode !== 4) {
  81091. //continue;
  81092. }
  81093. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  81094. index++;
  81095. }
  81096. }
  81097. // Finish
  81098. return newMesh;
  81099. };
  81100. /**
  81101. * Configure node transformation from position, rotation and scaling
  81102. */
  81103. var configureNode = function (newNode, position, rotation, scaling) {
  81104. if (newNode.position) {
  81105. newNode.position = position;
  81106. }
  81107. if (newNode.rotationQuaternion || newNode.rotation) {
  81108. newNode.rotationQuaternion = rotation;
  81109. }
  81110. if (newNode.scaling) {
  81111. newNode.scaling = scaling;
  81112. }
  81113. };
  81114. /**
  81115. * Configures node from transformation matrix
  81116. */
  81117. var configureNodeFromMatrix = function (newNode, node, parent) {
  81118. if (node.matrix) {
  81119. var position = new BABYLON.Vector3(0, 0, 0);
  81120. var rotation = new BABYLON.Quaternion();
  81121. var scaling = new BABYLON.Vector3(0, 0, 0);
  81122. var mat = BABYLON.Matrix.FromArray(node.matrix);
  81123. mat.decompose(scaling, rotation, position);
  81124. configureNode(newNode, position, rotation, scaling);
  81125. }
  81126. else if (node.translation && node.rotation && node.scale) {
  81127. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  81128. }
  81129. newNode.computeWorldMatrix(true);
  81130. };
  81131. /**
  81132. * Imports a node
  81133. */
  81134. var importNode = function (gltfRuntime, node, id, parent) {
  81135. var lastNode = null;
  81136. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  81137. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  81138. return null;
  81139. }
  81140. }
  81141. // Meshes
  81142. if (node.skin) {
  81143. if (node.meshes) {
  81144. var skin = gltfRuntime.skins[node.skin];
  81145. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  81146. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  81147. if (newMesh.skeleton === null) {
  81148. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  81149. if (!skin.babylonSkeleton) {
  81150. skin.babylonSkeleton = newMesh.skeleton;
  81151. }
  81152. }
  81153. lastNode = newMesh;
  81154. }
  81155. }
  81156. else if (node.meshes) {
  81157. /**
  81158. * Improve meshes property
  81159. */
  81160. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  81161. lastNode = newMesh;
  81162. }
  81163. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  81164. var light = gltfRuntime.lights[node.light];
  81165. if (light) {
  81166. if (light.type === "ambient") {
  81167. var ambienLight = light[light.type];
  81168. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  81169. hemiLight.name = node.name || "";
  81170. if (ambienLight.color) {
  81171. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  81172. }
  81173. lastNode = hemiLight;
  81174. }
  81175. else if (light.type === "directional") {
  81176. var directionalLight = light[light.type];
  81177. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  81178. dirLight.name = node.name || "";
  81179. if (directionalLight.color) {
  81180. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  81181. }
  81182. lastNode = dirLight;
  81183. }
  81184. else if (light.type === "point") {
  81185. var pointLight = light[light.type];
  81186. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  81187. ptLight.name = node.name || "";
  81188. if (pointLight.color) {
  81189. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  81190. }
  81191. lastNode = ptLight;
  81192. }
  81193. else if (light.type === "spot") {
  81194. var spotLight = light[light.type];
  81195. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  81196. spLight.name = node.name || "";
  81197. if (spotLight.color) {
  81198. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  81199. }
  81200. if (spotLight.fallOfAngle) {
  81201. spLight.angle = spotLight.fallOfAngle;
  81202. }
  81203. if (spotLight.fallOffExponent) {
  81204. spLight.exponent = spotLight.fallOffExponent;
  81205. }
  81206. lastNode = spLight;
  81207. }
  81208. }
  81209. }
  81210. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  81211. var camera = gltfRuntime.cameras[node.camera];
  81212. if (camera) {
  81213. if (camera.type === "orthographic") {
  81214. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  81215. orthoCamera.name = node.name || "";
  81216. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  81217. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  81218. lastNode = orthoCamera;
  81219. }
  81220. else if (camera.type === "perspective") {
  81221. var perspectiveCamera = camera[camera.type];
  81222. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  81223. persCamera.name = node.name || "";
  81224. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  81225. if (!perspectiveCamera.aspectRatio) {
  81226. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  81227. }
  81228. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  81229. persCamera.maxZ = perspectiveCamera.zfar;
  81230. persCamera.minZ = perspectiveCamera.znear;
  81231. }
  81232. lastNode = persCamera;
  81233. }
  81234. }
  81235. }
  81236. // Empty node
  81237. if (!node.jointName) {
  81238. if (node.babylonNode) {
  81239. return node.babylonNode;
  81240. }
  81241. else if (lastNode === null) {
  81242. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  81243. node.babylonNode = dummy;
  81244. lastNode = dummy;
  81245. }
  81246. }
  81247. if (lastNode !== null) {
  81248. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  81249. configureNodeFromMatrix(lastNode, node, parent);
  81250. }
  81251. else {
  81252. var translation = node.translation || [0, 0, 0];
  81253. var rotation = node.rotation || [0, 0, 0, 1];
  81254. var scale = node.scale || [1, 1, 1];
  81255. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  81256. }
  81257. lastNode.updateCache(true);
  81258. node.babylonNode = lastNode;
  81259. }
  81260. return lastNode;
  81261. };
  81262. /**
  81263. * Traverses nodes and creates them
  81264. */
  81265. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  81266. if (meshIncluded === void 0) { meshIncluded = false; }
  81267. var node = gltfRuntime.nodes[id];
  81268. var newNode = null;
  81269. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  81270. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  81271. meshIncluded = true;
  81272. }
  81273. else {
  81274. meshIncluded = false;
  81275. }
  81276. }
  81277. else {
  81278. meshIncluded = true;
  81279. }
  81280. if (!node.jointName && meshIncluded) {
  81281. newNode = importNode(gltfRuntime, node, id, parent);
  81282. if (newNode !== null) {
  81283. newNode.id = id;
  81284. newNode.parent = parent;
  81285. }
  81286. }
  81287. if (node.children) {
  81288. for (var i = 0; i < node.children.length; i++) {
  81289. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  81290. }
  81291. }
  81292. };
  81293. /**
  81294. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  81295. */
  81296. var postLoad = function (gltfRuntime) {
  81297. // Nodes
  81298. var currentScene = gltfRuntime.currentScene;
  81299. if (currentScene) {
  81300. for (var i = 0; i < currentScene.nodes.length; i++) {
  81301. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  81302. }
  81303. }
  81304. else {
  81305. for (var thing in gltfRuntime.scenes) {
  81306. currentScene = gltfRuntime.scenes[thing];
  81307. for (var i = 0; i < currentScene.nodes.length; i++) {
  81308. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  81309. }
  81310. }
  81311. }
  81312. // Set animations
  81313. loadAnimations(gltfRuntime);
  81314. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  81315. var skeleton = gltfRuntime.scene.skeletons[i];
  81316. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  81317. }
  81318. };
  81319. /**
  81320. * onBind shaderrs callback to set uniforms and matrices
  81321. */
  81322. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  81323. var materialValues = material.values || technique.parameters;
  81324. for (var unif in unTreatedUniforms) {
  81325. var uniform = unTreatedUniforms[unif];
  81326. var type = uniform.type;
  81327. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  81328. if (uniform.semantic && !uniform.source && !uniform.node) {
  81329. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  81330. }
  81331. else if (uniform.semantic && (uniform.source || uniform.node)) {
  81332. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  81333. if (source === null) {
  81334. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  81335. }
  81336. if (source === null) {
  81337. continue;
  81338. }
  81339. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  81340. }
  81341. }
  81342. else {
  81343. var value = materialValues[technique.uniforms[unif]];
  81344. if (!value) {
  81345. continue;
  81346. }
  81347. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  81348. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  81349. if (texture === null || texture === undefined) {
  81350. continue;
  81351. }
  81352. shaderMaterial.getEffect().setTexture(unif, texture);
  81353. }
  81354. else {
  81355. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  81356. }
  81357. }
  81358. }
  81359. onSuccess(shaderMaterial);
  81360. };
  81361. /**
  81362. * Prepare uniforms to send the only one time
  81363. * Loads the appropriate textures
  81364. */
  81365. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  81366. var materialValues = material.values || technique.parameters;
  81367. var techniqueUniforms = technique.uniforms;
  81368. /**
  81369. * Prepare values here (not matrices)
  81370. */
  81371. for (var unif in unTreatedUniforms) {
  81372. var uniform = unTreatedUniforms[unif];
  81373. var type = uniform.type;
  81374. var value = materialValues[techniqueUniforms[unif]];
  81375. if (value === undefined) {
  81376. // In case the value is the same for all materials
  81377. value = uniform.value;
  81378. }
  81379. if (!value) {
  81380. continue;
  81381. }
  81382. var onLoadTexture = function (uniformName) {
  81383. return function (texture) {
  81384. if (uniform.value && uniformName) {
  81385. // Static uniform
  81386. shaderMaterial.setTexture(uniformName, texture);
  81387. delete unTreatedUniforms[uniformName];
  81388. }
  81389. };
  81390. };
  81391. // Texture (sampler2D)
  81392. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  81393. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  81394. }
  81395. else {
  81396. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  81397. // Static uniform
  81398. delete unTreatedUniforms[unif];
  81399. }
  81400. }
  81401. }
  81402. };
  81403. /**
  81404. * Shader compilation failed
  81405. */
  81406. var onShaderCompileError = function (program, shaderMaterial, onError) {
  81407. return function (effect, error) {
  81408. shaderMaterial.dispose(true);
  81409. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  81410. };
  81411. };
  81412. /**
  81413. * Shader compilation success
  81414. */
  81415. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  81416. return function (_) {
  81417. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  81418. shaderMaterial.onBind = function (mesh) {
  81419. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  81420. };
  81421. };
  81422. };
  81423. /**
  81424. * Returns the appropriate uniform if already handled by babylon
  81425. */
  81426. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  81427. for (var unif in technique.uniforms) {
  81428. var uniform = technique.uniforms[unif];
  81429. var uniformParameter = technique.parameters[uniform];
  81430. if (tokenizer.currentIdentifier === unif) {
  81431. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  81432. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  81433. if (transformIndex !== -1) {
  81434. delete unTreatedUniforms[unif];
  81435. return babylonTransforms[transformIndex];
  81436. }
  81437. }
  81438. }
  81439. }
  81440. return tokenizer.currentIdentifier;
  81441. };
  81442. /**
  81443. * All shaders loaded. Create materials one by one
  81444. */
  81445. var importMaterials = function (gltfRuntime) {
  81446. // Create materials
  81447. for (var mat in gltfRuntime.materials) {
  81448. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  81449. }
  81450. };
  81451. /**
  81452. * Implementation of the base glTF spec
  81453. */
  81454. var GLTFLoaderBase = /** @class */ (function () {
  81455. function GLTFLoaderBase() {
  81456. }
  81457. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  81458. var gltfRuntime = {
  81459. extensions: {},
  81460. accessors: {},
  81461. buffers: {},
  81462. bufferViews: {},
  81463. meshes: {},
  81464. lights: {},
  81465. cameras: {},
  81466. nodes: {},
  81467. images: {},
  81468. textures: {},
  81469. shaders: {},
  81470. programs: {},
  81471. samplers: {},
  81472. techniques: {},
  81473. materials: {},
  81474. animations: {},
  81475. skins: {},
  81476. extensionsUsed: [],
  81477. scenes: {},
  81478. buffersCount: 0,
  81479. shaderscount: 0,
  81480. scene: scene,
  81481. rootUrl: rootUrl,
  81482. loadedBufferCount: 0,
  81483. loadedBufferViews: {},
  81484. loadedShaderCount: 0,
  81485. importOnlyMeshes: false,
  81486. dummyNodes: []
  81487. };
  81488. // Parse
  81489. if (parsedData.extensions) {
  81490. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  81491. }
  81492. if (parsedData.extensionsUsed) {
  81493. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  81494. }
  81495. if (parsedData.buffers) {
  81496. parseBuffers(parsedData.buffers, gltfRuntime);
  81497. }
  81498. if (parsedData.bufferViews) {
  81499. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  81500. }
  81501. if (parsedData.accessors) {
  81502. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  81503. }
  81504. if (parsedData.meshes) {
  81505. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  81506. }
  81507. if (parsedData.lights) {
  81508. parseObject(parsedData.lights, "lights", gltfRuntime);
  81509. }
  81510. if (parsedData.cameras) {
  81511. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  81512. }
  81513. if (parsedData.nodes) {
  81514. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  81515. }
  81516. if (parsedData.images) {
  81517. parseObject(parsedData.images, "images", gltfRuntime);
  81518. }
  81519. if (parsedData.textures) {
  81520. parseObject(parsedData.textures, "textures", gltfRuntime);
  81521. }
  81522. if (parsedData.shaders) {
  81523. parseShaders(parsedData.shaders, gltfRuntime);
  81524. }
  81525. if (parsedData.programs) {
  81526. parseObject(parsedData.programs, "programs", gltfRuntime);
  81527. }
  81528. if (parsedData.samplers) {
  81529. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  81530. }
  81531. if (parsedData.techniques) {
  81532. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  81533. }
  81534. if (parsedData.materials) {
  81535. parseObject(parsedData.materials, "materials", gltfRuntime);
  81536. }
  81537. if (parsedData.animations) {
  81538. parseObject(parsedData.animations, "animations", gltfRuntime);
  81539. }
  81540. if (parsedData.skins) {
  81541. parseObject(parsedData.skins, "skins", gltfRuntime);
  81542. }
  81543. if (parsedData.scenes) {
  81544. gltfRuntime.scenes = parsedData.scenes;
  81545. }
  81546. if (parsedData.scene && parsedData.scenes) {
  81547. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  81548. }
  81549. return gltfRuntime;
  81550. };
  81551. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  81552. var buffer = gltfRuntime.buffers[id];
  81553. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  81554. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  81555. }
  81556. else {
  81557. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  81558. if (request) {
  81559. onError(request.status + " " + request.statusText);
  81560. }
  81561. });
  81562. }
  81563. };
  81564. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  81565. var texture = gltfRuntime.textures[id];
  81566. if (!texture || !texture.source) {
  81567. onError("");
  81568. return;
  81569. }
  81570. if (texture.babylonTexture) {
  81571. onSuccess(null);
  81572. return;
  81573. }
  81574. var source = gltfRuntime.images[texture.source];
  81575. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  81576. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  81577. }
  81578. else {
  81579. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  81580. if (request) {
  81581. onError(request.status + " " + request.statusText);
  81582. }
  81583. });
  81584. }
  81585. };
  81586. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  81587. var texture = gltfRuntime.textures[id];
  81588. if (texture.babylonTexture) {
  81589. onSuccess(texture.babylonTexture);
  81590. return;
  81591. }
  81592. var sampler = gltfRuntime.samplers[texture.sampler];
  81593. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  81594. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  81595. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  81596. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  81597. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  81598. var blob = new Blob([buffer]);
  81599. var blobURL = URL.createObjectURL(blob);
  81600. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  81601. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  81602. if (sampler.wrapS !== undefined) {
  81603. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  81604. }
  81605. if (sampler.wrapT !== undefined) {
  81606. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  81607. }
  81608. newTexture.name = id;
  81609. texture.babylonTexture = newTexture;
  81610. onSuccess(newTexture);
  81611. };
  81612. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  81613. var shader = gltfRuntime.shaders[id];
  81614. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  81615. var shaderString = atob(shader.uri.split(",")[1]);
  81616. onSuccess(shaderString);
  81617. }
  81618. else {
  81619. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  81620. if (request) {
  81621. onError(request.status + " " + request.statusText);
  81622. }
  81623. });
  81624. }
  81625. };
  81626. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  81627. var material = gltfRuntime.materials[id];
  81628. if (!material.technique) {
  81629. if (onError) {
  81630. onError("No technique found.");
  81631. }
  81632. return;
  81633. }
  81634. var technique = gltfRuntime.techniques[material.technique];
  81635. if (!technique) {
  81636. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  81637. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  81638. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  81639. onSuccess(defaultMaterial);
  81640. return;
  81641. }
  81642. var program = gltfRuntime.programs[technique.program];
  81643. var states = technique.states;
  81644. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  81645. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  81646. var newVertexShader = "";
  81647. var newPixelShader = "";
  81648. var vertexTokenizer = new Tokenizer(vertexShader);
  81649. var pixelTokenizer = new Tokenizer(pixelShader);
  81650. var unTreatedUniforms = {};
  81651. var uniforms = [];
  81652. var attributes = [];
  81653. var samplers = [];
  81654. // Fill uniform, sampler2D and attributes
  81655. for (var unif in technique.uniforms) {
  81656. var uniform = technique.uniforms[unif];
  81657. var uniformParameter = technique.parameters[uniform];
  81658. unTreatedUniforms[unif] = uniformParameter;
  81659. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  81660. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  81661. if (transformIndex !== -1) {
  81662. uniforms.push(babylonTransforms[transformIndex]);
  81663. delete unTreatedUniforms[unif];
  81664. }
  81665. else {
  81666. uniforms.push(unif);
  81667. }
  81668. }
  81669. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  81670. samplers.push(unif);
  81671. }
  81672. else {
  81673. uniforms.push(unif);
  81674. }
  81675. }
  81676. for (var attr in technique.attributes) {
  81677. var attribute = technique.attributes[attr];
  81678. var attributeParameter = technique.parameters[attribute];
  81679. if (attributeParameter.semantic) {
  81680. attributes.push(getAttribute(attributeParameter));
  81681. }
  81682. }
  81683. // Configure vertex shader
  81684. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  81685. var tokenType = vertexTokenizer.currentToken;
  81686. if (tokenType !== ETokenType.IDENTIFIER) {
  81687. newVertexShader += vertexTokenizer.currentString;
  81688. continue;
  81689. }
  81690. var foundAttribute = false;
  81691. for (var attr in technique.attributes) {
  81692. var attribute = technique.attributes[attr];
  81693. var attributeParameter = technique.parameters[attribute];
  81694. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  81695. newVertexShader += getAttribute(attributeParameter);
  81696. foundAttribute = true;
  81697. break;
  81698. }
  81699. }
  81700. if (foundAttribute) {
  81701. continue;
  81702. }
  81703. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  81704. }
  81705. // Configure pixel shader
  81706. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  81707. var tokenType = pixelTokenizer.currentToken;
  81708. if (tokenType !== ETokenType.IDENTIFIER) {
  81709. newPixelShader += pixelTokenizer.currentString;
  81710. continue;
  81711. }
  81712. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  81713. }
  81714. // Create shader material
  81715. var shaderPath = {
  81716. vertex: program.vertexShader + id,
  81717. fragment: program.fragmentShader + id
  81718. };
  81719. var options = {
  81720. attributes: attributes,
  81721. uniforms: uniforms,
  81722. samplers: samplers,
  81723. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  81724. };
  81725. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  81726. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  81727. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  81728. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  81729. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  81730. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  81731. if (states && states.functions) {
  81732. var functions = states.functions;
  81733. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  81734. shaderMaterial.backFaceCulling = false;
  81735. }
  81736. var blendFunc = functions.blendFuncSeparate;
  81737. if (blendFunc) {
  81738. if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  81739. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  81740. }
  81741. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  81742. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  81743. }
  81744. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  81745. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  81746. }
  81747. else if (blendFunc[0] === GLTF1.EBlendingFunction.ZERO && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  81748. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  81749. }
  81750. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  81751. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  81752. }
  81753. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  81754. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  81755. }
  81756. }
  81757. }
  81758. };
  81759. return GLTFLoaderBase;
  81760. }());
  81761. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  81762. /**
  81763. * glTF V1 Loader
  81764. */
  81765. var GLTFLoader = /** @class */ (function () {
  81766. function GLTFLoader() {
  81767. }
  81768. GLTFLoader.RegisterExtension = function (extension) {
  81769. if (GLTFLoader.Extensions[extension.name]) {
  81770. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  81771. return;
  81772. }
  81773. GLTFLoader.Extensions[extension.name] = extension;
  81774. };
  81775. GLTFLoader.prototype.dispose = function () {
  81776. // do nothing
  81777. };
  81778. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  81779. var _this = this;
  81780. scene.useRightHandedSystem = true;
  81781. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  81782. gltfRuntime.importOnlyMeshes = true;
  81783. if (meshesNames === "") {
  81784. gltfRuntime.importMeshesNames = [];
  81785. }
  81786. else if (typeof meshesNames === "string") {
  81787. gltfRuntime.importMeshesNames = [meshesNames];
  81788. }
  81789. else if (meshesNames && !(meshesNames instanceof Array)) {
  81790. gltfRuntime.importMeshesNames = [meshesNames];
  81791. }
  81792. else {
  81793. gltfRuntime.importMeshesNames = [];
  81794. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  81795. }
  81796. // Create nodes
  81797. _this._createNodes(gltfRuntime);
  81798. var meshes = new Array();
  81799. var skeletons = new Array();
  81800. // Fill arrays of meshes and skeletons
  81801. for (var nde in gltfRuntime.nodes) {
  81802. var node = gltfRuntime.nodes[nde];
  81803. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  81804. meshes.push(node.babylonNode);
  81805. }
  81806. }
  81807. for (var skl in gltfRuntime.skins) {
  81808. var skin = gltfRuntime.skins[skl];
  81809. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  81810. skeletons.push(skin.babylonSkeleton);
  81811. }
  81812. }
  81813. // Load buffers, shaders, materials, etc.
  81814. _this._loadBuffersAsync(gltfRuntime, function () {
  81815. _this._loadShadersAsync(gltfRuntime, function () {
  81816. importMaterials(gltfRuntime);
  81817. postLoad(gltfRuntime);
  81818. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  81819. onSuccess(meshes, [], skeletons);
  81820. }
  81821. });
  81822. }, onProgress);
  81823. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  81824. onSuccess(meshes, [], skeletons);
  81825. }
  81826. }, onError);
  81827. return true;
  81828. };
  81829. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  81830. var _this = this;
  81831. scene.useRightHandedSystem = true;
  81832. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  81833. // Load runtime extensios
  81834. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  81835. // Create nodes
  81836. _this._createNodes(gltfRuntime);
  81837. // Load buffers, shaders, materials, etc.
  81838. _this._loadBuffersAsync(gltfRuntime, function () {
  81839. _this._loadShadersAsync(gltfRuntime, function () {
  81840. importMaterials(gltfRuntime);
  81841. postLoad(gltfRuntime);
  81842. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  81843. onSuccess();
  81844. }
  81845. });
  81846. });
  81847. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  81848. onSuccess();
  81849. }
  81850. }, onError);
  81851. }, onError);
  81852. };
  81853. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  81854. var hasShaders = false;
  81855. var processShader = function (sha, shader) {
  81856. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  81857. gltfRuntime.loadedShaderCount++;
  81858. if (shaderString) {
  81859. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  81860. }
  81861. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  81862. onload();
  81863. }
  81864. }, function () {
  81865. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  81866. });
  81867. };
  81868. for (var sha in gltfRuntime.shaders) {
  81869. hasShaders = true;
  81870. var shader = gltfRuntime.shaders[sha];
  81871. if (shader) {
  81872. processShader.bind(this, sha, shader)();
  81873. }
  81874. else {
  81875. BABYLON.Tools.Error("No shader named: " + sha);
  81876. }
  81877. }
  81878. if (!hasShaders) {
  81879. onload();
  81880. }
  81881. };
  81882. ;
  81883. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  81884. var hasBuffers = false;
  81885. var processBuffer = function (buf, buffer) {
  81886. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  81887. gltfRuntime.loadedBufferCount++;
  81888. if (bufferView) {
  81889. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  81890. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  81891. }
  81892. gltfRuntime.loadedBufferViews[buf] = bufferView;
  81893. }
  81894. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  81895. onLoad();
  81896. }
  81897. }, function () {
  81898. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  81899. });
  81900. };
  81901. for (var buf in gltfRuntime.buffers) {
  81902. hasBuffers = true;
  81903. var buffer = gltfRuntime.buffers[buf];
  81904. if (buffer) {
  81905. processBuffer.bind(this, buf, buffer)();
  81906. }
  81907. else {
  81908. BABYLON.Tools.Error("No buffer named: " + buf);
  81909. }
  81910. }
  81911. if (!hasBuffers) {
  81912. onLoad();
  81913. }
  81914. };
  81915. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  81916. var currentScene = gltfRuntime.currentScene;
  81917. if (currentScene) {
  81918. // Only one scene even if multiple scenes are defined
  81919. for (var i = 0; i < currentScene.nodes.length; i++) {
  81920. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  81921. }
  81922. }
  81923. else {
  81924. // Load all scenes
  81925. for (var thing in gltfRuntime.scenes) {
  81926. currentScene = gltfRuntime.scenes[thing];
  81927. for (var i = 0; i < currentScene.nodes.length; i++) {
  81928. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  81929. }
  81930. }
  81931. }
  81932. };
  81933. GLTFLoader.Extensions = {};
  81934. return GLTFLoader;
  81935. }());
  81936. GLTF1.GLTFLoader = GLTFLoader;
  81937. ;
  81938. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  81939. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  81940. })(BABYLON || (BABYLON = {}));
  81941. //# sourceMappingURL=babylon.glTFLoader.js.map
  81942. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  81943. var BABYLON;
  81944. (function (BABYLON) {
  81945. var GLTF1;
  81946. (function (GLTF1) {
  81947. /**
  81948. * Utils functions for GLTF
  81949. */
  81950. var GLTFUtils = /** @class */ (function () {
  81951. function GLTFUtils() {
  81952. }
  81953. /**
  81954. * Sets the given "parameter" matrix
  81955. * @param scene: the {BABYLON.Scene} object
  81956. * @param source: the source node where to pick the matrix
  81957. * @param parameter: the GLTF technique parameter
  81958. * @param uniformName: the name of the shader's uniform
  81959. * @param shaderMaterial: the shader material
  81960. */
  81961. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  81962. var mat = null;
  81963. if (parameter.semantic === "MODEL") {
  81964. mat = source.getWorldMatrix();
  81965. }
  81966. else if (parameter.semantic === "PROJECTION") {
  81967. mat = scene.getProjectionMatrix();
  81968. }
  81969. else if (parameter.semantic === "VIEW") {
  81970. mat = scene.getViewMatrix();
  81971. }
  81972. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  81973. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  81974. }
  81975. else if (parameter.semantic === "MODELVIEW") {
  81976. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  81977. }
  81978. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  81979. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  81980. }
  81981. else if (parameter.semantic === "MODELINVERSE") {
  81982. mat = source.getWorldMatrix().invert();
  81983. }
  81984. else if (parameter.semantic === "VIEWINVERSE") {
  81985. mat = scene.getViewMatrix().invert();
  81986. }
  81987. else if (parameter.semantic === "PROJECTIONINVERSE") {
  81988. mat = scene.getProjectionMatrix().invert();
  81989. }
  81990. else if (parameter.semantic === "MODELVIEWINVERSE") {
  81991. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  81992. }
  81993. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  81994. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  81995. }
  81996. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  81997. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  81998. }
  81999. else {
  82000. debugger;
  82001. }
  82002. if (mat) {
  82003. switch (parameter.type) {
  82004. case GLTF1.EParameterType.FLOAT_MAT2:
  82005. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  82006. break;
  82007. case GLTF1.EParameterType.FLOAT_MAT3:
  82008. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  82009. break;
  82010. case GLTF1.EParameterType.FLOAT_MAT4:
  82011. shaderMaterial.setMatrix(uniformName, mat);
  82012. break;
  82013. default: break;
  82014. }
  82015. }
  82016. };
  82017. /**
  82018. * Sets the given "parameter" matrix
  82019. * @param shaderMaterial: the shader material
  82020. * @param uniform: the name of the shader's uniform
  82021. * @param value: the value of the uniform
  82022. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  82023. */
  82024. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  82025. switch (type) {
  82026. case GLTF1.EParameterType.FLOAT:
  82027. shaderMaterial.setFloat(uniform, value);
  82028. return true;
  82029. case GLTF1.EParameterType.FLOAT_VEC2:
  82030. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  82031. return true;
  82032. case GLTF1.EParameterType.FLOAT_VEC3:
  82033. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  82034. return true;
  82035. case GLTF1.EParameterType.FLOAT_VEC4:
  82036. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  82037. return true;
  82038. default: return false;
  82039. }
  82040. };
  82041. /**
  82042. * If the uri is a base64 string
  82043. * @param uri: the uri to test
  82044. */
  82045. GLTFUtils.IsBase64 = function (uri) {
  82046. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  82047. };
  82048. /**
  82049. * Decode the base64 uri
  82050. * @param uri: the uri to decode
  82051. */
  82052. GLTFUtils.DecodeBase64 = function (uri) {
  82053. var decodedString = atob(uri.split(",")[1]);
  82054. var bufferLength = decodedString.length;
  82055. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  82056. for (var i = 0; i < bufferLength; i++) {
  82057. bufferView[i] = decodedString.charCodeAt(i);
  82058. }
  82059. return bufferView.buffer;
  82060. };
  82061. /**
  82062. * Returns the wrap mode of the texture
  82063. * @param mode: the mode value
  82064. */
  82065. GLTFUtils.GetWrapMode = function (mode) {
  82066. switch (mode) {
  82067. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  82068. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  82069. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  82070. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  82071. }
  82072. };
  82073. /**
  82074. * Returns the byte stride giving an accessor
  82075. * @param accessor: the GLTF accessor objet
  82076. */
  82077. GLTFUtils.GetByteStrideFromType = function (accessor) {
  82078. // Needs this function since "byteStride" isn't requiered in glTF format
  82079. var type = accessor.type;
  82080. switch (type) {
  82081. case "VEC2": return 2;
  82082. case "VEC3": return 3;
  82083. case "VEC4": return 4;
  82084. case "MAT2": return 4;
  82085. case "MAT3": return 9;
  82086. case "MAT4": return 16;
  82087. default: return 1;
  82088. }
  82089. };
  82090. /**
  82091. * Returns the texture filter mode giving a mode value
  82092. * @param mode: the filter mode value
  82093. */
  82094. GLTFUtils.GetTextureFilterMode = function (mode) {
  82095. switch (mode) {
  82096. case GLTF1.ETextureFilterType.LINEAR:
  82097. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  82098. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  82099. case GLTF1.ETextureFilterType.NEAREST:
  82100. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  82101. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  82102. }
  82103. };
  82104. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  82105. var byteOffset = bufferView.byteOffset + byteOffset;
  82106. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  82107. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  82108. throw new Error("Buffer access is out of range");
  82109. }
  82110. var buffer = loadedBufferView.buffer;
  82111. byteOffset += loadedBufferView.byteOffset;
  82112. switch (componentType) {
  82113. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  82114. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  82115. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  82116. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  82117. default: return new Float32Array(buffer, byteOffset, byteLength);
  82118. }
  82119. };
  82120. /**
  82121. * Returns a buffer from its accessor
  82122. * @param gltfRuntime: the GLTF runtime
  82123. * @param accessor: the GLTF accessor
  82124. */
  82125. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  82126. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  82127. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  82128. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  82129. };
  82130. /**
  82131. * Decodes a buffer view into a string
  82132. * @param view: the buffer view
  82133. */
  82134. GLTFUtils.DecodeBufferToText = function (view) {
  82135. var result = "";
  82136. var length = view.byteLength;
  82137. for (var i = 0; i < length; ++i) {
  82138. result += String.fromCharCode(view[i]);
  82139. }
  82140. return result;
  82141. };
  82142. /**
  82143. * Returns the default material of gltf. Related to
  82144. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  82145. * @param scene: the Babylon.js scene
  82146. */
  82147. GLTFUtils.GetDefaultMaterial = function (scene) {
  82148. if (!GLTFUtils._DefaultMaterial) {
  82149. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  82150. "precision highp float;",
  82151. "",
  82152. "uniform mat4 worldView;",
  82153. "uniform mat4 projection;",
  82154. "",
  82155. "attribute vec3 position;",
  82156. "",
  82157. "void main(void)",
  82158. "{",
  82159. " gl_Position = projection * worldView * vec4(position, 1.0);",
  82160. "}"
  82161. ].join("\n");
  82162. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  82163. "precision highp float;",
  82164. "",
  82165. "uniform vec4 u_emission;",
  82166. "",
  82167. "void main(void)",
  82168. "{",
  82169. " gl_FragColor = u_emission;",
  82170. "}"
  82171. ].join("\n");
  82172. var shaderPath = {
  82173. vertex: "GLTFDefaultMaterial",
  82174. fragment: "GLTFDefaultMaterial"
  82175. };
  82176. var options = {
  82177. attributes: ["position"],
  82178. uniforms: ["worldView", "projection", "u_emission"],
  82179. samplers: new Array(),
  82180. needAlphaBlending: false
  82181. };
  82182. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  82183. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  82184. }
  82185. return GLTFUtils._DefaultMaterial;
  82186. };
  82187. // The GLTF default material
  82188. GLTFUtils._DefaultMaterial = null;
  82189. return GLTFUtils;
  82190. }());
  82191. GLTF1.GLTFUtils = GLTFUtils;
  82192. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  82193. })(BABYLON || (BABYLON = {}));
  82194. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  82195. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  82196. var BABYLON;
  82197. (function (BABYLON) {
  82198. var GLTF1;
  82199. (function (GLTF1) {
  82200. var GLTFLoaderExtension = /** @class */ (function () {
  82201. function GLTFLoaderExtension(name) {
  82202. this._name = name;
  82203. }
  82204. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  82205. get: function () {
  82206. return this._name;
  82207. },
  82208. enumerable: true,
  82209. configurable: true
  82210. });
  82211. /**
  82212. * Defines an override for loading the runtime
  82213. * Return true to stop further extensions from loading the runtime
  82214. */
  82215. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  82216. return false;
  82217. };
  82218. /**
  82219. * Defines an onverride for creating gltf runtime
  82220. * Return true to stop further extensions from creating the runtime
  82221. */
  82222. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  82223. return false;
  82224. };
  82225. /**
  82226. * Defines an override for loading buffers
  82227. * Return true to stop further extensions from loading this buffer
  82228. */
  82229. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  82230. return false;
  82231. };
  82232. /**
  82233. * Defines an override for loading texture buffers
  82234. * Return true to stop further extensions from loading this texture data
  82235. */
  82236. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  82237. return false;
  82238. };
  82239. /**
  82240. * Defines an override for creating textures
  82241. * Return true to stop further extensions from loading this texture
  82242. */
  82243. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  82244. return false;
  82245. };
  82246. /**
  82247. * Defines an override for loading shader strings
  82248. * Return true to stop further extensions from loading this shader data
  82249. */
  82250. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  82251. return false;
  82252. };
  82253. /**
  82254. * Defines an override for loading materials
  82255. * Return true to stop further extensions from loading this material
  82256. */
  82257. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  82258. return false;
  82259. };
  82260. // ---------
  82261. // Utilities
  82262. // ---------
  82263. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  82264. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  82265. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  82266. }, function () {
  82267. setTimeout(function () {
  82268. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  82269. });
  82270. });
  82271. };
  82272. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  82273. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  82274. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  82275. }, function () {
  82276. setTimeout(function () {
  82277. onSuccess();
  82278. });
  82279. });
  82280. };
  82281. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  82282. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  82283. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  82284. }, function () {
  82285. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  82286. });
  82287. };
  82288. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  82289. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  82290. };
  82291. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  82292. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  82293. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  82294. }, function () {
  82295. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  82296. });
  82297. };
  82298. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  82299. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  82300. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  82301. }, function () {
  82302. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  82303. });
  82304. };
  82305. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  82306. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  82307. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  82308. }, function () {
  82309. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  82310. });
  82311. };
  82312. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  82313. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  82314. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  82315. }, function () {
  82316. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  82317. });
  82318. };
  82319. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  82320. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  82321. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  82322. if (func(loaderExtension)) {
  82323. return;
  82324. }
  82325. }
  82326. defaultFunc();
  82327. };
  82328. return GLTFLoaderExtension;
  82329. }());
  82330. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  82331. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  82332. })(BABYLON || (BABYLON = {}));
  82333. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  82334. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  82335. var BABYLON;
  82336. (function (BABYLON) {
  82337. var GLTF1;
  82338. (function (GLTF1) {
  82339. var BinaryExtensionBufferName = "binary_glTF";
  82340. ;
  82341. ;
  82342. var GLTFBinaryExtension = /** @class */ (function (_super) {
  82343. __extends(GLTFBinaryExtension, _super);
  82344. function GLTFBinaryExtension() {
  82345. return _super.call(this, "KHR_binary_glTF") || this;
  82346. }
  82347. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  82348. var extensionsUsed = data.json.extensionsUsed;
  82349. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  82350. return false;
  82351. }
  82352. this._bin = data.bin;
  82353. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  82354. return true;
  82355. };
  82356. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  82357. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  82358. return false;
  82359. }
  82360. if (id !== BinaryExtensionBufferName) {
  82361. return false;
  82362. }
  82363. onSuccess(this._bin);
  82364. return true;
  82365. };
  82366. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  82367. var texture = gltfRuntime.textures[id];
  82368. var source = gltfRuntime.images[texture.source];
  82369. if (!source.extensions || !(this.name in source.extensions)) {
  82370. return false;
  82371. }
  82372. var sourceExt = source.extensions[this.name];
  82373. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  82374. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  82375. onSuccess(buffer);
  82376. return true;
  82377. };
  82378. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  82379. var shader = gltfRuntime.shaders[id];
  82380. if (!shader.extensions || !(this.name in shader.extensions)) {
  82381. return false;
  82382. }
  82383. var binaryExtensionShader = shader.extensions[this.name];
  82384. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  82385. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  82386. setTimeout(function () {
  82387. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  82388. onSuccess(shaderString);
  82389. });
  82390. return true;
  82391. };
  82392. return GLTFBinaryExtension;
  82393. }(GLTF1.GLTFLoaderExtension));
  82394. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  82395. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  82396. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  82397. })(BABYLON || (BABYLON = {}));
  82398. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  82399. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  82400. var BABYLON;
  82401. (function (BABYLON) {
  82402. var GLTF1;
  82403. (function (GLTF1) {
  82404. ;
  82405. ;
  82406. ;
  82407. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  82408. __extends(GLTFMaterialsCommonExtension, _super);
  82409. function GLTFMaterialsCommonExtension() {
  82410. return _super.call(this, "KHR_materials_common") || this;
  82411. }
  82412. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  82413. if (!gltfRuntime.extensions)
  82414. return false;
  82415. var extension = gltfRuntime.extensions[this.name];
  82416. if (!extension)
  82417. return false;
  82418. // Create lights
  82419. var lights = extension.lights;
  82420. if (lights) {
  82421. for (var thing in lights) {
  82422. var light = lights[thing];
  82423. switch (light.type) {
  82424. case "ambient":
  82425. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  82426. var ambient = light.ambient;
  82427. if (ambient) {
  82428. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  82429. }
  82430. break;
  82431. case "point":
  82432. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  82433. var point = light.point;
  82434. if (point) {
  82435. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  82436. }
  82437. break;
  82438. case "directional":
  82439. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  82440. var directional = light.directional;
  82441. if (directional) {
  82442. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  82443. }
  82444. break;
  82445. case "spot":
  82446. var spot = light.spot;
  82447. if (spot) {
  82448. var spotLight = new BABYLON.SpotLight(light.name, new BABYLON.Vector3(0, 10, 0), new BABYLON.Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene);
  82449. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  82450. }
  82451. break;
  82452. default:
  82453. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  82454. break;
  82455. }
  82456. }
  82457. }
  82458. return false;
  82459. };
  82460. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  82461. var material = gltfRuntime.materials[id];
  82462. if (!material || !material.extensions)
  82463. return false;
  82464. var extension = material.extensions[this.name];
  82465. if (!extension)
  82466. return false;
  82467. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  82468. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  82469. if (extension.technique === "CONSTANT") {
  82470. standardMaterial.disableLighting = true;
  82471. }
  82472. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  82473. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  82474. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  82475. // Ambient
  82476. if (typeof extension.values.ambient === "string") {
  82477. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  82478. }
  82479. else {
  82480. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  82481. }
  82482. // Diffuse
  82483. if (typeof extension.values.diffuse === "string") {
  82484. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  82485. }
  82486. else {
  82487. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  82488. }
  82489. // Emission
  82490. if (typeof extension.values.emission === "string") {
  82491. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  82492. }
  82493. else {
  82494. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  82495. }
  82496. // Specular
  82497. if (typeof extension.values.specular === "string") {
  82498. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  82499. }
  82500. else {
  82501. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  82502. }
  82503. return true;
  82504. };
  82505. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  82506. // Create buffer from texture url
  82507. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  82508. // Create texture from buffer
  82509. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  82510. }, onError);
  82511. };
  82512. return GLTFMaterialsCommonExtension;
  82513. }(GLTF1.GLTFLoaderExtension));
  82514. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  82515. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  82516. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  82517. })(BABYLON || (BABYLON = {}));
  82518. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  82519. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  82520. var BABYLON;
  82521. (function (BABYLON) {
  82522. var GLTF2;
  82523. (function (GLTF2) {
  82524. /**
  82525. * Enums
  82526. */
  82527. var EComponentType;
  82528. (function (EComponentType) {
  82529. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  82530. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  82531. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  82532. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  82533. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  82534. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  82535. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  82536. var EMeshPrimitiveMode;
  82537. (function (EMeshPrimitiveMode) {
  82538. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  82539. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  82540. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  82541. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  82542. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  82543. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  82544. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  82545. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  82546. var ETextureMagFilter;
  82547. (function (ETextureMagFilter) {
  82548. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  82549. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  82550. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  82551. var ETextureMinFilter;
  82552. (function (ETextureMinFilter) {
  82553. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  82554. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  82555. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  82556. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  82557. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  82558. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  82559. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  82560. var ETextureWrapMode;
  82561. (function (ETextureWrapMode) {
  82562. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  82563. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  82564. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  82565. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  82566. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  82567. })(BABYLON || (BABYLON = {}));
  82568. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  82569. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  82570. var BABYLON;
  82571. (function (BABYLON) {
  82572. var GLTF2;
  82573. (function (GLTF2) {
  82574. var GLTFLoaderTracker = /** @class */ (function () {
  82575. function GLTFLoaderTracker(onComplete) {
  82576. this._pendingCount = 0;
  82577. this._callback = onComplete;
  82578. }
  82579. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  82580. this._pendingCount++;
  82581. };
  82582. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  82583. if (--this._pendingCount === 0) {
  82584. this._callback();
  82585. }
  82586. };
  82587. return GLTFLoaderTracker;
  82588. }());
  82589. var GLTFLoader = /** @class */ (function () {
  82590. function GLTFLoader(parent) {
  82591. this._disposed = false;
  82592. this._defaultSampler = {};
  82593. this._renderReady = false;
  82594. this._requests = new Array();
  82595. this._renderReadyObservable = new BABYLON.Observable();
  82596. // Count of pending work that needs to complete before the asset is rendered.
  82597. this._renderPendingCount = 0;
  82598. // Count of pending work that needs to complete before the loader is disposed.
  82599. this._loaderPendingCount = 0;
  82600. this._loaderTrackers = new Array();
  82601. this._parent = parent;
  82602. }
  82603. GLTFLoader.RegisterExtension = function (extension) {
  82604. if (GLTFLoader.Extensions[extension.name]) {
  82605. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  82606. return;
  82607. }
  82608. GLTFLoader.Extensions[extension.name] = extension;
  82609. // Keep the order of registration so that extensions registered first are called first.
  82610. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  82611. };
  82612. GLTFLoader.prototype.dispose = function () {
  82613. if (this._disposed) {
  82614. return;
  82615. }
  82616. this._disposed = true;
  82617. // Abort requests that are not complete
  82618. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  82619. var request = _a[_i];
  82620. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  82621. request.abort();
  82622. }
  82623. }
  82624. // Revoke object urls created during load
  82625. if (this._gltf.textures) {
  82626. for (var _b = 0, _c = this._gltf.textures; _b < _c.length; _b++) {
  82627. var texture = _c[_b];
  82628. if (texture.url) {
  82629. URL.revokeObjectURL(texture.url);
  82630. }
  82631. }
  82632. }
  82633. };
  82634. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  82635. var _this = this;
  82636. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  82637. if (onSuccess) {
  82638. onSuccess(_this._getMeshes(), [], _this._getSkeletons());
  82639. }
  82640. }, onProgress, onError);
  82641. };
  82642. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  82643. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  82644. };
  82645. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  82646. var _this = this;
  82647. this._babylonScene = scene;
  82648. this._rootUrl = rootUrl;
  82649. this._successCallback = onSuccess;
  82650. this._progressCallback = onProgress;
  82651. this._errorCallback = onError;
  82652. this._tryCatchOnError(function () {
  82653. _this._loadData(data);
  82654. _this._addPendingData(_this);
  82655. _this._loadDefaultScene(nodeNames);
  82656. _this._loadAnimations();
  82657. _this._removePendingData(_this);
  82658. });
  82659. };
  82660. GLTFLoader.prototype._onProgress = function () {
  82661. if (!this._progressCallback) {
  82662. return;
  82663. }
  82664. var lengthComputable = true;
  82665. var loaded = 0;
  82666. var total = 0;
  82667. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  82668. var request = _a[_i];
  82669. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  82670. return;
  82671. }
  82672. lengthComputable = lengthComputable && request._lengthComputable;
  82673. loaded += request._loaded;
  82674. total += request._total;
  82675. }
  82676. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  82677. };
  82678. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  82679. if (this._renderReady) {
  82680. func();
  82681. }
  82682. else {
  82683. this._renderReadyObservable.add(func);
  82684. }
  82685. };
  82686. GLTFLoader.prototype._onRenderReady = function () {
  82687. this._rootNode.babylonMesh.setEnabled(true);
  82688. this._startAnimations();
  82689. if (this._successCallback) {
  82690. this._successCallback();
  82691. }
  82692. this._renderReadyObservable.notifyObservers(this);
  82693. };
  82694. GLTFLoader.prototype._onComplete = function () {
  82695. if (this._parent.onComplete) {
  82696. this._parent.onComplete();
  82697. }
  82698. this.dispose();
  82699. };
  82700. GLTFLoader.prototype._loadData = function (data) {
  82701. this._gltf = data.json;
  82702. // Assign the index of each object for convinience.
  82703. GLTFLoader._AssignIndices(this._gltf.accessors);
  82704. GLTFLoader._AssignIndices(this._gltf.animations);
  82705. GLTFLoader._AssignIndices(this._gltf.buffers);
  82706. GLTFLoader._AssignIndices(this._gltf.bufferViews);
  82707. GLTFLoader._AssignIndices(this._gltf.images);
  82708. GLTFLoader._AssignIndices(this._gltf.materials);
  82709. GLTFLoader._AssignIndices(this._gltf.meshes);
  82710. GLTFLoader._AssignIndices(this._gltf.nodes);
  82711. GLTFLoader._AssignIndices(this._gltf.samplers);
  82712. GLTFLoader._AssignIndices(this._gltf.scenes);
  82713. GLTFLoader._AssignIndices(this._gltf.skins);
  82714. GLTFLoader._AssignIndices(this._gltf.textures);
  82715. if (data.bin) {
  82716. var buffers = this._gltf.buffers;
  82717. if (buffers && buffers[0] && !buffers[0].uri) {
  82718. var binaryBuffer = buffers[0];
  82719. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  82720. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  82721. }
  82722. binaryBuffer.loadedData = data.bin;
  82723. }
  82724. else {
  82725. BABYLON.Tools.Warn("Unexpected BIN chunk");
  82726. }
  82727. }
  82728. };
  82729. GLTFLoader.prototype._getMeshes = function () {
  82730. var meshes = new Array();
  82731. // Root mesh is always first.
  82732. meshes.push(this._rootNode.babylonMesh);
  82733. var nodes = this._gltf.nodes;
  82734. if (nodes) {
  82735. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  82736. var node = nodes_1[_i];
  82737. if (node.babylonMesh) {
  82738. meshes.push(node.babylonMesh);
  82739. }
  82740. }
  82741. }
  82742. return meshes;
  82743. };
  82744. GLTFLoader.prototype._getSkeletons = function () {
  82745. var skeletons = new Array();
  82746. var skins = this._gltf.skins;
  82747. if (skins) {
  82748. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  82749. var skin = skins_1[_i];
  82750. if (skin.babylonSkeleton) {
  82751. skeletons.push(skin.babylonSkeleton);
  82752. }
  82753. }
  82754. }
  82755. return skeletons;
  82756. };
  82757. GLTFLoader.prototype._startAnimations = function () {
  82758. var animations = this._gltf.animations;
  82759. if (!animations) {
  82760. return;
  82761. }
  82762. switch (this._parent.animationStartMode) {
  82763. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  82764. // do nothing
  82765. break;
  82766. }
  82767. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  82768. var animation = animations[0];
  82769. for (var _i = 0, _a = animation.targets; _i < _a.length; _i++) {
  82770. var target = _a[_i];
  82771. this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true);
  82772. }
  82773. break;
  82774. }
  82775. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  82776. for (var _b = 0, animations_1 = animations; _b < animations_1.length; _b++) {
  82777. var animation = animations_1[_b];
  82778. for (var _c = 0, _d = animation.targets; _c < _d.length; _c++) {
  82779. var target = _d[_c];
  82780. this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true);
  82781. }
  82782. }
  82783. break;
  82784. }
  82785. default: {
  82786. BABYLON.Tools.Error("Invalid animation start mode " + this._parent.animationStartMode);
  82787. return;
  82788. }
  82789. }
  82790. };
  82791. GLTFLoader.prototype._loadDefaultScene = function (nodeNames) {
  82792. var scene = GLTFLoader._GetProperty(this._gltf.scenes, this._gltf.scene || 0);
  82793. if (!scene) {
  82794. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  82795. }
  82796. this._loadScene("#/scenes/" + scene.index, scene, nodeNames);
  82797. };
  82798. GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) {
  82799. var _this = this;
  82800. this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) };
  82801. switch (this._parent.coordinateSystemMode) {
  82802. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  82803. if (!this._babylonScene.useRightHandedSystem) {
  82804. this._rootNode.rotation = [0, 1, 0, 0];
  82805. this._rootNode.scale = [1, 1, -1];
  82806. this._loadTransform(this._rootNode);
  82807. }
  82808. break;
  82809. }
  82810. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  82811. this._babylonScene.useRightHandedSystem = true;
  82812. break;
  82813. }
  82814. default: {
  82815. BABYLON.Tools.Error("Invalid coordinate system mode " + this._parent.coordinateSystemMode);
  82816. return;
  82817. }
  82818. }
  82819. if (this._parent.onMeshLoaded) {
  82820. this._parent.onMeshLoaded(this._rootNode.babylonMesh);
  82821. }
  82822. var nodeIndices = scene.nodes;
  82823. this._traverseNodes(context, nodeIndices, function (node, parentNode) {
  82824. node.parent = parentNode;
  82825. return true;
  82826. }, this._rootNode);
  82827. if (nodeNames) {
  82828. if (!(nodeNames instanceof Array)) {
  82829. nodeNames = [nodeNames];
  82830. }
  82831. var filteredNodeIndices_1 = new Array();
  82832. this._traverseNodes(context, nodeIndices, function (node) {
  82833. if (nodeNames.indexOf(node.name) !== -1) {
  82834. filteredNodeIndices_1.push(node.index);
  82835. node.parent = _this._rootNode;
  82836. return false;
  82837. }
  82838. return true;
  82839. }, this._rootNode);
  82840. nodeIndices = filteredNodeIndices_1;
  82841. }
  82842. for (var _i = 0, nodeIndices_1 = nodeIndices; _i < nodeIndices_1.length; _i++) {
  82843. var index = nodeIndices_1[_i];
  82844. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  82845. if (!node) {
  82846. throw new Error(context + ": Failed to find node " + index);
  82847. }
  82848. this._loadNode("#/nodes/" + index, node);
  82849. }
  82850. // Disable the root mesh until the asset is ready to render.
  82851. this._rootNode.babylonMesh.setEnabled(false);
  82852. };
  82853. GLTFLoader.prototype._loadNode = function (context, node) {
  82854. if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) {
  82855. return;
  82856. }
  82857. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  82858. node.babylonMesh.hasVertexAlpha = true;
  82859. this._loadTransform(node);
  82860. if (node.mesh != null) {
  82861. var mesh = GLTFLoader._GetProperty(this._gltf.meshes, node.mesh);
  82862. if (!mesh) {
  82863. throw new Error(context + ": Failed to find mesh " + node.mesh);
  82864. }
  82865. this._loadMesh("#/meshes/" + node.mesh, node, mesh);
  82866. }
  82867. node.babylonMesh.parent = node.parent.babylonMesh;
  82868. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  82869. node.babylonAnimationTargets.push(node.babylonMesh);
  82870. if (node.skin != null) {
  82871. var skin_1 = GLTFLoader._GetProperty(this._gltf.skins, node.skin);
  82872. if (!skin_1) {
  82873. throw new Error(context + ": Failed to find skin " + node.skin);
  82874. }
  82875. this._loadSkinAsync("#/skins/" + node.skin, skin_1, function () {
  82876. node.babylonMesh.skeleton = skin_1.babylonSkeleton;
  82877. node.babylonMesh._refreshBoundingInfo(true);
  82878. });
  82879. node.babylonMesh.parent = this._rootNode.babylonMesh;
  82880. node.babylonMesh.position = BABYLON.Vector3.Zero();
  82881. node.babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  82882. node.babylonMesh.scaling = BABYLON.Vector3.One();
  82883. }
  82884. if (node.camera != null) {
  82885. // TODO: handle cameras
  82886. }
  82887. if (node.children) {
  82888. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  82889. var index = _a[_i];
  82890. var childNode = GLTFLoader._GetProperty(this._gltf.nodes, index);
  82891. if (!childNode) {
  82892. throw new Error(context + ": Failed to find child node " + index);
  82893. }
  82894. this._loadNode("#/nodes/" + index, childNode);
  82895. }
  82896. }
  82897. if (this._parent.onMeshLoaded) {
  82898. this._parent.onMeshLoaded(node.babylonMesh);
  82899. }
  82900. };
  82901. GLTFLoader.prototype._loadMesh = function (context, node, mesh) {
  82902. var _this = this;
  82903. var primitives = mesh.primitives;
  82904. if (!primitives || primitives.length === 0) {
  82905. throw new Error(context + ": Primitives are missing");
  82906. }
  82907. this._createMorphTargets(context, node, mesh);
  82908. this._loadAllVertexDataAsync(context, mesh, function () {
  82909. _this._loadMorphTargets(context, node, mesh);
  82910. var vertexData = new BABYLON.VertexData();
  82911. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  82912. var primitive = primitives_1[_i];
  82913. vertexData.merge(primitive.vertexData);
  82914. }
  82915. new BABYLON.Geometry(node.babylonMesh.name, _this._babylonScene, vertexData, false, node.babylonMesh);
  82916. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  82917. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  82918. node.babylonMesh.subMeshes = [];
  82919. var verticesStart = 0;
  82920. var indicesStart = 0;
  82921. for (var index = 0; index < primitives.length; index++) {
  82922. var vertexData_1 = primitives[index].vertexData;
  82923. var verticesCount = vertexData_1.positions.length;
  82924. var indicesCount = vertexData_1.indices.length;
  82925. BABYLON.SubMesh.AddToMesh(index, verticesStart, verticesCount, indicesStart, indicesCount, node.babylonMesh);
  82926. verticesStart += verticesCount;
  82927. indicesStart += indicesCount;
  82928. }
  82929. ;
  82930. });
  82931. if (primitives.length === 1) {
  82932. var primitive = primitives[0];
  82933. if (primitive.material == null) {
  82934. node.babylonMesh.material = this._getDefaultMaterial();
  82935. }
  82936. else {
  82937. var material = GLTFLoader._GetProperty(this._gltf.materials, primitive.material);
  82938. if (!material) {
  82939. throw new Error(context + ": Failed to find material " + primitive.material);
  82940. }
  82941. this._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  82942. if (isNew && _this._parent.onMaterialLoaded) {
  82943. _this._parent.onMaterialLoaded(babylonMaterial);
  82944. }
  82945. node.babylonMesh.material = babylonMaterial;
  82946. });
  82947. }
  82948. }
  82949. else {
  82950. var multiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  82951. node.babylonMesh.material = multiMaterial;
  82952. var subMaterials_1 = multiMaterial.subMaterials;
  82953. var _loop_1 = function (index) {
  82954. var primitive = primitives[index];
  82955. if (primitive.material == null) {
  82956. subMaterials_1[index] = this_1._getDefaultMaterial();
  82957. }
  82958. else {
  82959. var material = GLTFLoader._GetProperty(this_1._gltf.materials, primitive.material);
  82960. if (!material) {
  82961. throw new Error(context + ": Failed to find material " + primitive.material);
  82962. }
  82963. this_1._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  82964. if (isNew && _this._parent.onMaterialLoaded) {
  82965. _this._parent.onMaterialLoaded(babylonMaterial);
  82966. }
  82967. subMaterials_1[index] = babylonMaterial;
  82968. });
  82969. }
  82970. };
  82971. var this_1 = this;
  82972. for (var index = 0; index < primitives.length; index++) {
  82973. _loop_1(index);
  82974. }
  82975. ;
  82976. }
  82977. };
  82978. GLTFLoader.prototype._loadAllVertexDataAsync = function (context, mesh, onSuccess) {
  82979. var primitives = mesh.primitives;
  82980. var numRemainingPrimitives = primitives.length;
  82981. var _loop_2 = function (index) {
  82982. var primitive = primitives[index];
  82983. this_2._loadVertexDataAsync(context + "/primitive/" + index, mesh, primitive, function (vertexData) {
  82984. primitive.vertexData = vertexData;
  82985. if (--numRemainingPrimitives === 0) {
  82986. onSuccess();
  82987. }
  82988. });
  82989. };
  82990. var this_2 = this;
  82991. for (var index = 0; index < primitives.length; index++) {
  82992. _loop_2(index);
  82993. }
  82994. };
  82995. /**
  82996. * Converts a data bufferview into a Float4 Texture Coordinate Array, based on the accessor component type
  82997. * @param {ArrayBufferView} data
  82998. * @param {IGLTFAccessor} accessor
  82999. */
  83000. GLTFLoader.prototype._convertToFloat4TextureCoordArray = function (context, data, accessor) {
  83001. if (accessor.componentType == GLTF2.EComponentType.FLOAT) {
  83002. return data;
  83003. }
  83004. var buffer = data;
  83005. var factor = 1;
  83006. switch (accessor.componentType) {
  83007. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  83008. factor = 1 / 255;
  83009. break;
  83010. }
  83011. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  83012. factor = 1 / 65535;
  83013. break;
  83014. }
  83015. default: {
  83016. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  83017. }
  83018. }
  83019. var result = new Float32Array(accessor.count * 2);
  83020. for (var i = 0; i < result.length; ++i) {
  83021. result[i] = buffer[i] * factor;
  83022. }
  83023. return result;
  83024. };
  83025. /**
  83026. * Converts a data bufferview into a Float4 Color Array, based on the accessor component type
  83027. * @param {ArrayBufferView} data
  83028. * @param {IGLTFAccessor} accessor
  83029. */
  83030. GLTFLoader.prototype._convertToFloat4ColorArray = function (context, data, accessor) {
  83031. var colorComponentCount = GLTFLoader._GetNumComponents(context, accessor.type);
  83032. if (colorComponentCount === 4 && accessor.componentType === GLTF2.EComponentType.FLOAT) {
  83033. return data;
  83034. }
  83035. var buffer = data;
  83036. var factor = 1;
  83037. switch (accessor.componentType) {
  83038. case GLTF2.EComponentType.FLOAT: {
  83039. factor = 1;
  83040. break;
  83041. }
  83042. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  83043. factor = 1 / 255;
  83044. break;
  83045. }
  83046. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  83047. factor = 1 / 65535;
  83048. break;
  83049. }
  83050. default: {
  83051. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  83052. }
  83053. }
  83054. var result = new Float32Array(accessor.count * 4);
  83055. if (colorComponentCount === 4) {
  83056. for (var i = 0; i < result.length; ++i) {
  83057. result[i] = buffer[i] * factor;
  83058. }
  83059. }
  83060. else {
  83061. var offset = 0;
  83062. for (var i = 0; i < result.length; ++i) {
  83063. if ((i + 1) % 4 === 0) {
  83064. result[i] = 1;
  83065. }
  83066. else {
  83067. result[i] = buffer[offset++] * factor;
  83068. }
  83069. }
  83070. }
  83071. return result;
  83072. };
  83073. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  83074. var _this = this;
  83075. var attributes = primitive.attributes;
  83076. if (!attributes) {
  83077. throw new Error(context + ": Attributes are missing");
  83078. }
  83079. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  83080. // TODO: handle other primitive modes
  83081. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  83082. }
  83083. var vertexData = new BABYLON.VertexData();
  83084. var numRemainingAttributes = Object.keys(attributes).length;
  83085. var _loop_3 = function (attribute) {
  83086. var accessor = GLTFLoader._GetProperty(this_3._gltf.accessors, attributes[attribute]);
  83087. if (!accessor) {
  83088. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  83089. }
  83090. this_3._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  83091. switch (attribute) {
  83092. case "POSITION": {
  83093. vertexData.positions = data;
  83094. break;
  83095. }
  83096. case "NORMAL": {
  83097. vertexData.normals = data;
  83098. break;
  83099. }
  83100. case "TANGENT": {
  83101. vertexData.tangents = data;
  83102. break;
  83103. }
  83104. case "TEXCOORD_0": {
  83105. vertexData.uvs = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  83106. break;
  83107. }
  83108. case "TEXCOORD_1": {
  83109. vertexData.uvs2 = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  83110. break;
  83111. }
  83112. case "JOINTS_0": {
  83113. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  83114. break;
  83115. }
  83116. case "WEIGHTS_0": {
  83117. //TODO: need to add support for normalized weights.
  83118. vertexData.matricesWeights = data;
  83119. break;
  83120. }
  83121. case "COLOR_0": {
  83122. vertexData.colors = _this._convertToFloat4ColorArray(context, data, accessor);
  83123. break;
  83124. }
  83125. default: {
  83126. BABYLON.Tools.Warn(context + ": Ignoring unrecognized attribute '" + attribute + "'");
  83127. break;
  83128. }
  83129. }
  83130. if (--numRemainingAttributes === 0) {
  83131. if (primitive.indices == null) {
  83132. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  83133. for (var i = 0; i < vertexData.indices.length; i++) {
  83134. vertexData.indices[i] = i;
  83135. }
  83136. onSuccess(vertexData);
  83137. }
  83138. else {
  83139. var indicesAccessor = GLTFLoader._GetProperty(_this._gltf.accessors, primitive.indices);
  83140. if (!indicesAccessor) {
  83141. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  83142. }
  83143. _this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, function (data) {
  83144. vertexData.indices = data;
  83145. onSuccess(vertexData);
  83146. });
  83147. }
  83148. }
  83149. });
  83150. };
  83151. var this_3 = this;
  83152. for (var attribute in attributes) {
  83153. _loop_3(attribute);
  83154. }
  83155. };
  83156. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh) {
  83157. var primitives = mesh.primitives;
  83158. var targets = primitives[0].targets;
  83159. if (!targets) {
  83160. return;
  83161. }
  83162. for (var _i = 0, primitives_2 = primitives; _i < primitives_2.length; _i++) {
  83163. var primitive = primitives_2[_i];
  83164. if (!primitive.targets || primitive.targets.length != targets.length) {
  83165. throw new Error(context + ": All primitives are required to list the same number of targets");
  83166. }
  83167. }
  83168. var morphTargetManager = new BABYLON.MorphTargetManager();
  83169. node.babylonMesh.morphTargetManager = morphTargetManager;
  83170. for (var index = 0; index < targets.length; index++) {
  83171. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  83172. morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  83173. }
  83174. };
  83175. GLTFLoader.prototype._loadMorphTargets = function (context, node, mesh) {
  83176. var morphTargetManager = node.babylonMesh.morphTargetManager;
  83177. if (!morphTargetManager) {
  83178. return;
  83179. }
  83180. this._loadAllMorphTargetVertexDataAsync(context, node, mesh, function () {
  83181. var numTargets = morphTargetManager.numTargets;
  83182. for (var index = 0; index < numTargets; index++) {
  83183. var vertexData = new BABYLON.VertexData();
  83184. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  83185. var primitive = _a[_i];
  83186. vertexData.merge(primitive.targetsVertexData[index], { tangentLength: 3 });
  83187. }
  83188. if (!vertexData.positions) {
  83189. throw new Error(context + ": Positions are missing");
  83190. }
  83191. var target = morphTargetManager.getTarget(index);
  83192. target.setPositions(vertexData.positions);
  83193. target.setNormals(vertexData.normals);
  83194. target.setTangents(vertexData.tangents);
  83195. }
  83196. });
  83197. };
  83198. GLTFLoader.prototype._loadAllMorphTargetVertexDataAsync = function (context, node, mesh, onSuccess) {
  83199. var numRemainingTargets = mesh.primitives.length * node.babylonMesh.morphTargetManager.numTargets;
  83200. var _loop_4 = function (primitive) {
  83201. var targets = primitive.targets;
  83202. primitive.targetsVertexData = new Array(targets.length);
  83203. var _loop_5 = function (index) {
  83204. this_4._loadMorphTargetVertexDataAsync(context + "/targets/" + index, primitive.vertexData, targets[index], function (vertexData) {
  83205. primitive.targetsVertexData[index] = vertexData;
  83206. if (--numRemainingTargets === 0) {
  83207. onSuccess();
  83208. }
  83209. });
  83210. };
  83211. for (var index = 0; index < targets.length; index++) {
  83212. _loop_5(index);
  83213. }
  83214. };
  83215. var this_4 = this;
  83216. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  83217. var primitive = _a[_i];
  83218. _loop_4(primitive);
  83219. }
  83220. };
  83221. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, vertexData, attributes, onSuccess) {
  83222. var targetVertexData = new BABYLON.VertexData();
  83223. var numRemainingAttributes = Object.keys(attributes).length;
  83224. var _loop_6 = function (attribute) {
  83225. var accessor = GLTFLoader._GetProperty(this_5._gltf.accessors, attributes[attribute]);
  83226. if (!accessor) {
  83227. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  83228. }
  83229. this_5._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  83230. // glTF stores morph target information as deltas while babylon.js expects the final data.
  83231. // As a result we have to add the original data to the delta to calculate the final data.
  83232. var values = data;
  83233. switch (attribute) {
  83234. case "POSITION": {
  83235. for (var i = 0; i < values.length; i++) {
  83236. values[i] += vertexData.positions[i];
  83237. }
  83238. targetVertexData.positions = values;
  83239. break;
  83240. }
  83241. case "NORMAL": {
  83242. for (var i = 0; i < values.length; i++) {
  83243. values[i] += vertexData.normals[i];
  83244. }
  83245. targetVertexData.normals = values;
  83246. break;
  83247. }
  83248. case "TANGENT": {
  83249. // Tangent data for morph targets is stored as xyz delta.
  83250. // The vertexData.tangent is stored as xyzw.
  83251. // So we need to skip every fourth vertexData.tangent.
  83252. for (var i = 0, j = 0; i < values.length; i++, j++) {
  83253. values[i] += vertexData.tangents[j];
  83254. if ((i + 1) % 3 == 0) {
  83255. j++;
  83256. }
  83257. }
  83258. targetVertexData.tangents = values;
  83259. break;
  83260. }
  83261. default: {
  83262. BABYLON.Tools.Warn(context + ": Ignoring unrecognized attribute '" + attribute + "'");
  83263. break;
  83264. }
  83265. }
  83266. if (--numRemainingAttributes === 0) {
  83267. onSuccess(targetVertexData);
  83268. }
  83269. });
  83270. };
  83271. var this_5 = this;
  83272. for (var attribute in attributes) {
  83273. _loop_6(attribute);
  83274. }
  83275. };
  83276. GLTFLoader.prototype._loadTransform = function (node) {
  83277. var position = BABYLON.Vector3.Zero();
  83278. var rotation = BABYLON.Quaternion.Identity();
  83279. var scaling = BABYLON.Vector3.One();
  83280. if (node.matrix) {
  83281. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  83282. matrix.decompose(scaling, rotation, position);
  83283. }
  83284. else {
  83285. if (node.translation)
  83286. position = BABYLON.Vector3.FromArray(node.translation);
  83287. if (node.rotation)
  83288. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  83289. if (node.scale)
  83290. scaling = BABYLON.Vector3.FromArray(node.scale);
  83291. }
  83292. node.babylonMesh.position = position;
  83293. node.babylonMesh.rotationQuaternion = rotation;
  83294. node.babylonMesh.scaling = scaling;
  83295. };
  83296. GLTFLoader.prototype._loadSkinAsync = function (context, skin, onSuccess) {
  83297. var _this = this;
  83298. if (skin.babylonSkeleton) {
  83299. onSuccess();
  83300. return;
  83301. }
  83302. var skeletonId = "skeleton" + skin.index;
  83303. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  83304. if (skin.inverseBindMatrices == null) {
  83305. this._loadBones(context, skin, null);
  83306. onSuccess();
  83307. }
  83308. else {
  83309. var accessor = GLTFLoader._GetProperty(this._gltf.accessors, skin.inverseBindMatrices);
  83310. if (!accessor) {
  83311. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  83312. }
  83313. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  83314. _this._loadBones(context, skin, data);
  83315. onSuccess();
  83316. });
  83317. }
  83318. };
  83319. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  83320. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  83321. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  83322. node.babylonAnimationTargets.push(babylonBone);
  83323. return babylonBone;
  83324. };
  83325. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  83326. var babylonBones = {};
  83327. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  83328. var index = _a[_i];
  83329. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  83330. if (!node) {
  83331. throw new Error(context + ": Failed to find joint " + index);
  83332. }
  83333. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  83334. }
  83335. };
  83336. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  83337. var babylonBone = babylonBones[node.index];
  83338. if (babylonBone) {
  83339. return babylonBone;
  83340. }
  83341. var boneIndex = skin.joints.indexOf(node.index);
  83342. var baseMatrix = BABYLON.Matrix.Identity();
  83343. if (inverseBindMatrixData && boneIndex !== -1) {
  83344. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  83345. baseMatrix.invertToRef(baseMatrix);
  83346. }
  83347. var babylonParentBone = null;
  83348. if (node.parent !== this._rootNode) {
  83349. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  83350. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  83351. }
  83352. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  83353. babylonBones[node.index] = babylonBone;
  83354. return babylonBone;
  83355. };
  83356. GLTFLoader.prototype._getNodeMatrix = function (node) {
  83357. return node.matrix ?
  83358. BABYLON.Matrix.FromArray(node.matrix) :
  83359. BABYLON.Matrix.Compose(node.scale ? BABYLON.Vector3.FromArray(node.scale) : BABYLON.Vector3.One(), node.rotation ? BABYLON.Quaternion.FromArray(node.rotation) : BABYLON.Quaternion.Identity(), node.translation ? BABYLON.Vector3.FromArray(node.translation) : BABYLON.Vector3.Zero());
  83360. };
  83361. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  83362. for (var _i = 0, indices_1 = indices; _i < indices_1.length; _i++) {
  83363. var index = indices_1[_i];
  83364. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  83365. if (!node) {
  83366. throw new Error(context + ": Failed to find node " + index);
  83367. }
  83368. this._traverseNode(context, node, action, parentNode);
  83369. }
  83370. };
  83371. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  83372. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  83373. return;
  83374. }
  83375. if (!action(node, parentNode)) {
  83376. return;
  83377. }
  83378. if (node.children) {
  83379. this._traverseNodes(context, node.children, action, node);
  83380. }
  83381. };
  83382. GLTFLoader.prototype._loadAnimations = function () {
  83383. var animations = this._gltf.animations;
  83384. if (!animations) {
  83385. return;
  83386. }
  83387. for (var index = 0; index < animations.length; index++) {
  83388. var animation = animations[index];
  83389. this._loadAnimation("#/animations/" + index, animation);
  83390. }
  83391. };
  83392. GLTFLoader.prototype._loadAnimation = function (context, animation) {
  83393. animation.targets = [];
  83394. for (var index = 0; index < animation.channels.length; index++) {
  83395. var channel = GLTFLoader._GetProperty(animation.channels, index);
  83396. if (!channel) {
  83397. throw new Error(context + ": Failed to find channel " + index);
  83398. }
  83399. var sampler = GLTFLoader._GetProperty(animation.samplers, channel.sampler);
  83400. if (!sampler) {
  83401. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  83402. }
  83403. this._loadAnimationChannel(animation, context + "/channels/" + index, channel, context + "/samplers/" + channel.sampler, sampler);
  83404. }
  83405. };
  83406. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  83407. var targetNode = GLTFLoader._GetProperty(this._gltf.nodes, channel.target.node);
  83408. if (!targetNode) {
  83409. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  83410. }
  83411. var targetPath;
  83412. var animationType;
  83413. switch (channel.target.path) {
  83414. case "translation": {
  83415. targetPath = "position";
  83416. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  83417. break;
  83418. }
  83419. case "rotation": {
  83420. targetPath = "rotationQuaternion";
  83421. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  83422. break;
  83423. }
  83424. case "scale": {
  83425. targetPath = "scaling";
  83426. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  83427. break;
  83428. }
  83429. case "weights": {
  83430. targetPath = "influence";
  83431. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  83432. break;
  83433. }
  83434. default: {
  83435. throw new Error(channelContext + ": Invalid target path " + channel.target.path);
  83436. }
  83437. }
  83438. var inputData;
  83439. var outputData;
  83440. var checkSuccess = function () {
  83441. if (!inputData || !outputData) {
  83442. return;
  83443. }
  83444. var outputBufferOffset = 0;
  83445. var getNextOutputValue;
  83446. switch (targetPath) {
  83447. case "position": {
  83448. getNextOutputValue = function () {
  83449. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  83450. outputBufferOffset += 3;
  83451. return value;
  83452. };
  83453. break;
  83454. }
  83455. case "rotationQuaternion": {
  83456. getNextOutputValue = function () {
  83457. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  83458. outputBufferOffset += 4;
  83459. return value;
  83460. };
  83461. break;
  83462. }
  83463. case "scaling": {
  83464. getNextOutputValue = function () {
  83465. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  83466. outputBufferOffset += 3;
  83467. return value;
  83468. };
  83469. break;
  83470. }
  83471. case "influence": {
  83472. getNextOutputValue = function () {
  83473. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  83474. var value = new Array(numTargets);
  83475. for (var i = 0; i < numTargets; i++) {
  83476. value[i] = outputData[outputBufferOffset++];
  83477. }
  83478. return value;
  83479. };
  83480. break;
  83481. }
  83482. }
  83483. var getNextKey;
  83484. switch (sampler.interpolation) {
  83485. case "LINEAR": {
  83486. getNextKey = function (frameIndex) { return ({
  83487. frame: inputData[frameIndex],
  83488. value: getNextOutputValue()
  83489. }); };
  83490. break;
  83491. }
  83492. case "CUBICSPLINE": {
  83493. getNextKey = function (frameIndex) { return ({
  83494. frame: inputData[frameIndex],
  83495. inTangent: getNextOutputValue(),
  83496. value: getNextOutputValue(),
  83497. outTangent: getNextOutputValue()
  83498. }); };
  83499. break;
  83500. }
  83501. default: {
  83502. throw new Error(samplerContext + ": Invalid interpolation " + sampler.interpolation);
  83503. }
  83504. }
  83505. ;
  83506. var keys;
  83507. if (inputData.length === 1) {
  83508. var key = getNextKey(0);
  83509. keys = [
  83510. { frame: key.frame, value: key.value },
  83511. { frame: key.frame + 1, value: key.value }
  83512. ];
  83513. }
  83514. else {
  83515. keys = new Array(inputData.length);
  83516. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  83517. keys[frameIndex] = getNextKey(frameIndex);
  83518. }
  83519. }
  83520. if (targetPath === "influence") {
  83521. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  83522. var _loop_7 = function (targetIndex) {
  83523. var morphTarget = morphTargetManager.getTarget(targetIndex);
  83524. var animationName = (animation.name || "anim" + animation.index) + "_" + targetIndex;
  83525. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  83526. babylonAnimation.setKeys(keys.map(function (key) { return ({
  83527. frame: key.frame,
  83528. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  83529. value: key.value[targetIndex],
  83530. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  83531. }); }));
  83532. morphTarget.animations.push(babylonAnimation);
  83533. animation.targets.push(morphTarget);
  83534. };
  83535. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  83536. _loop_7(targetIndex);
  83537. }
  83538. }
  83539. else {
  83540. var animationName = animation.name || "anim" + animation.index;
  83541. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  83542. babylonAnimation.setKeys(keys);
  83543. if (targetNode.babylonAnimationTargets) {
  83544. for (var _i = 0, _a = targetNode.babylonAnimationTargets; _i < _a.length; _i++) {
  83545. var target = _a[_i];
  83546. target.animations.push(babylonAnimation.clone());
  83547. animation.targets.push(target);
  83548. }
  83549. }
  83550. }
  83551. };
  83552. var inputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.input);
  83553. if (!inputAccessor) {
  83554. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  83555. }
  83556. this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, function (data) {
  83557. inputData = data;
  83558. checkSuccess();
  83559. });
  83560. var outputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.output);
  83561. if (!outputAccessor) {
  83562. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  83563. }
  83564. this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, function (data) {
  83565. outputData = data;
  83566. checkSuccess();
  83567. });
  83568. };
  83569. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  83570. var _this = this;
  83571. this._addPendingData(buffer);
  83572. if (buffer.loadedData) {
  83573. onSuccess(buffer.loadedData);
  83574. this._removePendingData(buffer);
  83575. }
  83576. else if (buffer.loadedObservable) {
  83577. buffer.loadedObservable.add(function (buffer) {
  83578. onSuccess(buffer.loadedData);
  83579. _this._removePendingData(buffer);
  83580. });
  83581. }
  83582. else {
  83583. if (!buffer.uri) {
  83584. throw new Error(context + ": Uri is missing");
  83585. }
  83586. buffer.loadedObservable = new BABYLON.Observable();
  83587. buffer.loadedObservable.add(function (buffer) {
  83588. onSuccess(buffer.loadedData);
  83589. _this._removePendingData(buffer);
  83590. });
  83591. this._loadUriAsync(context, buffer.uri, function (data) {
  83592. buffer.loadedData = data;
  83593. buffer.loadedObservable.notifyObservers(buffer);
  83594. buffer.loadedObservable = undefined;
  83595. });
  83596. }
  83597. };
  83598. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  83599. var buffer = GLTFLoader._GetProperty(this._gltf.buffers, bufferView.buffer);
  83600. if (!buffer) {
  83601. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  83602. }
  83603. this._loadBufferAsync("#/buffers/" + buffer.index, buffer, function (bufferData) {
  83604. var data;
  83605. try {
  83606. data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  83607. }
  83608. catch (e) {
  83609. throw new Error(context + ": " + e.message);
  83610. }
  83611. onSuccess(data);
  83612. });
  83613. };
  83614. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  83615. var _this = this;
  83616. if (accessor.sparse) {
  83617. throw new Error(context + ": Sparse accessors are not currently supported");
  83618. }
  83619. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, accessor.bufferView);
  83620. if (!bufferView) {
  83621. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  83622. }
  83623. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, function (bufferViewData) {
  83624. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  83625. var data;
  83626. var byteOffset = accessor.byteOffset || 0;
  83627. var byteStride = bufferView.byteStride;
  83628. if (byteStride === 0) {
  83629. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  83630. }
  83631. try {
  83632. switch (accessor.componentType) {
  83633. case GLTF2.EComponentType.BYTE: {
  83634. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  83635. break;
  83636. }
  83637. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  83638. data = _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  83639. break;
  83640. }
  83641. case GLTF2.EComponentType.SHORT: {
  83642. data = _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  83643. break;
  83644. }
  83645. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  83646. data = _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  83647. break;
  83648. }
  83649. case GLTF2.EComponentType.UNSIGNED_INT: {
  83650. data = _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  83651. break;
  83652. }
  83653. case GLTF2.EComponentType.FLOAT: {
  83654. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  83655. break;
  83656. }
  83657. default: {
  83658. throw new Error(context + ": Invalid component type " + accessor.componentType);
  83659. }
  83660. }
  83661. }
  83662. catch (e) {
  83663. throw new Error(context + ": " + e);
  83664. }
  83665. onSuccess(data);
  83666. });
  83667. };
  83668. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  83669. byteOffset += data.byteOffset;
  83670. var targetLength = count * numComponents;
  83671. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  83672. return new typedArray(data.buffer, byteOffset, targetLength);
  83673. }
  83674. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  83675. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  83676. var targetBuffer = new typedArray(targetLength);
  83677. var sourceIndex = 0;
  83678. var targetIndex = 0;
  83679. while (targetIndex < targetLength) {
  83680. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  83681. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  83682. targetIndex++;
  83683. }
  83684. sourceIndex += elementStride;
  83685. }
  83686. return targetBuffer;
  83687. };
  83688. GLTFLoader.prototype._addPendingData = function (data) {
  83689. if (!this._renderReady) {
  83690. this._renderPendingCount++;
  83691. }
  83692. this._addLoaderPendingData(data);
  83693. };
  83694. GLTFLoader.prototype._removePendingData = function (data) {
  83695. var _this = this;
  83696. if (!this._renderReady) {
  83697. if (--this._renderPendingCount === 0) {
  83698. this._addLoaderPendingData(this);
  83699. this._compileMaterialsAsync(function () {
  83700. _this._compileShadowGeneratorsAsync(function () {
  83701. _this._removeLoaderPendingData(_this);
  83702. _this._renderReady = true;
  83703. _this._onRenderReady();
  83704. });
  83705. });
  83706. }
  83707. }
  83708. this._removeLoaderPendingData(data);
  83709. };
  83710. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  83711. this._loaderPendingCount++;
  83712. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  83713. var tracker = _a[_i];
  83714. tracker._addPendingData(data);
  83715. }
  83716. };
  83717. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  83718. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  83719. var tracker = _a[_i];
  83720. tracker._removePendingData(data);
  83721. }
  83722. if (--this._loaderPendingCount === 0) {
  83723. this._onComplete();
  83724. }
  83725. };
  83726. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  83727. var _this = this;
  83728. var tracker = new GLTFLoaderTracker(function () {
  83729. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker), 1);
  83730. onComplete();
  83731. });
  83732. this._loaderTrackers.push(tracker);
  83733. this._addLoaderPendingData(tracker);
  83734. action();
  83735. this._removeLoaderPendingData(tracker);
  83736. };
  83737. GLTFLoader.prototype._getDefaultMaterial = function () {
  83738. if (!this._defaultMaterial) {
  83739. var id = "__gltf_default";
  83740. var material = this._babylonScene.getMaterialByName(id);
  83741. if (!material) {
  83742. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  83743. material.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  83744. material.sideOrientation = BABYLON.Material.ClockWiseSideOrientation;
  83745. material.metallic = 1;
  83746. material.roughness = 1;
  83747. }
  83748. this._defaultMaterial = material;
  83749. }
  83750. return this._defaultMaterial;
  83751. };
  83752. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  83753. var babylonMaterial = material.babylonMaterial;
  83754. // Ensure metallic workflow
  83755. babylonMaterial.metallic = 1;
  83756. babylonMaterial.roughness = 1;
  83757. var properties = material.pbrMetallicRoughness;
  83758. if (!properties) {
  83759. return;
  83760. }
  83761. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  83762. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  83763. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  83764. if (properties.baseColorTexture) {
  83765. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.baseColorTexture.index);
  83766. if (!texture) {
  83767. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  83768. }
  83769. babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord);
  83770. }
  83771. if (properties.metallicRoughnessTexture) {
  83772. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.metallicRoughnessTexture.index);
  83773. if (!texture) {
  83774. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  83775. }
  83776. babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord);
  83777. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  83778. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  83779. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  83780. }
  83781. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  83782. };
  83783. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  83784. if (material.babylonMaterial) {
  83785. assign(material.babylonMaterial, false);
  83786. return;
  83787. }
  83788. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  83789. return;
  83790. }
  83791. this._createPbrMaterial(material);
  83792. this._loadMaterialBaseProperties(context, material);
  83793. this._loadMaterialMetallicRoughnessProperties(context, material);
  83794. assign(material.babylonMaterial, true);
  83795. };
  83796. GLTFLoader.prototype._createPbrMaterial = function (material) {
  83797. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  83798. babylonMaterial.sideOrientation = BABYLON.Material.ClockWiseSideOrientation;
  83799. material.babylonMaterial = babylonMaterial;
  83800. };
  83801. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  83802. var babylonMaterial = material.babylonMaterial;
  83803. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  83804. if (material.doubleSided) {
  83805. babylonMaterial.backFaceCulling = false;
  83806. babylonMaterial.twoSidedLighting = true;
  83807. }
  83808. if (material.normalTexture) {
  83809. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.normalTexture.index);
  83810. if (!texture) {
  83811. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  83812. }
  83813. babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord);
  83814. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  83815. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  83816. if (material.normalTexture.scale != null) {
  83817. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  83818. }
  83819. }
  83820. if (material.occlusionTexture) {
  83821. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.occlusionTexture.index);
  83822. if (!texture) {
  83823. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  83824. }
  83825. babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord);
  83826. babylonMaterial.useAmbientInGrayScale = true;
  83827. if (material.occlusionTexture.strength != null) {
  83828. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  83829. }
  83830. }
  83831. if (material.emissiveTexture) {
  83832. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.emissiveTexture.index);
  83833. if (!texture) {
  83834. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  83835. }
  83836. babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord);
  83837. }
  83838. };
  83839. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  83840. var babylonMaterial = material.babylonMaterial;
  83841. var alphaMode = material.alphaMode || "OPAQUE";
  83842. switch (alphaMode) {
  83843. case "OPAQUE": {
  83844. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  83845. break;
  83846. }
  83847. case "MASK": {
  83848. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  83849. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  83850. if (colorFactor) {
  83851. if (colorFactor[3] == 0) {
  83852. babylonMaterial.alphaCutOff = 1;
  83853. }
  83854. else {
  83855. babylonMaterial.alphaCutOff /= colorFactor[3];
  83856. }
  83857. }
  83858. if (babylonMaterial.albedoTexture) {
  83859. babylonMaterial.albedoTexture.hasAlpha = true;
  83860. }
  83861. break;
  83862. }
  83863. case "BLEND": {
  83864. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  83865. if (colorFactor) {
  83866. babylonMaterial.alpha = colorFactor[3];
  83867. }
  83868. if (babylonMaterial.albedoTexture) {
  83869. babylonMaterial.albedoTexture.hasAlpha = true;
  83870. babylonMaterial.useAlphaFromAlbedoTexture = true;
  83871. }
  83872. break;
  83873. }
  83874. default: {
  83875. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  83876. }
  83877. }
  83878. };
  83879. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  83880. var _this = this;
  83881. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(this._gltf.samplers, texture.sampler));
  83882. if (!sampler) {
  83883. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  83884. }
  83885. this._loadSampler("#/samplers/" + sampler.index, sampler);
  83886. this._addPendingData(texture);
  83887. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, sampler.noMipMaps, false, sampler.samplingMode, function () {
  83888. _this._tryCatchOnError(function () {
  83889. _this._removePendingData(texture);
  83890. });
  83891. }, function (message) {
  83892. _this._tryCatchOnError(function () {
  83893. throw new Error(context + ": " + message);
  83894. });
  83895. });
  83896. if (texture.url) {
  83897. babylonTexture.updateURL(texture.url);
  83898. }
  83899. else if (texture.dataReadyObservable) {
  83900. texture.dataReadyObservable.add(function (texture) {
  83901. babylonTexture.updateURL(texture.url);
  83902. });
  83903. }
  83904. else {
  83905. texture.dataReadyObservable = new BABYLON.Observable();
  83906. texture.dataReadyObservable.add(function (texture) {
  83907. babylonTexture.updateURL(texture.url);
  83908. });
  83909. var image_1 = GLTFLoader._GetProperty(this._gltf.images, texture.source);
  83910. if (!image_1) {
  83911. throw new Error(context + ": Failed to find source " + texture.source);
  83912. }
  83913. this._loadImageAsync("#/images/" + image_1.index, image_1, function (data) {
  83914. texture.url = URL.createObjectURL(new Blob([data], { type: image_1.mimeType }));
  83915. texture.dataReadyObservable.notifyObservers(texture);
  83916. texture.dataReadyObservable = undefined;
  83917. });
  83918. }
  83919. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  83920. babylonTexture.wrapU = sampler.wrapU;
  83921. babylonTexture.wrapV = sampler.wrapV;
  83922. babylonTexture.name = texture.name || "texture" + texture.index;
  83923. if (this._parent.onTextureLoaded) {
  83924. this._parent.onTextureLoaded(babylonTexture);
  83925. }
  83926. return babylonTexture;
  83927. };
  83928. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  83929. if (sampler.noMipMaps != undefined) {
  83930. return;
  83931. }
  83932. sampler.noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  83933. sampler.samplingMode = GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter);
  83934. sampler.wrapU = GLTFLoader._GetTextureWrapMode(context, sampler.wrapS);
  83935. sampler.wrapV = GLTFLoader._GetTextureWrapMode(context, sampler.wrapT);
  83936. };
  83937. GLTFLoader.prototype._loadImageAsync = function (context, image, onSuccess) {
  83938. if (image.uri) {
  83939. this._loadUriAsync(context, image.uri, onSuccess);
  83940. }
  83941. else {
  83942. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, image.bufferView);
  83943. if (!bufferView) {
  83944. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  83945. }
  83946. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess);
  83947. }
  83948. };
  83949. GLTFLoader.prototype._loadUriAsync = function (context, uri, onSuccess) {
  83950. var _this = this;
  83951. if (GLTF2.GLTFUtils.IsBase64(uri)) {
  83952. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(uri)));
  83953. return;
  83954. }
  83955. if (!GLTF2.GLTFUtils.ValidateUri(uri)) {
  83956. throw new Error(context + ": Uri '" + uri + "' is invalid");
  83957. }
  83958. var request = BABYLON.Tools.LoadFile(this._rootUrl + uri, function (data) {
  83959. _this._tryCatchOnError(function () {
  83960. onSuccess(new Uint8Array(data));
  83961. });
  83962. }, function (event) {
  83963. _this._tryCatchOnError(function () {
  83964. if (request && !_this._renderReady) {
  83965. request._lengthComputable = event.lengthComputable;
  83966. request._loaded = event.loaded;
  83967. request._total = event.total;
  83968. _this._onProgress();
  83969. }
  83970. });
  83971. }, this._babylonScene.database, true, function (request, exception) {
  83972. _this._tryCatchOnError(function () {
  83973. throw new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request);
  83974. });
  83975. }, function (oldRequest, newRequest) {
  83976. _this._requests.splice(_this._requests.indexOf(oldRequest), 1, newRequest);
  83977. });
  83978. if (request) {
  83979. this._requests.push(request);
  83980. }
  83981. };
  83982. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  83983. if (this._disposed) {
  83984. return;
  83985. }
  83986. try {
  83987. handler();
  83988. }
  83989. catch (e) {
  83990. BABYLON.Tools.Error("glTF Loader: " + e.message);
  83991. if (this._errorCallback) {
  83992. this._errorCallback(e.message, e);
  83993. }
  83994. this.dispose();
  83995. }
  83996. };
  83997. GLTFLoader._AssignIndices = function (array) {
  83998. if (array) {
  83999. for (var index = 0; index < array.length; index++) {
  84000. array[index].index = index;
  84001. }
  84002. }
  84003. };
  84004. GLTFLoader._GetProperty = function (array, index) {
  84005. if (!array || index == undefined || !array[index]) {
  84006. return null;
  84007. }
  84008. return array[index];
  84009. };
  84010. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  84011. // Set defaults if undefined
  84012. mode = mode == undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  84013. switch (mode) {
  84014. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  84015. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  84016. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  84017. default:
  84018. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  84019. return BABYLON.Texture.WRAP_ADDRESSMODE;
  84020. }
  84021. };
  84022. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  84023. // Set defaults if undefined
  84024. magFilter = magFilter == undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  84025. minFilter = minFilter == undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  84026. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  84027. switch (minFilter) {
  84028. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  84029. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  84030. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  84031. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  84032. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  84033. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  84034. default:
  84035. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  84036. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  84037. }
  84038. }
  84039. else {
  84040. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  84041. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  84042. }
  84043. switch (minFilter) {
  84044. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  84045. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  84046. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  84047. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  84048. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  84049. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  84050. default:
  84051. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  84052. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  84053. }
  84054. }
  84055. };
  84056. GLTFLoader._GetNumComponents = function (context, type) {
  84057. switch (type) {
  84058. case "SCALAR": return 1;
  84059. case "VEC2": return 2;
  84060. case "VEC3": return 3;
  84061. case "VEC4": return 4;
  84062. case "MAT2": return 4;
  84063. case "MAT3": return 9;
  84064. case "MAT4": return 16;
  84065. }
  84066. throw new Error(context + ": Invalid type " + type);
  84067. };
  84068. GLTFLoader.prototype._compileMaterialAsync = function (babylonMaterial, babylonMesh, onSuccess) {
  84069. var _this = this;
  84070. if (this._parent.useClipPlane) {
  84071. babylonMaterial.forceCompilation(babylonMesh, function () {
  84072. babylonMaterial.forceCompilation(babylonMesh, function () {
  84073. _this._tryCatchOnError(onSuccess);
  84074. }, { clipPlane: true });
  84075. });
  84076. }
  84077. else {
  84078. babylonMaterial.forceCompilation(babylonMesh, function () {
  84079. _this._tryCatchOnError(onSuccess);
  84080. });
  84081. }
  84082. };
  84083. GLTFLoader.prototype._compileMaterialsAsync = function (onSuccess) {
  84084. if (!this._parent.compileMaterials || !this._gltf.materials) {
  84085. onSuccess();
  84086. return;
  84087. }
  84088. var meshes = this._getMeshes();
  84089. var remaining = 0;
  84090. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  84091. var mesh = meshes_1[_i];
  84092. if (mesh.material instanceof BABYLON.MultiMaterial) {
  84093. for (var _a = 0, _b = mesh.material.subMaterials; _a < _b.length; _a++) {
  84094. var subMaterial = _b[_a];
  84095. if (subMaterial) {
  84096. remaining++;
  84097. }
  84098. }
  84099. }
  84100. else if (mesh.material) {
  84101. remaining++;
  84102. }
  84103. }
  84104. if (remaining === 0) {
  84105. onSuccess();
  84106. return;
  84107. }
  84108. for (var _c = 0, meshes_2 = meshes; _c < meshes_2.length; _c++) {
  84109. var mesh = meshes_2[_c];
  84110. if (mesh.material instanceof BABYLON.MultiMaterial) {
  84111. for (var _d = 0, _e = mesh.material.subMaterials; _d < _e.length; _d++) {
  84112. var subMaterial = _e[_d];
  84113. if (subMaterial) {
  84114. this._compileMaterialAsync(subMaterial, mesh, function () {
  84115. if (--remaining === 0) {
  84116. onSuccess();
  84117. }
  84118. });
  84119. }
  84120. }
  84121. }
  84122. else if (mesh.material) {
  84123. this._compileMaterialAsync(mesh.material, mesh, function () {
  84124. if (--remaining === 0) {
  84125. onSuccess();
  84126. }
  84127. });
  84128. }
  84129. }
  84130. };
  84131. GLTFLoader.prototype._compileShadowGeneratorsAsync = function (onSuccess) {
  84132. var _this = this;
  84133. if (!this._parent.compileShadowGenerators) {
  84134. onSuccess();
  84135. return;
  84136. }
  84137. var lights = this._babylonScene.lights;
  84138. var remaining = 0;
  84139. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  84140. var light = lights_1[_i];
  84141. var generator = light.getShadowGenerator();
  84142. if (generator) {
  84143. remaining++;
  84144. }
  84145. }
  84146. if (remaining === 0) {
  84147. onSuccess();
  84148. return;
  84149. }
  84150. for (var _a = 0, lights_2 = lights; _a < lights_2.length; _a++) {
  84151. var light = lights_2[_a];
  84152. var generator = light.getShadowGenerator();
  84153. if (generator) {
  84154. generator.forceCompilation(function () {
  84155. if (--remaining === 0) {
  84156. _this._tryCatchOnError(onSuccess);
  84157. }
  84158. });
  84159. }
  84160. }
  84161. };
  84162. GLTFLoader.Extensions = {};
  84163. return GLTFLoader;
  84164. }());
  84165. GLTF2.GLTFLoader = GLTFLoader;
  84166. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  84167. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  84168. })(BABYLON || (BABYLON = {}));
  84169. //# sourceMappingURL=babylon.glTFLoader.js.map
  84170. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  84171. var BABYLON;
  84172. (function (BABYLON) {
  84173. var GLTF2;
  84174. (function (GLTF2) {
  84175. /**
  84176. * Utils functions for GLTF
  84177. */
  84178. var GLTFUtils = /** @class */ (function () {
  84179. function GLTFUtils() {
  84180. }
  84181. /**
  84182. * If the uri is a base64 string
  84183. * @param uri: the uri to test
  84184. */
  84185. GLTFUtils.IsBase64 = function (uri) {
  84186. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  84187. };
  84188. /**
  84189. * Decode the base64 uri
  84190. * @param uri: the uri to decode
  84191. */
  84192. GLTFUtils.DecodeBase64 = function (uri) {
  84193. var decodedString = atob(uri.split(",")[1]);
  84194. var bufferLength = decodedString.length;
  84195. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  84196. for (var i = 0; i < bufferLength; i++) {
  84197. bufferView[i] = decodedString.charCodeAt(i);
  84198. }
  84199. return bufferView.buffer;
  84200. };
  84201. GLTFUtils.ValidateUri = function (uri) {
  84202. return (uri.indexOf("..") === -1);
  84203. };
  84204. return GLTFUtils;
  84205. }());
  84206. GLTF2.GLTFUtils = GLTFUtils;
  84207. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  84208. })(BABYLON || (BABYLON = {}));
  84209. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  84210. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  84211. var BABYLON;
  84212. (function (BABYLON) {
  84213. var GLTF2;
  84214. (function (GLTF2) {
  84215. var GLTFLoaderExtension = /** @class */ (function () {
  84216. function GLTFLoaderExtension() {
  84217. this.enabled = true;
  84218. }
  84219. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  84220. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  84221. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  84222. GLTFLoaderExtension.prototype._loadExtension = function (context, property, action) {
  84223. var _this = this;
  84224. if (!property.extensions) {
  84225. return false;
  84226. }
  84227. var extension = property.extensions[this.name];
  84228. if (!extension) {
  84229. return false;
  84230. }
  84231. // Clear out the extension before executing the action to avoid recursing into the same property.
  84232. property.extensions[this.name] = undefined;
  84233. action(context + "extensions/" + this.name, extension, function () {
  84234. // Restore the extension after completing the action.
  84235. property.extensions[_this.name] = extension;
  84236. });
  84237. return true;
  84238. };
  84239. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  84240. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  84241. };
  84242. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  84243. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  84244. };
  84245. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  84246. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  84247. };
  84248. GLTFLoaderExtension._ApplyExtensions = function (action) {
  84249. var extensions = GLTFLoaderExtension._Extensions;
  84250. if (!extensions) {
  84251. return false;
  84252. }
  84253. for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
  84254. var extension = extensions_1[_i];
  84255. if (extension.enabled && action(extension)) {
  84256. return true;
  84257. }
  84258. }
  84259. return false;
  84260. };
  84261. //
  84262. // Utilities
  84263. //
  84264. GLTFLoaderExtension._Extensions = [];
  84265. return GLTFLoaderExtension;
  84266. }());
  84267. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  84268. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  84269. })(BABYLON || (BABYLON = {}));
  84270. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  84271. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  84272. var BABYLON;
  84273. (function (BABYLON) {
  84274. var GLTF2;
  84275. (function (GLTF2) {
  84276. var Extensions;
  84277. (function (Extensions) {
  84278. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  84279. var MSFTLOD = /** @class */ (function (_super) {
  84280. __extends(MSFTLOD, _super);
  84281. function MSFTLOD() {
  84282. var _this = _super !== null && _super.apply(this, arguments) || this;
  84283. /**
  84284. * Specify the minimal delay between LODs in ms (default = 250)
  84285. */
  84286. _this.Delay = 250;
  84287. return _this;
  84288. }
  84289. Object.defineProperty(MSFTLOD.prototype, "name", {
  84290. get: function () {
  84291. return "MSFT_lod";
  84292. },
  84293. enumerable: true,
  84294. configurable: true
  84295. });
  84296. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  84297. return this._loadExtension(context, node, function (context, extension, onComplete) {
  84298. for (var i = extension.ids.length - 1; i >= 0; i--) {
  84299. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, extension.ids[i]);
  84300. if (!lodNode) {
  84301. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  84302. }
  84303. loader._traverseNode(context, lodNode, action, parentNode);
  84304. }
  84305. loader._traverseNode(context, node, action, parentNode);
  84306. onComplete();
  84307. });
  84308. };
  84309. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  84310. var _this = this;
  84311. return this._loadExtension(context, node, function (context, extension, onComplete) {
  84312. var nodes = [node];
  84313. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  84314. var index = _a[_i];
  84315. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, index);
  84316. if (!lodNode) {
  84317. throw new Error(context + ": Failed to find node " + index);
  84318. }
  84319. nodes.push(lodNode);
  84320. }
  84321. loader._addLoaderPendingData(node);
  84322. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  84323. loader._removeLoaderPendingData(node);
  84324. onComplete();
  84325. });
  84326. });
  84327. };
  84328. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  84329. var _this = this;
  84330. loader._whenAction(function () {
  84331. loader._loadNode(context, nodes[index]);
  84332. }, function () {
  84333. if (index !== nodes.length - 1) {
  84334. var previousNode = nodes[index + 1];
  84335. previousNode.babylonMesh.setEnabled(false);
  84336. }
  84337. if (index === 0) {
  84338. onComplete();
  84339. return;
  84340. }
  84341. setTimeout(function () {
  84342. loader._tryCatchOnError(function () {
  84343. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  84344. });
  84345. }, _this.Delay);
  84346. });
  84347. };
  84348. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  84349. var _this = this;
  84350. return this._loadExtension(context, material, function (context, extension, onComplete) {
  84351. var materials = [material];
  84352. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  84353. var index = _a[_i];
  84354. var lodMaterial = GLTF2.GLTFLoader._GetProperty(loader._gltf.materials, index);
  84355. if (!lodMaterial) {
  84356. throw new Error(context + ": Failed to find material " + index);
  84357. }
  84358. materials.push(lodMaterial);
  84359. }
  84360. loader._addLoaderPendingData(material);
  84361. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  84362. loader._removeLoaderPendingData(material);
  84363. onComplete();
  84364. });
  84365. });
  84366. };
  84367. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  84368. var _this = this;
  84369. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  84370. if (index === materials.length - 1) {
  84371. assign(babylonMaterial, isNew);
  84372. // Load the next LOD when the loader is ready to render.
  84373. loader._executeWhenRenderReady(function () {
  84374. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  84375. });
  84376. }
  84377. else {
  84378. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  84379. assign(babylonMaterial, isNew);
  84380. if (index === 0) {
  84381. onComplete();
  84382. }
  84383. else {
  84384. setTimeout(function () {
  84385. loader._tryCatchOnError(function () {
  84386. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  84387. });
  84388. }, _this.Delay);
  84389. }
  84390. });
  84391. }
  84392. });
  84393. };
  84394. return MSFTLOD;
  84395. }(GLTF2.GLTFLoaderExtension));
  84396. Extensions.MSFTLOD = MSFTLOD;
  84397. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  84398. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  84399. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  84400. })(BABYLON || (BABYLON = {}));
  84401. //# sourceMappingURL=MSFT_lod.js.map
  84402. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  84403. var BABYLON;
  84404. (function (BABYLON) {
  84405. var GLTF2;
  84406. (function (GLTF2) {
  84407. var Extensions;
  84408. (function (Extensions) {
  84409. var KHRMaterialsPbrSpecularGlossiness = /** @class */ (function (_super) {
  84410. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  84411. function KHRMaterialsPbrSpecularGlossiness() {
  84412. return _super !== null && _super.apply(this, arguments) || this;
  84413. }
  84414. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  84415. get: function () {
  84416. return "KHR_materials_pbrSpecularGlossiness";
  84417. },
  84418. enumerable: true,
  84419. configurable: true
  84420. });
  84421. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  84422. var _this = this;
  84423. return this._loadExtension(context, material, function (context, extension, onComplete) {
  84424. loader._createPbrMaterial(material);
  84425. loader._loadMaterialBaseProperties(context, material);
  84426. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  84427. assign(material.babylonMaterial, true);
  84428. onComplete();
  84429. });
  84430. };
  84431. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  84432. var babylonMaterial = material.babylonMaterial;
  84433. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  84434. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  84435. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  84436. if (properties.diffuseTexture) {
  84437. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.diffuseTexture.index);
  84438. if (!texture) {
  84439. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  84440. }
  84441. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  84442. }
  84443. if (properties.specularGlossinessTexture) {
  84444. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.specularGlossinessTexture.index);
  84445. if (!texture) {
  84446. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  84447. }
  84448. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  84449. babylonMaterial.reflectivityTexture.hasAlpha = true;
  84450. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  84451. }
  84452. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  84453. };
  84454. return KHRMaterialsPbrSpecularGlossiness;
  84455. }(GLTF2.GLTFLoaderExtension));
  84456. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  84457. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  84458. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  84459. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  84460. })(BABYLON || (BABYLON = {}));
  84461. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  84462. (function universalModuleDefinition(root, factory) {
  84463. var f = factory();
  84464. if (root && root["BABYLON"]) {
  84465. return;
  84466. }
  84467. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  84468. globalObject["BABYLON"] = f;
  84469. if(typeof exports === 'object' && typeof module === 'object')
  84470. module.exports = f;
  84471. else if(typeof define === 'function' && define.amd)
  84472. define(["BABYLON"], factory);
  84473. else if(typeof exports === 'object')
  84474. exports["BABYLON"] = f;
  84475. else {
  84476. root["BABYLON"] = f;
  84477. }
  84478. })(this, function() {
  84479. return BABYLON;
  84480. });