babylon.max.js 4.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997
  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. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2857. BABYLON.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. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  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. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  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. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  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. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  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. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  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. // Screenshots
  5772. var screenshotCanvas;
  5773. var cloneValue = function (source, destinationObject) {
  5774. if (!source)
  5775. return null;
  5776. if (source instanceof BABYLON.Mesh) {
  5777. return null;
  5778. }
  5779. if (source instanceof BABYLON.SubMesh) {
  5780. return source.clone(destinationObject);
  5781. }
  5782. else if (source.clone) {
  5783. return source.clone();
  5784. }
  5785. return null;
  5786. };
  5787. var Tools = /** @class */ (function () {
  5788. function Tools() {
  5789. }
  5790. /**
  5791. * Interpolates between a and b via alpha
  5792. * @param a The lower value (returned when alpha = 0)
  5793. * @param b The upper value (returned when alpha = 1)
  5794. * @param alpha The interpolation-factor
  5795. * @return The mixed value
  5796. */
  5797. Tools.Mix = function (a, b, alpha) {
  5798. return a * (1 - alpha) + b * alpha;
  5799. };
  5800. Tools.Instantiate = function (className) {
  5801. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  5802. return Tools.RegisteredExternalClasses[className];
  5803. }
  5804. var arr = className.split(".");
  5805. var fn = (window || this);
  5806. for (var i = 0, len = arr.length; i < len; i++) {
  5807. fn = fn[arr[i]];
  5808. }
  5809. if (typeof fn !== "function") {
  5810. return null;
  5811. }
  5812. return fn;
  5813. };
  5814. Tools.SetImmediate = function (action) {
  5815. if (window.setImmediate) {
  5816. window.setImmediate(action);
  5817. }
  5818. else {
  5819. setTimeout(action, 1);
  5820. }
  5821. };
  5822. Tools.IsExponentOfTwo = function (value) {
  5823. var count = 1;
  5824. do {
  5825. count *= 2;
  5826. } while (count < value);
  5827. return count === value;
  5828. };
  5829. /**
  5830. * Find the next highest power of two.
  5831. * @param x Number to start search from.
  5832. * @return Next highest power of two.
  5833. */
  5834. Tools.CeilingPOT = function (x) {
  5835. x--;
  5836. x |= x >> 1;
  5837. x |= x >> 2;
  5838. x |= x >> 4;
  5839. x |= x >> 8;
  5840. x |= x >> 16;
  5841. x++;
  5842. return x;
  5843. };
  5844. /**
  5845. * Find the next lowest power of two.
  5846. * @param x Number to start search from.
  5847. * @return Next lowest power of two.
  5848. */
  5849. Tools.FloorPOT = function (x) {
  5850. x = x | (x >> 1);
  5851. x = x | (x >> 2);
  5852. x = x | (x >> 4);
  5853. x = x | (x >> 8);
  5854. x = x | (x >> 16);
  5855. return x - (x >> 1);
  5856. };
  5857. /**
  5858. * Find the nearest power of two.
  5859. * @param x Number to start search from.
  5860. * @return Next nearest power of two.
  5861. */
  5862. Tools.NearestPOT = function (x) {
  5863. var c = Tools.CeilingPOT(x);
  5864. var f = Tools.FloorPOT(x);
  5865. return (c - x) > (x - f) ? f : c;
  5866. };
  5867. Tools.GetExponentOfTwo = function (value, max, mode) {
  5868. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5869. var pot;
  5870. switch (mode) {
  5871. case BABYLON.Engine.SCALEMODE_FLOOR:
  5872. pot = Tools.FloorPOT(value);
  5873. break;
  5874. case BABYLON.Engine.SCALEMODE_NEAREST:
  5875. pot = Tools.NearestPOT(value);
  5876. break;
  5877. case BABYLON.Engine.SCALEMODE_CEILING:
  5878. default:
  5879. pot = Tools.CeilingPOT(value);
  5880. break;
  5881. }
  5882. return Math.min(pot, max);
  5883. };
  5884. Tools.GetFilename = function (path) {
  5885. var index = path.lastIndexOf("/");
  5886. if (index < 0)
  5887. return path;
  5888. return path.substring(index + 1);
  5889. };
  5890. Tools.GetFolderPath = function (uri) {
  5891. var index = uri.lastIndexOf("/");
  5892. if (index < 0)
  5893. return "";
  5894. return uri.substring(0, index + 1);
  5895. };
  5896. Tools.GetDOMTextContent = function (element) {
  5897. var result = "";
  5898. var child = element.firstChild;
  5899. while (child) {
  5900. if (child.nodeType === 3) {
  5901. result += child.textContent;
  5902. }
  5903. child = child.nextSibling;
  5904. }
  5905. return result;
  5906. };
  5907. Tools.ToDegrees = function (angle) {
  5908. return angle * 180 / Math.PI;
  5909. };
  5910. Tools.ToRadians = function (angle) {
  5911. return angle * Math.PI / 180;
  5912. };
  5913. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5914. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5915. var output = "";
  5916. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5917. var i = 0;
  5918. var bytes = new Uint8Array(buffer);
  5919. while (i < bytes.length) {
  5920. chr1 = bytes[i++];
  5921. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5922. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5923. enc1 = chr1 >> 2;
  5924. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5925. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5926. enc4 = chr3 & 63;
  5927. if (isNaN(chr2)) {
  5928. enc3 = enc4 = 64;
  5929. }
  5930. else if (isNaN(chr3)) {
  5931. enc4 = 64;
  5932. }
  5933. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5934. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5935. }
  5936. return "data:image/png;base64," + output;
  5937. };
  5938. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5939. if (bias === void 0) { bias = null; }
  5940. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5941. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5942. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5943. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5944. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5945. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5946. }
  5947. if (bias) {
  5948. minimum.x -= minimum.x * bias.x + bias.y;
  5949. minimum.y -= minimum.y * bias.x + bias.y;
  5950. minimum.z -= minimum.z * bias.x + bias.y;
  5951. maximum.x += maximum.x * bias.x + bias.y;
  5952. maximum.y += maximum.y * bias.x + bias.y;
  5953. maximum.z += maximum.z * bias.x + bias.y;
  5954. }
  5955. return {
  5956. minimum: minimum,
  5957. maximum: maximum
  5958. };
  5959. };
  5960. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5961. if (bias === void 0) { bias = null; }
  5962. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5963. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5964. if (!stride) {
  5965. stride = 3;
  5966. }
  5967. for (var index = start; index < start + count; index++) {
  5968. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5969. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5970. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5971. }
  5972. if (bias) {
  5973. minimum.x -= minimum.x * bias.x + bias.y;
  5974. minimum.y -= minimum.y * bias.x + bias.y;
  5975. minimum.z -= minimum.z * bias.x + bias.y;
  5976. maximum.x += maximum.x * bias.x + bias.y;
  5977. maximum.y += maximum.y * bias.x + bias.y;
  5978. maximum.z += maximum.z * bias.x + bias.y;
  5979. }
  5980. return {
  5981. minimum: minimum,
  5982. maximum: maximum
  5983. };
  5984. };
  5985. Tools.Vector2ArrayFeeder = function (array) {
  5986. return function (index) {
  5987. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5988. var length = isFloatArray ? array.length / 2 : array.length;
  5989. if (index >= length) {
  5990. return null;
  5991. }
  5992. if (isFloatArray) {
  5993. var fa = array;
  5994. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5995. }
  5996. var a = array;
  5997. return a[index];
  5998. };
  5999. };
  6000. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  6001. if (bias === void 0) { bias = null; }
  6002. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  6003. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  6004. var i = 0;
  6005. var cur = feeder(i++);
  6006. while (cur) {
  6007. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  6008. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  6009. cur = feeder(i++);
  6010. }
  6011. if (bias) {
  6012. minimum.x -= minimum.x * bias.x + bias.y;
  6013. minimum.y -= minimum.y * bias.x + bias.y;
  6014. maximum.x += maximum.x * bias.x + bias.y;
  6015. maximum.y += maximum.y * bias.x + bias.y;
  6016. }
  6017. return {
  6018. minimum: minimum,
  6019. maximum: maximum
  6020. };
  6021. };
  6022. Tools.MakeArray = function (obj, allowsNullUndefined) {
  6023. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  6024. return null;
  6025. return Array.isArray(obj) ? obj : [obj];
  6026. };
  6027. // Misc.
  6028. Tools.GetPointerPrefix = function () {
  6029. var eventPrefix = "pointer";
  6030. // Check if pointer events are supported
  6031. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  6032. eventPrefix = "mouse";
  6033. }
  6034. return eventPrefix;
  6035. };
  6036. /**
  6037. * @param func - the function to be called
  6038. * @param requester - the object that will request the next frame. Falls back to window.
  6039. */
  6040. Tools.QueueNewFrame = function (func, requester) {
  6041. if (!Tools.IsWindowObjectExist()) {
  6042. return setTimeout(func, 16);
  6043. }
  6044. if (!requester) {
  6045. requester = window;
  6046. }
  6047. if (requester.requestAnimationFrame) {
  6048. return requester.requestAnimationFrame(func);
  6049. }
  6050. else if (requester.msRequestAnimationFrame) {
  6051. return requester.msRequestAnimationFrame(func);
  6052. }
  6053. else if (requester.webkitRequestAnimationFrame) {
  6054. return requester.webkitRequestAnimationFrame(func);
  6055. }
  6056. else if (requester.mozRequestAnimationFrame) {
  6057. return requester.mozRequestAnimationFrame(func);
  6058. }
  6059. else if (requester.oRequestAnimationFrame) {
  6060. return requester.oRequestAnimationFrame(func);
  6061. }
  6062. else {
  6063. return window.setTimeout(func, 16);
  6064. }
  6065. };
  6066. Tools.RequestFullscreen = function (element) {
  6067. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  6068. if (!requestFunction)
  6069. return;
  6070. requestFunction.call(element);
  6071. };
  6072. Tools.ExitFullscreen = function () {
  6073. if (document.exitFullscreen) {
  6074. document.exitFullscreen();
  6075. }
  6076. else if (document.mozCancelFullScreen) {
  6077. document.mozCancelFullScreen();
  6078. }
  6079. else if (document.webkitCancelFullScreen) {
  6080. document.webkitCancelFullScreen();
  6081. }
  6082. else if (document.msCancelFullScreen) {
  6083. document.msCancelFullScreen();
  6084. }
  6085. };
  6086. Tools.SetCorsBehavior = function (url, element) {
  6087. if (url && url.indexOf("data:") === 0) {
  6088. return;
  6089. }
  6090. if (Tools.CorsBehavior) {
  6091. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  6092. element.crossOrigin = Tools.CorsBehavior;
  6093. }
  6094. else {
  6095. var result = Tools.CorsBehavior(url);
  6096. if (result) {
  6097. element.crossOrigin = result;
  6098. }
  6099. }
  6100. }
  6101. };
  6102. // External files
  6103. Tools.CleanUrl = function (url) {
  6104. url = url.replace(/#/mg, "%23");
  6105. return url;
  6106. };
  6107. Tools.LoadImage = function (url, onLoad, onError, database) {
  6108. if (url instanceof ArrayBuffer) {
  6109. url = Tools.EncodeArrayBufferTobase64(url);
  6110. }
  6111. url = Tools.CleanUrl(url);
  6112. url = Tools.PreprocessUrl(url);
  6113. var img = new Image();
  6114. Tools.SetCorsBehavior(url, img);
  6115. img.onload = function () {
  6116. onLoad(img);
  6117. };
  6118. img.onerror = function (err) {
  6119. Tools.Error("Error while trying to load image: " + url);
  6120. if (onError) {
  6121. onError("Error while trying to load image: " + url, err);
  6122. }
  6123. };
  6124. var noIndexedDB = function () {
  6125. img.src = url;
  6126. };
  6127. var loadFromIndexedDB = function () {
  6128. if (database) {
  6129. database.loadImageFromDB(url, img);
  6130. }
  6131. };
  6132. //ANY database to do!
  6133. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  6134. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6135. }
  6136. else {
  6137. if (url.indexOf("file:") !== -1) {
  6138. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  6139. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  6140. try {
  6141. var blobURL;
  6142. try {
  6143. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  6144. }
  6145. catch (ex) {
  6146. // Chrome doesn't support oneTimeOnly parameter
  6147. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  6148. }
  6149. img.src = blobURL;
  6150. }
  6151. catch (e) {
  6152. img.src = "";
  6153. }
  6154. return img;
  6155. }
  6156. }
  6157. noIndexedDB();
  6158. }
  6159. return img;
  6160. };
  6161. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  6162. url = Tools.CleanUrl(url);
  6163. url = Tools.PreprocessUrl(url);
  6164. var request = null;
  6165. var noIndexedDB = function () {
  6166. request = new XMLHttpRequest();
  6167. var loadUrl = Tools.BaseUrl + url;
  6168. request.open('GET', loadUrl, true);
  6169. if (useArrayBuffer) {
  6170. request.responseType = "arraybuffer";
  6171. }
  6172. if (progressCallBack) {
  6173. request.onprogress = progressCallBack;
  6174. }
  6175. request.onreadystatechange = function () {
  6176. var req = request;
  6177. // In case of undefined state in some browsers.
  6178. if (req.readyState === (XMLHttpRequest.DONE || 4)) {
  6179. req.onreadystatechange = function () { }; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  6180. if (req.status >= 200 && req.status < 300 || (!Tools.IsWindowObjectExist() && (req.status === 0))) {
  6181. callback(!useArrayBuffer ? req.responseText : req.response, req.responseURL);
  6182. }
  6183. else {
  6184. var e = new Error("Error status: " + req.status + " - Unable to load " + loadUrl);
  6185. if (onError) {
  6186. onError(req, e);
  6187. }
  6188. else {
  6189. throw e;
  6190. }
  6191. }
  6192. }
  6193. };
  6194. request.send(null);
  6195. };
  6196. var loadFromIndexedDB = function () {
  6197. if (database) {
  6198. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  6199. }
  6200. };
  6201. // If file and file input are set
  6202. if (url.indexOf("file:") !== -1) {
  6203. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  6204. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  6205. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  6206. return request;
  6207. }
  6208. }
  6209. // Caching all files
  6210. if (database && database.enableSceneOffline) {
  6211. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6212. }
  6213. else {
  6214. noIndexedDB();
  6215. }
  6216. return request;
  6217. };
  6218. /**
  6219. * Load a script (identified by an url). When the url returns, the
  6220. * content of this file is added into a new script element, attached to the DOM (body element)
  6221. */
  6222. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  6223. var head = document.getElementsByTagName('head')[0];
  6224. var script = document.createElement('script');
  6225. script.type = 'text/javascript';
  6226. script.src = scriptUrl;
  6227. script.onload = function () {
  6228. if (onSuccess) {
  6229. onSuccess();
  6230. }
  6231. };
  6232. script.onerror = function (e) {
  6233. if (onError) {
  6234. onError("Unable to load script", e);
  6235. }
  6236. };
  6237. head.appendChild(script);
  6238. };
  6239. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  6240. var reader = new FileReader();
  6241. reader.onload = function (e) {
  6242. //target doesn't have result from ts 1.3
  6243. callback(e.target['result']);
  6244. };
  6245. reader.onprogress = progressCallback;
  6246. reader.readAsDataURL(fileToLoad);
  6247. };
  6248. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6249. var reader = new FileReader();
  6250. reader.onerror = function (e) {
  6251. Tools.Log("Error while reading file: " + fileToLoad.name);
  6252. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6253. };
  6254. reader.onload = function (e) {
  6255. //target doesn't have result from ts 1.3
  6256. callback(e.target['result']);
  6257. };
  6258. if (progressCallBack) {
  6259. reader.onprogress = progressCallBack;
  6260. }
  6261. if (!useArrayBuffer) {
  6262. // Asynchronous read
  6263. reader.readAsText(fileToLoad);
  6264. }
  6265. else {
  6266. reader.readAsArrayBuffer(fileToLoad);
  6267. }
  6268. };
  6269. //returns a downloadable url to a file content.
  6270. Tools.FileAsURL = function (content) {
  6271. var fileBlob = new Blob([content]);
  6272. var url = window.URL || window.webkitURL;
  6273. var link = url.createObjectURL(fileBlob);
  6274. return link;
  6275. };
  6276. // Misc.
  6277. Tools.Format = function (value, decimals) {
  6278. if (decimals === void 0) { decimals = 2; }
  6279. return value.toFixed(decimals);
  6280. };
  6281. Tools.CheckExtends = function (v, min, max) {
  6282. if (v.x < min.x)
  6283. min.x = v.x;
  6284. if (v.y < min.y)
  6285. min.y = v.y;
  6286. if (v.z < min.z)
  6287. min.z = v.z;
  6288. if (v.x > max.x)
  6289. max.x = v.x;
  6290. if (v.y > max.y)
  6291. max.y = v.y;
  6292. if (v.z > max.z)
  6293. max.z = v.z;
  6294. };
  6295. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6296. for (var prop in source) {
  6297. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6298. continue;
  6299. }
  6300. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6301. continue;
  6302. }
  6303. var sourceValue = source[prop];
  6304. var typeOfSourceValue = typeof sourceValue;
  6305. if (typeOfSourceValue === "function") {
  6306. continue;
  6307. }
  6308. if (typeOfSourceValue === "object") {
  6309. if (sourceValue instanceof Array) {
  6310. destination[prop] = [];
  6311. if (sourceValue.length > 0) {
  6312. if (typeof sourceValue[0] == "object") {
  6313. for (var index = 0; index < sourceValue.length; index++) {
  6314. var clonedValue = cloneValue(sourceValue[index], destination);
  6315. if (destination[prop].indexOf(clonedValue) === -1) {
  6316. destination[prop].push(clonedValue);
  6317. }
  6318. }
  6319. }
  6320. else {
  6321. destination[prop] = sourceValue.slice(0);
  6322. }
  6323. }
  6324. }
  6325. else {
  6326. destination[prop] = cloneValue(sourceValue, destination);
  6327. }
  6328. }
  6329. else {
  6330. destination[prop] = sourceValue;
  6331. }
  6332. }
  6333. };
  6334. Tools.IsEmpty = function (obj) {
  6335. for (var i in obj) {
  6336. if (obj.hasOwnProperty(i)) {
  6337. return false;
  6338. }
  6339. }
  6340. return true;
  6341. };
  6342. Tools.RegisterTopRootEvents = function (events) {
  6343. for (var index = 0; index < events.length; index++) {
  6344. var event = events[index];
  6345. window.addEventListener(event.name, event.handler, false);
  6346. try {
  6347. if (window.parent) {
  6348. window.parent.addEventListener(event.name, event.handler, false);
  6349. }
  6350. }
  6351. catch (e) {
  6352. // Silently fails...
  6353. }
  6354. }
  6355. };
  6356. Tools.UnregisterTopRootEvents = function (events) {
  6357. for (var index = 0; index < events.length; index++) {
  6358. var event = events[index];
  6359. window.removeEventListener(event.name, event.handler);
  6360. try {
  6361. if (window.parent) {
  6362. window.parent.removeEventListener(event.name, event.handler);
  6363. }
  6364. }
  6365. catch (e) {
  6366. // Silently fails...
  6367. }
  6368. }
  6369. };
  6370. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  6371. if (mimeType === void 0) { mimeType = "image/png"; }
  6372. // Read the contents of the framebuffer
  6373. var numberOfChannelsByLine = width * 4;
  6374. var halfHeight = height / 2;
  6375. //Reading datas from WebGL
  6376. var data = engine.readPixels(0, 0, width, height);
  6377. //To flip image on Y axis.
  6378. for (var i = 0; i < halfHeight; i++) {
  6379. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6380. var currentCell = j + i * numberOfChannelsByLine;
  6381. var targetLine = height - i - 1;
  6382. var targetCell = j + targetLine * numberOfChannelsByLine;
  6383. var temp = data[currentCell];
  6384. data[currentCell] = data[targetCell];
  6385. data[targetCell] = temp;
  6386. }
  6387. }
  6388. // Create a 2D canvas to store the result
  6389. if (!screenshotCanvas) {
  6390. screenshotCanvas = document.createElement('canvas');
  6391. }
  6392. screenshotCanvas.width = width;
  6393. screenshotCanvas.height = height;
  6394. var context = screenshotCanvas.getContext('2d');
  6395. if (context) {
  6396. // Copy the pixels to a 2D canvas
  6397. var imageData = context.createImageData(width, height);
  6398. var castData = (imageData.data);
  6399. castData.set(data);
  6400. context.putImageData(imageData, 0, 0);
  6401. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  6402. }
  6403. };
  6404. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  6405. if (mimeType === void 0) { mimeType = "image/png"; }
  6406. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6407. if (successCallback) {
  6408. successCallback(base64Image);
  6409. }
  6410. else {
  6411. // We need HTMLCanvasElement.toBlob for HD screenshots
  6412. if (!screenshotCanvas.toBlob) {
  6413. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  6414. screenshotCanvas.toBlob = function (callback, type, quality) {
  6415. var _this = this;
  6416. setTimeout(function () {
  6417. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  6418. for (var i = 0; i < len; i++) {
  6419. arr[i] = binStr.charCodeAt(i);
  6420. }
  6421. callback(new Blob([arr], { type: type || 'image/png' }));
  6422. });
  6423. };
  6424. }
  6425. screenshotCanvas.toBlob(function (blob) {
  6426. var url = URL.createObjectURL(blob);
  6427. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6428. if (("download" in document.createElement("a"))) {
  6429. var a = window.document.createElement("a");
  6430. a.href = url;
  6431. if (fileName) {
  6432. a.setAttribute("download", fileName);
  6433. }
  6434. else {
  6435. var date = new Date();
  6436. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6437. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6438. }
  6439. window.document.body.appendChild(a);
  6440. a.addEventListener("click", function () {
  6441. if (a.parentElement) {
  6442. a.parentElement.removeChild(a);
  6443. }
  6444. });
  6445. a.click();
  6446. }
  6447. else {
  6448. var newWindow = window.open("");
  6449. if (!newWindow)
  6450. return;
  6451. var img = newWindow.document.createElement("img");
  6452. img.onload = function () {
  6453. // no longer need to read the blob so it's revoked
  6454. URL.revokeObjectURL(url);
  6455. };
  6456. img.src = url;
  6457. newWindow.document.body.appendChild(img);
  6458. }
  6459. });
  6460. }
  6461. };
  6462. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6463. if (mimeType === void 0) { mimeType = "image/png"; }
  6464. var width;
  6465. var height;
  6466. // If a precision value is specified
  6467. if (size.precision) {
  6468. width = Math.round(engine.getRenderWidth() * size.precision);
  6469. height = Math.round(width / engine.getAspectRatio(camera));
  6470. }
  6471. else if (size.width && size.height) {
  6472. width = size.width;
  6473. height = size.height;
  6474. }
  6475. else if (size.width && !size.height) {
  6476. width = size.width;
  6477. height = Math.round(width / engine.getAspectRatio(camera));
  6478. }
  6479. else if (size.height && !size.width) {
  6480. height = size.height;
  6481. width = Math.round(height * engine.getAspectRatio(camera));
  6482. }
  6483. else if (!isNaN(size)) {
  6484. height = size;
  6485. width = size;
  6486. }
  6487. else {
  6488. Tools.Error("Invalid 'size' parameter !");
  6489. return;
  6490. }
  6491. if (!screenshotCanvas) {
  6492. screenshotCanvas = document.createElement('canvas');
  6493. }
  6494. screenshotCanvas.width = width;
  6495. screenshotCanvas.height = height;
  6496. var renderContext = screenshotCanvas.getContext("2d");
  6497. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6498. var newWidth = width;
  6499. var newHeight = newWidth / ratio;
  6500. if (newHeight > height) {
  6501. newHeight = height;
  6502. newWidth = newHeight * ratio;
  6503. }
  6504. var offsetX = Math.max(0, width - newWidth) / 2;
  6505. var offsetY = Math.max(0, height - newHeight) / 2;
  6506. var renderingCanvas = engine.getRenderingCanvas();
  6507. if (renderContext && renderingCanvas) {
  6508. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  6509. }
  6510. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6511. };
  6512. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  6513. if (mimeType === void 0) { mimeType = "image/png"; }
  6514. if (samples === void 0) { samples = 1; }
  6515. if (antialiasing === void 0) { antialiasing = false; }
  6516. var width;
  6517. var height;
  6518. //If a precision value is specified
  6519. if (size.precision) {
  6520. width = Math.round(engine.getRenderWidth() * size.precision);
  6521. height = Math.round(width / engine.getAspectRatio(camera));
  6522. size = { width: width, height: height };
  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. size = { width: width, height: height };
  6532. }
  6533. else if (size.height && !size.width) {
  6534. height = size.height;
  6535. width = Math.round(height * engine.getAspectRatio(camera));
  6536. size = { width: width, height: height };
  6537. }
  6538. else if (!isNaN(size)) {
  6539. height = size;
  6540. width = size;
  6541. }
  6542. else {
  6543. Tools.Error("Invalid 'size' parameter !");
  6544. return;
  6545. }
  6546. var scene = camera.getScene();
  6547. var previousCamera = null;
  6548. if (scene.activeCamera !== camera) {
  6549. previousCamera = scene.activeCamera;
  6550. scene.activeCamera = camera;
  6551. }
  6552. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6553. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6554. texture.renderList = null;
  6555. texture.samples = samples;
  6556. if (antialiasing) {
  6557. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  6558. }
  6559. texture.onAfterRenderObservable.add(function () {
  6560. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  6561. });
  6562. scene.incrementRenderId();
  6563. scene.resetCachedMaterial();
  6564. texture.render(true);
  6565. texture.dispose();
  6566. if (previousCamera) {
  6567. scene.activeCamera = previousCamera;
  6568. }
  6569. camera.getProjectionMatrix(true); // Force cache refresh;
  6570. };
  6571. // XHR response validator for local file scenario
  6572. Tools.ValidateXHRData = function (xhr, dataType) {
  6573. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6574. if (dataType === void 0) { dataType = 7; }
  6575. try {
  6576. if (dataType & 1) {
  6577. if (xhr.responseText && xhr.responseText.length > 0) {
  6578. return true;
  6579. }
  6580. else if (dataType === 1) {
  6581. return false;
  6582. }
  6583. }
  6584. if (dataType & 2) {
  6585. // Check header width and height since there is no "TGA" magic number
  6586. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6587. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6588. return true;
  6589. }
  6590. else if (dataType === 2) {
  6591. return false;
  6592. }
  6593. }
  6594. if (dataType & 4) {
  6595. // Check for the "DDS" magic number
  6596. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6597. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6598. return true;
  6599. }
  6600. else {
  6601. return false;
  6602. }
  6603. }
  6604. }
  6605. catch (e) {
  6606. // Global protection
  6607. }
  6608. return false;
  6609. };
  6610. /**
  6611. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6612. * Be aware Math.random() could cause collisions, but:
  6613. * "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"
  6614. */
  6615. Tools.RandomId = function () {
  6616. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6617. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6618. return v.toString(16);
  6619. });
  6620. };
  6621. Object.defineProperty(Tools, "NoneLogLevel", {
  6622. get: function () {
  6623. return Tools._NoneLogLevel;
  6624. },
  6625. enumerable: true,
  6626. configurable: true
  6627. });
  6628. Object.defineProperty(Tools, "MessageLogLevel", {
  6629. get: function () {
  6630. return Tools._MessageLogLevel;
  6631. },
  6632. enumerable: true,
  6633. configurable: true
  6634. });
  6635. Object.defineProperty(Tools, "WarningLogLevel", {
  6636. get: function () {
  6637. return Tools._WarningLogLevel;
  6638. },
  6639. enumerable: true,
  6640. configurable: true
  6641. });
  6642. Object.defineProperty(Tools, "ErrorLogLevel", {
  6643. get: function () {
  6644. return Tools._ErrorLogLevel;
  6645. },
  6646. enumerable: true,
  6647. configurable: true
  6648. });
  6649. Object.defineProperty(Tools, "AllLogLevel", {
  6650. get: function () {
  6651. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6652. },
  6653. enumerable: true,
  6654. configurable: true
  6655. });
  6656. Tools._AddLogEntry = function (entry) {
  6657. Tools._LogCache = entry + Tools._LogCache;
  6658. if (Tools.OnNewCacheEntry) {
  6659. Tools.OnNewCacheEntry(entry);
  6660. }
  6661. };
  6662. Tools._FormatMessage = function (message) {
  6663. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6664. var date = new Date();
  6665. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6666. };
  6667. Tools._LogDisabled = function (message) {
  6668. // nothing to do
  6669. };
  6670. Tools._LogEnabled = function (message) {
  6671. var formattedMessage = Tools._FormatMessage(message);
  6672. console.log("BJS - " + formattedMessage);
  6673. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6674. Tools._AddLogEntry(entry);
  6675. };
  6676. Tools._WarnDisabled = function (message) {
  6677. // nothing to do
  6678. };
  6679. Tools._WarnEnabled = function (message) {
  6680. var formattedMessage = Tools._FormatMessage(message);
  6681. console.warn("BJS - " + formattedMessage);
  6682. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6683. Tools._AddLogEntry(entry);
  6684. };
  6685. Tools._ErrorDisabled = function (message) {
  6686. // nothing to do
  6687. };
  6688. Tools._ErrorEnabled = function (message) {
  6689. Tools.errorsCount++;
  6690. var formattedMessage = Tools._FormatMessage(message);
  6691. console.error("BJS - " + formattedMessage);
  6692. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6693. Tools._AddLogEntry(entry);
  6694. };
  6695. Object.defineProperty(Tools, "LogCache", {
  6696. get: function () {
  6697. return Tools._LogCache;
  6698. },
  6699. enumerable: true,
  6700. configurable: true
  6701. });
  6702. Tools.ClearLogCache = function () {
  6703. Tools._LogCache = "";
  6704. Tools.errorsCount = 0;
  6705. };
  6706. Object.defineProperty(Tools, "LogLevels", {
  6707. set: function (level) {
  6708. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6709. Tools.Log = Tools._LogEnabled;
  6710. }
  6711. else {
  6712. Tools.Log = Tools._LogDisabled;
  6713. }
  6714. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6715. Tools.Warn = Tools._WarnEnabled;
  6716. }
  6717. else {
  6718. Tools.Warn = Tools._WarnDisabled;
  6719. }
  6720. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6721. Tools.Error = Tools._ErrorEnabled;
  6722. }
  6723. else {
  6724. Tools.Error = Tools._ErrorDisabled;
  6725. }
  6726. },
  6727. enumerable: true,
  6728. configurable: true
  6729. });
  6730. Tools.IsWindowObjectExist = function () {
  6731. return (typeof window) !== "undefined";
  6732. };
  6733. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6734. get: function () {
  6735. return Tools._PerformanceNoneLogLevel;
  6736. },
  6737. enumerable: true,
  6738. configurable: true
  6739. });
  6740. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6741. get: function () {
  6742. return Tools._PerformanceUserMarkLogLevel;
  6743. },
  6744. enumerable: true,
  6745. configurable: true
  6746. });
  6747. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6748. get: function () {
  6749. return Tools._PerformanceConsoleLogLevel;
  6750. },
  6751. enumerable: true,
  6752. configurable: true
  6753. });
  6754. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6755. set: function (level) {
  6756. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6757. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6758. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6759. return;
  6760. }
  6761. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6762. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6763. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6764. return;
  6765. }
  6766. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6767. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6768. },
  6769. enumerable: true,
  6770. configurable: true
  6771. });
  6772. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6773. };
  6774. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6775. };
  6776. Tools._StartUserMark = function (counterName, condition) {
  6777. if (condition === void 0) { condition = true; }
  6778. if (!Tools._performance) {
  6779. if (!Tools.IsWindowObjectExist()) {
  6780. return;
  6781. }
  6782. Tools._performance = window.performance;
  6783. }
  6784. if (!condition || !Tools._performance.mark) {
  6785. return;
  6786. }
  6787. Tools._performance.mark(counterName + "-Begin");
  6788. };
  6789. Tools._EndUserMark = function (counterName, condition) {
  6790. if (condition === void 0) { condition = true; }
  6791. if (!condition || !Tools._performance.mark) {
  6792. return;
  6793. }
  6794. Tools._performance.mark(counterName + "-End");
  6795. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6796. };
  6797. Tools._StartPerformanceConsole = function (counterName, condition) {
  6798. if (condition === void 0) { condition = true; }
  6799. if (!condition) {
  6800. return;
  6801. }
  6802. Tools._StartUserMark(counterName, condition);
  6803. if (console.time) {
  6804. console.time(counterName);
  6805. }
  6806. };
  6807. Tools._EndPerformanceConsole = function (counterName, condition) {
  6808. if (condition === void 0) { condition = true; }
  6809. if (!condition) {
  6810. return;
  6811. }
  6812. Tools._EndUserMark(counterName, condition);
  6813. if (console.time) {
  6814. console.timeEnd(counterName);
  6815. }
  6816. };
  6817. Object.defineProperty(Tools, "Now", {
  6818. get: function () {
  6819. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  6820. return window.performance.now();
  6821. }
  6822. return new Date().getTime();
  6823. },
  6824. enumerable: true,
  6825. configurable: true
  6826. });
  6827. /**
  6828. * This method will return the name of the class used to create the instance of the given object.
  6829. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6830. * @param object the object to get the class name from
  6831. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6832. */
  6833. Tools.GetClassName = function (object, isType) {
  6834. if (isType === void 0) { isType = false; }
  6835. var name = null;
  6836. if (!isType && object.getClassName) {
  6837. name = object.getClassName();
  6838. }
  6839. else {
  6840. if (object instanceof Object) {
  6841. var classObj = isType ? object : Object.getPrototypeOf(object);
  6842. name = classObj.constructor["__bjsclassName__"];
  6843. }
  6844. if (!name) {
  6845. name = typeof object;
  6846. }
  6847. }
  6848. return name;
  6849. };
  6850. Tools.First = function (array, predicate) {
  6851. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6852. var el = array_1[_i];
  6853. if (predicate(el)) {
  6854. return el;
  6855. }
  6856. }
  6857. return null;
  6858. };
  6859. /**
  6860. * This method will return the name of the full name of the class, including its owning module (if any).
  6861. * 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).
  6862. * @param object the object to get the class name from
  6863. * @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.
  6864. */
  6865. Tools.getFullClassName = function (object, isType) {
  6866. if (isType === void 0) { isType = false; }
  6867. var className = null;
  6868. var moduleName = null;
  6869. if (!isType && object.getClassName) {
  6870. className = object.getClassName();
  6871. }
  6872. else {
  6873. if (object instanceof Object) {
  6874. var classObj = isType ? object : Object.getPrototypeOf(object);
  6875. className = classObj.constructor["__bjsclassName__"];
  6876. moduleName = classObj.constructor["__bjsmoduleName__"];
  6877. }
  6878. if (!className) {
  6879. className = typeof object;
  6880. }
  6881. }
  6882. if (!className) {
  6883. return null;
  6884. }
  6885. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6886. };
  6887. /**
  6888. * 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.
  6889. * @param array
  6890. */
  6891. Tools.arrayOrStringFeeder = function (array) {
  6892. return function (index) {
  6893. if (index >= array.length) {
  6894. return null;
  6895. }
  6896. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6897. if (val && val.getHashCode) {
  6898. val = val.getHashCode();
  6899. }
  6900. if (typeof val === "string") {
  6901. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6902. }
  6903. return val;
  6904. };
  6905. };
  6906. /**
  6907. * Compute the hashCode of a stream of number
  6908. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6909. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6910. * @return the hash code computed
  6911. */
  6912. Tools.hashCodeFromStream = function (feeder) {
  6913. // Based from here: http://stackoverflow.com/a/7616484/802124
  6914. var hash = 0;
  6915. var index = 0;
  6916. var chr = feeder(index++);
  6917. while (chr != null) {
  6918. hash = ((hash << 5) - hash) + chr;
  6919. hash |= 0; // Convert to 32bit integer
  6920. chr = feeder(index++);
  6921. }
  6922. return hash;
  6923. };
  6924. Tools.BaseUrl = "";
  6925. /**
  6926. * Default behaviour for cors in the application.
  6927. * It can be a string if the expected behavior is identical in the entire app.
  6928. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  6929. */
  6930. Tools.CorsBehavior = "anonymous";
  6931. Tools.UseFallbackTexture = true;
  6932. /**
  6933. * Use this object to register external classes like custom textures or material
  6934. * to allow the laoders to instantiate them
  6935. */
  6936. Tools.RegisteredExternalClasses = {};
  6937. // Used in case of a texture loading problem
  6938. 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";
  6939. Tools.PreprocessUrl = function (url) {
  6940. return url;
  6941. };
  6942. // Logs
  6943. Tools._NoneLogLevel = 0;
  6944. Tools._MessageLogLevel = 1;
  6945. Tools._WarningLogLevel = 2;
  6946. Tools._ErrorLogLevel = 4;
  6947. Tools._LogCache = "";
  6948. Tools.errorsCount = 0;
  6949. Tools.Log = Tools._LogEnabled;
  6950. Tools.Warn = Tools._WarnEnabled;
  6951. Tools.Error = Tools._ErrorEnabled;
  6952. // Performances
  6953. Tools._PerformanceNoneLogLevel = 0;
  6954. Tools._PerformanceUserMarkLogLevel = 1;
  6955. Tools._PerformanceConsoleLogLevel = 2;
  6956. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6957. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6958. return Tools;
  6959. }());
  6960. BABYLON.Tools = Tools;
  6961. /**
  6962. * This class is used to track a performance counter which is number based.
  6963. * The user has access to many properties which give statistics of different nature
  6964. *
  6965. * The implementer can track two kinds of Performance Counter: time and count
  6966. * 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.
  6967. * 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.
  6968. */
  6969. var PerfCounter = /** @class */ (function () {
  6970. function PerfCounter() {
  6971. this._startMonitoringTime = 0;
  6972. this._min = 0;
  6973. this._max = 0;
  6974. this._average = 0;
  6975. this._lastSecAverage = 0;
  6976. this._current = 0;
  6977. this._totalValueCount = 0;
  6978. this._totalAccumulated = 0;
  6979. this._lastSecAccumulated = 0;
  6980. this._lastSecTime = 0;
  6981. this._lastSecValueCount = 0;
  6982. }
  6983. Object.defineProperty(PerfCounter.prototype, "min", {
  6984. /**
  6985. * Returns the smallest value ever
  6986. */
  6987. get: function () {
  6988. return this._min;
  6989. },
  6990. enumerable: true,
  6991. configurable: true
  6992. });
  6993. Object.defineProperty(PerfCounter.prototype, "max", {
  6994. /**
  6995. * Returns the biggest value ever
  6996. */
  6997. get: function () {
  6998. return this._max;
  6999. },
  7000. enumerable: true,
  7001. configurable: true
  7002. });
  7003. Object.defineProperty(PerfCounter.prototype, "average", {
  7004. /**
  7005. * Returns the average value since the performance counter is running
  7006. */
  7007. get: function () {
  7008. return this._average;
  7009. },
  7010. enumerable: true,
  7011. configurable: true
  7012. });
  7013. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  7014. /**
  7015. * Returns the average value of the last second the counter was monitored
  7016. */
  7017. get: function () {
  7018. return this._lastSecAverage;
  7019. },
  7020. enumerable: true,
  7021. configurable: true
  7022. });
  7023. Object.defineProperty(PerfCounter.prototype, "current", {
  7024. /**
  7025. * Returns the current value
  7026. */
  7027. get: function () {
  7028. return this._current;
  7029. },
  7030. enumerable: true,
  7031. configurable: true
  7032. });
  7033. Object.defineProperty(PerfCounter.prototype, "total", {
  7034. get: function () {
  7035. return this._totalAccumulated;
  7036. },
  7037. enumerable: true,
  7038. configurable: true
  7039. });
  7040. Object.defineProperty(PerfCounter.prototype, "count", {
  7041. get: function () {
  7042. return this._totalValueCount;
  7043. },
  7044. enumerable: true,
  7045. configurable: true
  7046. });
  7047. /**
  7048. * Call this method to start monitoring a new frame.
  7049. * 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.
  7050. */
  7051. PerfCounter.prototype.fetchNewFrame = function () {
  7052. this._totalValueCount++;
  7053. this._current = 0;
  7054. this._lastSecValueCount++;
  7055. };
  7056. /**
  7057. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  7058. * @param newCount the count value to add to the monitored count
  7059. * @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.
  7060. */
  7061. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  7062. if (!PerfCounter.Enabled) {
  7063. return;
  7064. }
  7065. this._current += newCount;
  7066. if (fetchResult) {
  7067. this._fetchResult();
  7068. }
  7069. };
  7070. /**
  7071. * Start monitoring this performance counter
  7072. */
  7073. PerfCounter.prototype.beginMonitoring = function () {
  7074. if (!PerfCounter.Enabled) {
  7075. return;
  7076. }
  7077. this._startMonitoringTime = Tools.Now;
  7078. };
  7079. /**
  7080. * Compute the time lapsed since the previous beginMonitoring() call.
  7081. * @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
  7082. */
  7083. PerfCounter.prototype.endMonitoring = function (newFrame) {
  7084. if (newFrame === void 0) { newFrame = true; }
  7085. if (!PerfCounter.Enabled) {
  7086. return;
  7087. }
  7088. if (newFrame) {
  7089. this.fetchNewFrame();
  7090. }
  7091. var currentTime = Tools.Now;
  7092. this._current = currentTime - this._startMonitoringTime;
  7093. if (newFrame) {
  7094. this._fetchResult();
  7095. }
  7096. };
  7097. PerfCounter.prototype._fetchResult = function () {
  7098. this._totalAccumulated += this._current;
  7099. this._lastSecAccumulated += this._current;
  7100. // Min/Max update
  7101. this._min = Math.min(this._min, this._current);
  7102. this._max = Math.max(this._max, this._current);
  7103. this._average = this._totalAccumulated / this._totalValueCount;
  7104. // Reset last sec?
  7105. var now = Tools.Now;
  7106. if ((now - this._lastSecTime) > 1000) {
  7107. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  7108. this._lastSecTime = now;
  7109. this._lastSecAccumulated = 0;
  7110. this._lastSecValueCount = 0;
  7111. }
  7112. };
  7113. PerfCounter.Enabled = true;
  7114. return PerfCounter;
  7115. }());
  7116. BABYLON.PerfCounter = PerfCounter;
  7117. /**
  7118. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  7119. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  7120. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  7121. * @param name The name of the class, case should be preserved
  7122. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  7123. */
  7124. function className(name, module) {
  7125. return function (target) {
  7126. target["__bjsclassName__"] = name;
  7127. target["__bjsmoduleName__"] = (module != null) ? module : null;
  7128. };
  7129. }
  7130. BABYLON.className = className;
  7131. /**
  7132. * An implementation of a loop for asynchronous functions.
  7133. */
  7134. var AsyncLoop = /** @class */ (function () {
  7135. /**
  7136. * Constroctor.
  7137. * @param iterations the number of iterations.
  7138. * @param _fn the function to run each iteration
  7139. * @param _successCallback the callback that will be called upon succesful execution
  7140. * @param offset starting offset.
  7141. */
  7142. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  7143. if (offset === void 0) { offset = 0; }
  7144. this.iterations = iterations;
  7145. this._fn = _fn;
  7146. this._successCallback = _successCallback;
  7147. this.index = offset - 1;
  7148. this._done = false;
  7149. }
  7150. /**
  7151. * Execute the next iteration. Must be called after the last iteration was finished.
  7152. */
  7153. AsyncLoop.prototype.executeNext = function () {
  7154. if (!this._done) {
  7155. if (this.index + 1 < this.iterations) {
  7156. ++this.index;
  7157. this._fn(this);
  7158. }
  7159. else {
  7160. this.breakLoop();
  7161. }
  7162. }
  7163. };
  7164. /**
  7165. * Break the loop and run the success callback.
  7166. */
  7167. AsyncLoop.prototype.breakLoop = function () {
  7168. this._done = true;
  7169. this._successCallback();
  7170. };
  7171. /**
  7172. * Helper function
  7173. */
  7174. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  7175. if (offset === void 0) { offset = 0; }
  7176. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  7177. loop.executeNext();
  7178. return loop;
  7179. };
  7180. /**
  7181. * A for-loop that will run a given number of iterations synchronous and the rest async.
  7182. * @param iterations total number of iterations
  7183. * @param syncedIterations number of synchronous iterations in each async iteration.
  7184. * @param fn the function to call each iteration.
  7185. * @param callback a success call back that will be called when iterating stops.
  7186. * @param breakFunction a break condition (optional)
  7187. * @param timeout timeout settings for the setTimeout function. default - 0.
  7188. * @constructor
  7189. */
  7190. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  7191. if (timeout === void 0) { timeout = 0; }
  7192. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  7193. if (breakFunction && breakFunction())
  7194. loop.breakLoop();
  7195. else {
  7196. setTimeout(function () {
  7197. for (var i = 0; i < syncedIterations; ++i) {
  7198. var iteration = (loop.index * syncedIterations) + i;
  7199. if (iteration >= iterations)
  7200. break;
  7201. fn(iteration);
  7202. if (breakFunction && breakFunction()) {
  7203. loop.breakLoop();
  7204. break;
  7205. }
  7206. }
  7207. loop.executeNext();
  7208. }, timeout);
  7209. }
  7210. }, callback);
  7211. };
  7212. return AsyncLoop;
  7213. }());
  7214. BABYLON.AsyncLoop = AsyncLoop;
  7215. })(BABYLON || (BABYLON = {}));
  7216. //# sourceMappingURL=babylon.tools.js.map
  7217. var BABYLON;
  7218. (function (BABYLON) {
  7219. var Internals;
  7220. (function (Internals) {
  7221. var _AlphaState = /** @class */ (function () {
  7222. /**
  7223. * Initializes the state.
  7224. */
  7225. function _AlphaState() {
  7226. this._isAlphaBlendDirty = false;
  7227. this._isBlendFunctionParametersDirty = false;
  7228. this._isBlendEquationParametersDirty = false;
  7229. this._isBlendConstantsDirty = false;
  7230. this._alphaBlend = false;
  7231. this._blendFunctionParameters = new Array(4);
  7232. this._blendEquationParameters = new Array(2);
  7233. this._blendConstants = new Array(4);
  7234. this.reset();
  7235. }
  7236. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  7237. get: function () {
  7238. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  7239. },
  7240. enumerable: true,
  7241. configurable: true
  7242. });
  7243. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  7244. get: function () {
  7245. return this._alphaBlend;
  7246. },
  7247. set: function (value) {
  7248. if (this._alphaBlend === value) {
  7249. return;
  7250. }
  7251. this._alphaBlend = value;
  7252. this._isAlphaBlendDirty = true;
  7253. },
  7254. enumerable: true,
  7255. configurable: true
  7256. });
  7257. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  7258. if (this._blendConstants[0] === r &&
  7259. this._blendConstants[1] === g &&
  7260. this._blendConstants[2] === b &&
  7261. this._blendConstants[3] === a) {
  7262. return;
  7263. }
  7264. this._blendConstants[0] = r;
  7265. this._blendConstants[1] = g;
  7266. this._blendConstants[2] = b;
  7267. this._blendConstants[3] = a;
  7268. this._isBlendConstantsDirty = true;
  7269. };
  7270. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  7271. if (this._blendFunctionParameters[0] === value0 &&
  7272. this._blendFunctionParameters[1] === value1 &&
  7273. this._blendFunctionParameters[2] === value2 &&
  7274. this._blendFunctionParameters[3] === value3) {
  7275. return;
  7276. }
  7277. this._blendFunctionParameters[0] = value0;
  7278. this._blendFunctionParameters[1] = value1;
  7279. this._blendFunctionParameters[2] = value2;
  7280. this._blendFunctionParameters[3] = value3;
  7281. this._isBlendFunctionParametersDirty = true;
  7282. };
  7283. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  7284. if (this._blendEquationParameters[0] === rgb &&
  7285. this._blendEquationParameters[1] === alpha) {
  7286. return;
  7287. }
  7288. this._blendEquationParameters[0] = rgb;
  7289. this._blendEquationParameters[1] = alpha;
  7290. this._isBlendEquationParametersDirty = true;
  7291. };
  7292. _AlphaState.prototype.reset = function () {
  7293. this._alphaBlend = false;
  7294. this._blendFunctionParameters[0] = null;
  7295. this._blendFunctionParameters[1] = null;
  7296. this._blendFunctionParameters[2] = null;
  7297. this._blendFunctionParameters[3] = null;
  7298. this._blendEquationParameters[0] = null;
  7299. this._blendEquationParameters[1] = null;
  7300. this._blendConstants[0] = null;
  7301. this._blendConstants[1] = null;
  7302. this._blendConstants[2] = null;
  7303. this._blendConstants[3] = null;
  7304. this._isAlphaBlendDirty = true;
  7305. this._isBlendFunctionParametersDirty = false;
  7306. this._isBlendEquationParametersDirty = false;
  7307. this._isBlendConstantsDirty = false;
  7308. };
  7309. _AlphaState.prototype.apply = function (gl) {
  7310. if (!this.isDirty) {
  7311. return;
  7312. }
  7313. // Alpha blend
  7314. if (this._isAlphaBlendDirty) {
  7315. if (this._alphaBlend) {
  7316. gl.enable(gl.BLEND);
  7317. }
  7318. else {
  7319. gl.disable(gl.BLEND);
  7320. }
  7321. this._isAlphaBlendDirty = false;
  7322. }
  7323. // Alpha function
  7324. if (this._isBlendFunctionParametersDirty) {
  7325. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7326. this._isBlendFunctionParametersDirty = false;
  7327. }
  7328. // Alpha equation
  7329. if (this._isBlendEquationParametersDirty) {
  7330. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  7331. this._isBlendEquationParametersDirty = false;
  7332. }
  7333. // Constants
  7334. if (this._isBlendConstantsDirty) {
  7335. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  7336. this._isBlendConstantsDirty = false;
  7337. }
  7338. };
  7339. return _AlphaState;
  7340. }());
  7341. Internals._AlphaState = _AlphaState;
  7342. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7343. })(BABYLON || (BABYLON = {}));
  7344. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7345. var BABYLON;
  7346. (function (BABYLON) {
  7347. var Internals;
  7348. (function (Internals) {
  7349. var _DepthCullingState = /** @class */ (function () {
  7350. /**
  7351. * Initializes the state.
  7352. */
  7353. function _DepthCullingState() {
  7354. this._isDepthTestDirty = false;
  7355. this._isDepthMaskDirty = false;
  7356. this._isDepthFuncDirty = false;
  7357. this._isCullFaceDirty = false;
  7358. this._isCullDirty = false;
  7359. this._isZOffsetDirty = false;
  7360. this.reset();
  7361. }
  7362. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7363. get: function () {
  7364. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7365. },
  7366. enumerable: true,
  7367. configurable: true
  7368. });
  7369. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7370. get: function () {
  7371. return this._zOffset;
  7372. },
  7373. set: function (value) {
  7374. if (this._zOffset === value) {
  7375. return;
  7376. }
  7377. this._zOffset = value;
  7378. this._isZOffsetDirty = true;
  7379. },
  7380. enumerable: true,
  7381. configurable: true
  7382. });
  7383. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7384. get: function () {
  7385. return this._cullFace;
  7386. },
  7387. set: function (value) {
  7388. if (this._cullFace === value) {
  7389. return;
  7390. }
  7391. this._cullFace = value;
  7392. this._isCullFaceDirty = true;
  7393. },
  7394. enumerable: true,
  7395. configurable: true
  7396. });
  7397. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7398. get: function () {
  7399. return this._cull;
  7400. },
  7401. set: function (value) {
  7402. if (this._cull === value) {
  7403. return;
  7404. }
  7405. this._cull = value;
  7406. this._isCullDirty = true;
  7407. },
  7408. enumerable: true,
  7409. configurable: true
  7410. });
  7411. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7412. get: function () {
  7413. return this._depthFunc;
  7414. },
  7415. set: function (value) {
  7416. if (this._depthFunc === value) {
  7417. return;
  7418. }
  7419. this._depthFunc = value;
  7420. this._isDepthFuncDirty = true;
  7421. },
  7422. enumerable: true,
  7423. configurable: true
  7424. });
  7425. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7426. get: function () {
  7427. return this._depthMask;
  7428. },
  7429. set: function (value) {
  7430. if (this._depthMask === value) {
  7431. return;
  7432. }
  7433. this._depthMask = value;
  7434. this._isDepthMaskDirty = true;
  7435. },
  7436. enumerable: true,
  7437. configurable: true
  7438. });
  7439. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7440. get: function () {
  7441. return this._depthTest;
  7442. },
  7443. set: function (value) {
  7444. if (this._depthTest === value) {
  7445. return;
  7446. }
  7447. this._depthTest = value;
  7448. this._isDepthTestDirty = true;
  7449. },
  7450. enumerable: true,
  7451. configurable: true
  7452. });
  7453. _DepthCullingState.prototype.reset = function () {
  7454. this._depthMask = true;
  7455. this._depthTest = true;
  7456. this._depthFunc = null;
  7457. this._cullFace = null;
  7458. this._cull = null;
  7459. this._zOffset = 0;
  7460. this._isDepthTestDirty = true;
  7461. this._isDepthMaskDirty = true;
  7462. this._isDepthFuncDirty = false;
  7463. this._isCullFaceDirty = false;
  7464. this._isCullDirty = false;
  7465. this._isZOffsetDirty = false;
  7466. };
  7467. _DepthCullingState.prototype.apply = function (gl) {
  7468. if (!this.isDirty) {
  7469. return;
  7470. }
  7471. // Cull
  7472. if (this._isCullDirty) {
  7473. if (this.cull) {
  7474. gl.enable(gl.CULL_FACE);
  7475. }
  7476. else {
  7477. gl.disable(gl.CULL_FACE);
  7478. }
  7479. this._isCullDirty = false;
  7480. }
  7481. // Cull face
  7482. if (this._isCullFaceDirty) {
  7483. gl.cullFace(this.cullFace);
  7484. this._isCullFaceDirty = false;
  7485. }
  7486. // Depth mask
  7487. if (this._isDepthMaskDirty) {
  7488. gl.depthMask(this.depthMask);
  7489. this._isDepthMaskDirty = false;
  7490. }
  7491. // Depth test
  7492. if (this._isDepthTestDirty) {
  7493. if (this.depthTest) {
  7494. gl.enable(gl.DEPTH_TEST);
  7495. }
  7496. else {
  7497. gl.disable(gl.DEPTH_TEST);
  7498. }
  7499. this._isDepthTestDirty = false;
  7500. }
  7501. // Depth func
  7502. if (this._isDepthFuncDirty) {
  7503. gl.depthFunc(this.depthFunc);
  7504. this._isDepthFuncDirty = false;
  7505. }
  7506. // zOffset
  7507. if (this._isZOffsetDirty) {
  7508. if (this.zOffset) {
  7509. gl.enable(gl.POLYGON_OFFSET_FILL);
  7510. gl.polygonOffset(this.zOffset, 0);
  7511. }
  7512. else {
  7513. gl.disable(gl.POLYGON_OFFSET_FILL);
  7514. }
  7515. this._isZOffsetDirty = false;
  7516. }
  7517. };
  7518. return _DepthCullingState;
  7519. }());
  7520. Internals._DepthCullingState = _DepthCullingState;
  7521. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7522. })(BABYLON || (BABYLON = {}));
  7523. //# sourceMappingURL=babylon.depthCullingState.js.map
  7524. var BABYLON;
  7525. (function (BABYLON) {
  7526. var Internals;
  7527. (function (Internals) {
  7528. var _StencilState = /** @class */ (function () {
  7529. function _StencilState() {
  7530. this._isStencilTestDirty = false;
  7531. this._isStencilMaskDirty = false;
  7532. this._isStencilFuncDirty = false;
  7533. this._isStencilOpDirty = false;
  7534. this.reset();
  7535. }
  7536. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7537. get: function () {
  7538. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7539. },
  7540. enumerable: true,
  7541. configurable: true
  7542. });
  7543. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7544. get: function () {
  7545. return this._stencilFunc;
  7546. },
  7547. set: function (value) {
  7548. if (this._stencilFunc === value) {
  7549. return;
  7550. }
  7551. this._stencilFunc = value;
  7552. this._isStencilFuncDirty = true;
  7553. },
  7554. enumerable: true,
  7555. configurable: true
  7556. });
  7557. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7558. get: function () {
  7559. return this._stencilFuncRef;
  7560. },
  7561. set: function (value) {
  7562. if (this._stencilFuncRef === value) {
  7563. return;
  7564. }
  7565. this._stencilFuncRef = value;
  7566. this._isStencilFuncDirty = true;
  7567. },
  7568. enumerable: true,
  7569. configurable: true
  7570. });
  7571. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7572. get: function () {
  7573. return this._stencilFuncMask;
  7574. },
  7575. set: function (value) {
  7576. if (this._stencilFuncMask === value) {
  7577. return;
  7578. }
  7579. this._stencilFuncMask = value;
  7580. this._isStencilFuncDirty = true;
  7581. },
  7582. enumerable: true,
  7583. configurable: true
  7584. });
  7585. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7586. get: function () {
  7587. return this._stencilOpStencilFail;
  7588. },
  7589. set: function (value) {
  7590. if (this._stencilOpStencilFail === value) {
  7591. return;
  7592. }
  7593. this._stencilOpStencilFail = value;
  7594. this._isStencilOpDirty = true;
  7595. },
  7596. enumerable: true,
  7597. configurable: true
  7598. });
  7599. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7600. get: function () {
  7601. return this._stencilOpDepthFail;
  7602. },
  7603. set: function (value) {
  7604. if (this._stencilOpDepthFail === value) {
  7605. return;
  7606. }
  7607. this._stencilOpDepthFail = value;
  7608. this._isStencilOpDirty = true;
  7609. },
  7610. enumerable: true,
  7611. configurable: true
  7612. });
  7613. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7614. get: function () {
  7615. return this._stencilOpStencilDepthPass;
  7616. },
  7617. set: function (value) {
  7618. if (this._stencilOpStencilDepthPass === value) {
  7619. return;
  7620. }
  7621. this._stencilOpStencilDepthPass = value;
  7622. this._isStencilOpDirty = true;
  7623. },
  7624. enumerable: true,
  7625. configurable: true
  7626. });
  7627. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7628. get: function () {
  7629. return this._stencilMask;
  7630. },
  7631. set: function (value) {
  7632. if (this._stencilMask === value) {
  7633. return;
  7634. }
  7635. this._stencilMask = value;
  7636. this._isStencilMaskDirty = true;
  7637. },
  7638. enumerable: true,
  7639. configurable: true
  7640. });
  7641. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7642. get: function () {
  7643. return this._stencilTest;
  7644. },
  7645. set: function (value) {
  7646. if (this._stencilTest === value) {
  7647. return;
  7648. }
  7649. this._stencilTest = value;
  7650. this._isStencilTestDirty = true;
  7651. },
  7652. enumerable: true,
  7653. configurable: true
  7654. });
  7655. _StencilState.prototype.reset = function () {
  7656. this._stencilTest = false;
  7657. this._stencilMask = 0xFF;
  7658. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7659. this._stencilFuncRef = 1;
  7660. this._stencilFuncMask = 0xFF;
  7661. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7662. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7663. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7664. this._isStencilTestDirty = true;
  7665. this._isStencilMaskDirty = true;
  7666. this._isStencilFuncDirty = true;
  7667. this._isStencilOpDirty = true;
  7668. };
  7669. _StencilState.prototype.apply = function (gl) {
  7670. if (!this.isDirty) {
  7671. return;
  7672. }
  7673. // Stencil test
  7674. if (this._isStencilTestDirty) {
  7675. if (this.stencilTest) {
  7676. gl.enable(gl.STENCIL_TEST);
  7677. }
  7678. else {
  7679. gl.disable(gl.STENCIL_TEST);
  7680. }
  7681. this._isStencilTestDirty = false;
  7682. }
  7683. // Stencil mask
  7684. if (this._isStencilMaskDirty) {
  7685. gl.stencilMask(this.stencilMask);
  7686. this._isStencilMaskDirty = false;
  7687. }
  7688. // Stencil func
  7689. if (this._isStencilFuncDirty) {
  7690. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7691. this._isStencilFuncDirty = false;
  7692. }
  7693. // Stencil op
  7694. if (this._isStencilOpDirty) {
  7695. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7696. this._isStencilOpDirty = false;
  7697. }
  7698. };
  7699. return _StencilState;
  7700. }());
  7701. Internals._StencilState = _StencilState;
  7702. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7703. })(BABYLON || (BABYLON = {}));
  7704. //# sourceMappingURL=babylon.stencilState.js.map
  7705. var BABYLON;
  7706. (function (BABYLON) {
  7707. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7708. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  7709. };
  7710. var compileRawShader = function (gl, source, type) {
  7711. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7712. gl.shaderSource(shader, source);
  7713. gl.compileShader(shader);
  7714. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7715. var log = gl.getShaderInfoLog(shader);
  7716. if (log) {
  7717. throw new Error(log);
  7718. }
  7719. }
  7720. if (!shader) {
  7721. throw new Error("Something went wrong while compile the shader.");
  7722. }
  7723. return shader;
  7724. };
  7725. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7726. var magFilter = gl.NEAREST;
  7727. var minFilter = gl.NEAREST;
  7728. switch (samplingMode) {
  7729. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7730. magFilter = gl.LINEAR;
  7731. if (generateMipMaps) {
  7732. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7733. }
  7734. else {
  7735. minFilter = gl.LINEAR;
  7736. }
  7737. break;
  7738. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7739. magFilter = gl.LINEAR;
  7740. if (generateMipMaps) {
  7741. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7742. }
  7743. else {
  7744. minFilter = gl.LINEAR;
  7745. }
  7746. break;
  7747. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7748. magFilter = gl.NEAREST;
  7749. if (generateMipMaps) {
  7750. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7751. }
  7752. else {
  7753. minFilter = gl.NEAREST;
  7754. }
  7755. break;
  7756. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7757. magFilter = gl.NEAREST;
  7758. if (generateMipMaps) {
  7759. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7760. }
  7761. else {
  7762. minFilter = gl.NEAREST;
  7763. }
  7764. break;
  7765. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7766. magFilter = gl.NEAREST;
  7767. if (generateMipMaps) {
  7768. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7769. }
  7770. else {
  7771. minFilter = gl.LINEAR;
  7772. }
  7773. break;
  7774. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7775. magFilter = gl.NEAREST;
  7776. if (generateMipMaps) {
  7777. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7778. }
  7779. else {
  7780. minFilter = gl.LINEAR;
  7781. }
  7782. break;
  7783. case BABYLON.Texture.NEAREST_LINEAR:
  7784. magFilter = gl.NEAREST;
  7785. minFilter = gl.LINEAR;
  7786. break;
  7787. case BABYLON.Texture.NEAREST_NEAREST:
  7788. magFilter = gl.NEAREST;
  7789. minFilter = gl.NEAREST;
  7790. break;
  7791. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7792. magFilter = gl.LINEAR;
  7793. if (generateMipMaps) {
  7794. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7795. }
  7796. else {
  7797. minFilter = gl.NEAREST;
  7798. }
  7799. break;
  7800. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7801. magFilter = gl.LINEAR;
  7802. if (generateMipMaps) {
  7803. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7804. }
  7805. else {
  7806. minFilter = gl.NEAREST;
  7807. }
  7808. break;
  7809. case BABYLON.Texture.LINEAR_LINEAR:
  7810. magFilter = gl.LINEAR;
  7811. minFilter = gl.LINEAR;
  7812. break;
  7813. case BABYLON.Texture.LINEAR_NEAREST:
  7814. magFilter = gl.LINEAR;
  7815. minFilter = gl.NEAREST;
  7816. break;
  7817. }
  7818. return {
  7819. min: minFilter,
  7820. mag: magFilter
  7821. };
  7822. };
  7823. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7824. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7825. var img;
  7826. var onload = function () {
  7827. loadedImages[index] = img;
  7828. loadedImages._internalCount++;
  7829. if (scene) {
  7830. scene._removePendingData(img);
  7831. }
  7832. if (loadedImages._internalCount === 6) {
  7833. onfinish(loadedImages);
  7834. }
  7835. };
  7836. var onerror = function (message, exception) {
  7837. if (scene) {
  7838. scene._removePendingData(img);
  7839. }
  7840. if (onErrorCallBack) {
  7841. onErrorCallBack(message, exception);
  7842. }
  7843. };
  7844. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  7845. if (scene) {
  7846. scene._addPendingData(img);
  7847. }
  7848. };
  7849. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  7850. if (onError === void 0) { onError = null; }
  7851. var loadedImages = [];
  7852. loadedImages._internalCount = 0;
  7853. for (var index = 0; index < 6; index++) {
  7854. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  7855. }
  7856. };
  7857. var partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  7858. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7859. var onload = function (data) {
  7860. loadedFiles[index] = data;
  7861. loadedFiles._internalCount++;
  7862. if (loadedFiles._internalCount === 6) {
  7863. onfinish(loadedFiles);
  7864. }
  7865. };
  7866. var onerror = function (request, exception) {
  7867. if (onErrorCallBack && request) {
  7868. onErrorCallBack(request.status + " " + request.statusText, exception);
  7869. }
  7870. };
  7871. BABYLON.Tools.LoadFile(url, onload, undefined, undefined, true, onerror);
  7872. };
  7873. var cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  7874. if (onError === void 0) { onError = null; }
  7875. var loadedFiles = [];
  7876. loadedFiles._internalCount = 0;
  7877. for (var index = 0; index < 6; index++) {
  7878. partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  7879. }
  7880. };
  7881. var BufferPointer = /** @class */ (function () {
  7882. function BufferPointer() {
  7883. }
  7884. return BufferPointer;
  7885. }());
  7886. var InstancingAttributeInfo = /** @class */ (function () {
  7887. function InstancingAttributeInfo() {
  7888. }
  7889. return InstancingAttributeInfo;
  7890. }());
  7891. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7892. /**
  7893. * Define options used to create a render target texture
  7894. */
  7895. var RenderTargetCreationOptions = /** @class */ (function () {
  7896. function RenderTargetCreationOptions() {
  7897. }
  7898. return RenderTargetCreationOptions;
  7899. }());
  7900. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  7901. /**
  7902. * Regroup several parameters relative to the browser in use
  7903. */
  7904. var EngineCapabilities = /** @class */ (function () {
  7905. function EngineCapabilities() {
  7906. }
  7907. return EngineCapabilities;
  7908. }());
  7909. BABYLON.EngineCapabilities = EngineCapabilities;
  7910. /**
  7911. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7912. */
  7913. var Engine = /** @class */ (function () {
  7914. /**
  7915. * @constructor
  7916. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7917. * @param {boolean} [antialias] - enable antialias
  7918. * @param options - further options to be sent to the getContext function
  7919. */
  7920. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7921. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7922. var _this = this;
  7923. // Public members
  7924. this.forcePOTTextures = false;
  7925. this.isFullscreen = false;
  7926. this.isPointerLock = false;
  7927. this.cullBackFaces = true;
  7928. this.renderEvenInBackground = true;
  7929. this.preventCacheWipeBetweenFrames = false;
  7930. // To enable/disable IDB support and avoid XHR on .manifest
  7931. this.enableOfflineSupport = false;
  7932. this.scenes = new Array();
  7933. this.postProcesses = new Array();
  7934. // Observables
  7935. /**
  7936. * Observable event triggered each time the rendering canvas is resized
  7937. */
  7938. this.onResizeObservable = new BABYLON.Observable();
  7939. /**
  7940. * Observable event triggered each time the canvas loses focus
  7941. */
  7942. this.onCanvasBlurObservable = new BABYLON.Observable();
  7943. /**
  7944. * Observable event triggered each time the canvas gains focus
  7945. */
  7946. this.onCanvasFocusObservable = new BABYLON.Observable();
  7947. /**
  7948. * Observable event triggered each time the canvas receives pointerout event
  7949. */
  7950. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  7951. /**
  7952. * Observable event triggered before each texture is initialized
  7953. */
  7954. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  7955. //WebVR
  7956. this._vrDisplay = undefined;
  7957. this._vrSupported = false;
  7958. this._vrExclusivePointerMode = false;
  7959. // Uniform buffers list
  7960. this.disableUniformBuffers = false;
  7961. this._uniformBuffers = new Array();
  7962. // Observables
  7963. /**
  7964. * Observable raised when the engine begins a new frame
  7965. */
  7966. this.onBeginFrameObservable = new BABYLON.Observable();
  7967. /**
  7968. * Observable raised when the engine ends the current frame
  7969. */
  7970. this.onEndFrameObservable = new BABYLON.Observable();
  7971. /**
  7972. * Observable raised when the engine is about to compile a shader
  7973. */
  7974. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  7975. /**
  7976. * Observable raised when the engine has jsut compiled a shader
  7977. */
  7978. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  7979. this._windowIsBackground = false;
  7980. this._webGLVersion = 1.0;
  7981. this._badOS = false;
  7982. this._badDesktopOS = false;
  7983. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  7984. this.onVRRequestPresentComplete = new BABYLON.Observable();
  7985. this.onVRRequestPresentStart = new BABYLON.Observable();
  7986. this._colorWrite = true;
  7987. this._drawCalls = new BABYLON.PerfCounter();
  7988. this._renderingQueueLaunched = false;
  7989. this._activeRenderLoops = new Array();
  7990. // Deterministic lockstepMaxSteps
  7991. this._deterministicLockstep = false;
  7992. this._lockstepMaxSteps = 4;
  7993. // Lost context
  7994. this.onContextLostObservable = new BABYLON.Observable();
  7995. this.onContextRestoredObservable = new BABYLON.Observable();
  7996. this._contextWasLost = false;
  7997. this._doNotHandleContextLost = false;
  7998. // FPS
  7999. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  8000. this._fps = 60;
  8001. this._deltaTime = 0;
  8002. /**
  8003. * Turn this value on if you want to pause FPS computation when in background
  8004. */
  8005. this.disablePerformanceMonitorInBackground = false;
  8006. // States
  8007. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  8008. this._stencilState = new BABYLON.Internals._StencilState();
  8009. this._alphaState = new BABYLON.Internals._AlphaState();
  8010. this._alphaMode = Engine.ALPHA_DISABLE;
  8011. // Cache
  8012. this._internalTexturesCache = new Array();
  8013. this._boundTexturesCache = {};
  8014. this._compiledEffects = {};
  8015. this._vertexAttribArraysEnabled = [];
  8016. this._uintIndicesCurrentlySet = false;
  8017. this._currentBoundBuffer = new Array();
  8018. this._currentBufferPointers = new Array();
  8019. this._currentInstanceLocations = new Array();
  8020. this._currentInstanceBuffers = new Array();
  8021. this._vaoRecordInProgress = false;
  8022. this._mustWipeVertexAttributes = false;
  8023. // Hardware supported Compressed Textures
  8024. this._texturesSupported = new Array();
  8025. this._onVRFullScreenTriggered = function () {
  8026. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  8027. //get the old size before we change
  8028. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  8029. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  8030. //get the width and height, change the render size
  8031. var leftEye = _this._vrDisplay.getEyeParameters('left');
  8032. _this.setHardwareScalingLevel(1);
  8033. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  8034. }
  8035. else {
  8036. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  8037. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  8038. }
  8039. };
  8040. var canvas = null;
  8041. Engine.Instances.push(this);
  8042. if (!canvasOrContext) {
  8043. return;
  8044. }
  8045. options = options || {};
  8046. if (canvasOrContext.getContext) {
  8047. canvas = canvasOrContext;
  8048. this._renderingCanvas = canvas;
  8049. if (antialias != null) {
  8050. options.antialias = antialias;
  8051. }
  8052. if (options.deterministicLockstep === undefined) {
  8053. options.deterministicLockstep = false;
  8054. }
  8055. if (options.lockstepMaxSteps === undefined) {
  8056. options.lockstepMaxSteps = 4;
  8057. }
  8058. if (options.preserveDrawingBuffer === undefined) {
  8059. options.preserveDrawingBuffer = false;
  8060. }
  8061. if (options.audioEngine === undefined) {
  8062. options.audioEngine = true;
  8063. }
  8064. if (options.stencil === undefined) {
  8065. options.stencil = true;
  8066. }
  8067. this._deterministicLockstep = options.deterministicLockstep;
  8068. this._lockstepMaxSteps = options.lockstepMaxSteps;
  8069. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  8070. // GL
  8071. if (!options.disableWebGL2Support) {
  8072. try {
  8073. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  8074. if (this._gl) {
  8075. this._webGLVersion = 2.0;
  8076. }
  8077. }
  8078. catch (e) {
  8079. // Do nothing
  8080. }
  8081. }
  8082. if (!this._gl) {
  8083. if (!canvas) {
  8084. throw new Error("The provided canvas is null or undefined.");
  8085. }
  8086. try {
  8087. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  8088. }
  8089. catch (e) {
  8090. throw new Error("WebGL not supported");
  8091. }
  8092. }
  8093. if (!this._gl) {
  8094. throw new Error("WebGL not supported");
  8095. }
  8096. this._onCanvasFocus = function () {
  8097. _this.onCanvasFocusObservable.notifyObservers(_this);
  8098. };
  8099. this._onCanvasBlur = function () {
  8100. _this.onCanvasBlurObservable.notifyObservers(_this);
  8101. };
  8102. canvas.addEventListener("focus", this._onCanvasFocus);
  8103. canvas.addEventListener("blur", this._onCanvasBlur);
  8104. this._onBlur = function () {
  8105. if (_this.disablePerformanceMonitorInBackground) {
  8106. _this._performanceMonitor.disable();
  8107. }
  8108. _this._windowIsBackground = true;
  8109. };
  8110. this._onFocus = function () {
  8111. if (_this.disablePerformanceMonitorInBackground) {
  8112. _this._performanceMonitor.enable();
  8113. }
  8114. _this._windowIsBackground = false;
  8115. };
  8116. this._onCanvasPointerOut = function () {
  8117. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  8118. };
  8119. window.addEventListener("blur", this._onBlur);
  8120. window.addEventListener("focus", this._onFocus);
  8121. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  8122. // Context lost
  8123. if (!this._doNotHandleContextLost) {
  8124. this._onContextLost = function (evt) {
  8125. evt.preventDefault();
  8126. _this._contextWasLost = true;
  8127. BABYLON.Tools.Warn("WebGL context lost.");
  8128. _this.onContextLostObservable.notifyObservers(_this);
  8129. };
  8130. this._onContextRestored = function (evt) {
  8131. // Adding a timeout to avoid race condition at browser level
  8132. setTimeout(function () {
  8133. // Rebuild gl context
  8134. _this._initGLContext();
  8135. // Rebuild effects
  8136. _this._rebuildEffects();
  8137. // Rebuild textures
  8138. _this._rebuildInternalTextures();
  8139. // Rebuild buffers
  8140. _this._rebuildBuffers();
  8141. // Cache
  8142. _this.wipeCaches(true);
  8143. BABYLON.Tools.Warn("WebGL context successfully restored.");
  8144. _this.onContextRestoredObservable.notifyObservers(_this);
  8145. _this._contextWasLost = false;
  8146. }, 0);
  8147. };
  8148. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  8149. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  8150. }
  8151. }
  8152. else {
  8153. this._gl = canvasOrContext;
  8154. this._renderingCanvas = this._gl.canvas;
  8155. if (this._gl.renderbufferStorageMultisample) {
  8156. this._webGLVersion = 2.0;
  8157. }
  8158. options.stencil = this._gl.getContextAttributes().stencil;
  8159. }
  8160. // Viewport
  8161. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  8162. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  8163. this.resize();
  8164. this._isStencilEnable = options.stencil ? true : false;
  8165. this._initGLContext();
  8166. if (canvas) {
  8167. // Fullscreen
  8168. this._onFullscreenChange = function () {
  8169. if (document.fullscreen !== undefined) {
  8170. _this.isFullscreen = document.fullscreen;
  8171. }
  8172. else if (document.mozFullScreen !== undefined) {
  8173. _this.isFullscreen = document.mozFullScreen;
  8174. }
  8175. else if (document.webkitIsFullScreen !== undefined) {
  8176. _this.isFullscreen = document.webkitIsFullScreen;
  8177. }
  8178. else if (document.msIsFullScreen !== undefined) {
  8179. _this.isFullscreen = document.msIsFullScreen;
  8180. }
  8181. // Pointer lock
  8182. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  8183. canvas.requestPointerLock = canvas.requestPointerLock ||
  8184. canvas.msRequestPointerLock ||
  8185. canvas.mozRequestPointerLock ||
  8186. canvas.webkitRequestPointerLock;
  8187. if (canvas.requestPointerLock) {
  8188. canvas.requestPointerLock();
  8189. }
  8190. }
  8191. };
  8192. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  8193. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  8194. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  8195. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  8196. // Pointer lock
  8197. this._onPointerLockChange = function () {
  8198. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  8199. document.webkitPointerLockElement === canvas ||
  8200. document.msPointerLockElement === canvas ||
  8201. document.pointerLockElement === canvas);
  8202. };
  8203. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  8204. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  8205. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  8206. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  8207. this._onVRDisplayPointerRestricted = function () {
  8208. if (canvas) {
  8209. canvas.requestPointerLock();
  8210. }
  8211. };
  8212. this._onVRDisplayPointerUnrestricted = function () {
  8213. document.exitPointerLock();
  8214. };
  8215. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  8216. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  8217. }
  8218. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  8219. Engine.audioEngine = new BABYLON.AudioEngine();
  8220. }
  8221. // Prepare buffer pointers
  8222. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  8223. this._currentBufferPointers[i] = new BufferPointer();
  8224. }
  8225. // Load WebVR Devices
  8226. if (options.autoEnableWebVR) {
  8227. this.initWebVR();
  8228. }
  8229. // Detect if we are running on a faulty buggy OS.
  8230. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  8231. // Detect if we are running on a faulty buggy desktop OS.
  8232. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  8233. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  8234. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  8235. }
  8236. Object.defineProperty(Engine, "LastCreatedEngine", {
  8237. get: function () {
  8238. if (Engine.Instances.length === 0) {
  8239. return null;
  8240. }
  8241. return Engine.Instances[Engine.Instances.length - 1];
  8242. },
  8243. enumerable: true,
  8244. configurable: true
  8245. });
  8246. Object.defineProperty(Engine, "LastCreatedScene", {
  8247. get: function () {
  8248. var lastCreatedEngine = Engine.LastCreatedEngine;
  8249. if (!lastCreatedEngine) {
  8250. return null;
  8251. }
  8252. if (lastCreatedEngine.scenes.length === 0) {
  8253. return null;
  8254. }
  8255. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  8256. },
  8257. enumerable: true,
  8258. configurable: true
  8259. });
  8260. /**
  8261. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  8262. */
  8263. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  8264. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  8265. var engine = Engine.Instances[engineIndex];
  8266. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  8267. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  8268. }
  8269. }
  8270. };
  8271. Object.defineProperty(Engine, "NEVER", {
  8272. get: function () {
  8273. return Engine._NEVER;
  8274. },
  8275. enumerable: true,
  8276. configurable: true
  8277. });
  8278. Object.defineProperty(Engine, "ALWAYS", {
  8279. get: function () {
  8280. return Engine._ALWAYS;
  8281. },
  8282. enumerable: true,
  8283. configurable: true
  8284. });
  8285. Object.defineProperty(Engine, "LESS", {
  8286. get: function () {
  8287. return Engine._LESS;
  8288. },
  8289. enumerable: true,
  8290. configurable: true
  8291. });
  8292. Object.defineProperty(Engine, "EQUAL", {
  8293. get: function () {
  8294. return Engine._EQUAL;
  8295. },
  8296. enumerable: true,
  8297. configurable: true
  8298. });
  8299. Object.defineProperty(Engine, "LEQUAL", {
  8300. get: function () {
  8301. return Engine._LEQUAL;
  8302. },
  8303. enumerable: true,
  8304. configurable: true
  8305. });
  8306. Object.defineProperty(Engine, "GREATER", {
  8307. get: function () {
  8308. return Engine._GREATER;
  8309. },
  8310. enumerable: true,
  8311. configurable: true
  8312. });
  8313. Object.defineProperty(Engine, "GEQUAL", {
  8314. get: function () {
  8315. return Engine._GEQUAL;
  8316. },
  8317. enumerable: true,
  8318. configurable: true
  8319. });
  8320. Object.defineProperty(Engine, "NOTEQUAL", {
  8321. get: function () {
  8322. return Engine._NOTEQUAL;
  8323. },
  8324. enumerable: true,
  8325. configurable: true
  8326. });
  8327. Object.defineProperty(Engine, "KEEP", {
  8328. get: function () {
  8329. return Engine._KEEP;
  8330. },
  8331. enumerable: true,
  8332. configurable: true
  8333. });
  8334. Object.defineProperty(Engine, "REPLACE", {
  8335. get: function () {
  8336. return Engine._REPLACE;
  8337. },
  8338. enumerable: true,
  8339. configurable: true
  8340. });
  8341. Object.defineProperty(Engine, "INCR", {
  8342. get: function () {
  8343. return Engine._INCR;
  8344. },
  8345. enumerable: true,
  8346. configurable: true
  8347. });
  8348. Object.defineProperty(Engine, "DECR", {
  8349. get: function () {
  8350. return Engine._DECR;
  8351. },
  8352. enumerable: true,
  8353. configurable: true
  8354. });
  8355. Object.defineProperty(Engine, "INVERT", {
  8356. get: function () {
  8357. return Engine._INVERT;
  8358. },
  8359. enumerable: true,
  8360. configurable: true
  8361. });
  8362. Object.defineProperty(Engine, "INCR_WRAP", {
  8363. get: function () {
  8364. return Engine._INCR_WRAP;
  8365. },
  8366. enumerable: true,
  8367. configurable: true
  8368. });
  8369. Object.defineProperty(Engine, "DECR_WRAP", {
  8370. get: function () {
  8371. return Engine._DECR_WRAP;
  8372. },
  8373. enumerable: true,
  8374. configurable: true
  8375. });
  8376. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8377. get: function () {
  8378. return Engine._ALPHA_DISABLE;
  8379. },
  8380. enumerable: true,
  8381. configurable: true
  8382. });
  8383. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8384. get: function () {
  8385. return Engine._ALPHA_ONEONE;
  8386. },
  8387. enumerable: true,
  8388. configurable: true
  8389. });
  8390. Object.defineProperty(Engine, "ALPHA_ADD", {
  8391. get: function () {
  8392. return Engine._ALPHA_ADD;
  8393. },
  8394. enumerable: true,
  8395. configurable: true
  8396. });
  8397. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8398. get: function () {
  8399. return Engine._ALPHA_COMBINE;
  8400. },
  8401. enumerable: true,
  8402. configurable: true
  8403. });
  8404. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8405. get: function () {
  8406. return Engine._ALPHA_SUBTRACT;
  8407. },
  8408. enumerable: true,
  8409. configurable: true
  8410. });
  8411. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8412. get: function () {
  8413. return Engine._ALPHA_MULTIPLY;
  8414. },
  8415. enumerable: true,
  8416. configurable: true
  8417. });
  8418. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8419. get: function () {
  8420. return Engine._ALPHA_MAXIMIZED;
  8421. },
  8422. enumerable: true,
  8423. configurable: true
  8424. });
  8425. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8426. get: function () {
  8427. return Engine._ALPHA_PREMULTIPLIED;
  8428. },
  8429. enumerable: true,
  8430. configurable: true
  8431. });
  8432. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  8433. get: function () {
  8434. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  8435. },
  8436. enumerable: true,
  8437. configurable: true
  8438. });
  8439. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  8440. get: function () {
  8441. return Engine._ALPHA_INTERPOLATE;
  8442. },
  8443. enumerable: true,
  8444. configurable: true
  8445. });
  8446. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  8447. get: function () {
  8448. return Engine._ALPHA_SCREENMODE;
  8449. },
  8450. enumerable: true,
  8451. configurable: true
  8452. });
  8453. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8454. get: function () {
  8455. return Engine._DELAYLOADSTATE_NONE;
  8456. },
  8457. enumerable: true,
  8458. configurable: true
  8459. });
  8460. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8461. get: function () {
  8462. return Engine._DELAYLOADSTATE_LOADED;
  8463. },
  8464. enumerable: true,
  8465. configurable: true
  8466. });
  8467. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8468. get: function () {
  8469. return Engine._DELAYLOADSTATE_LOADING;
  8470. },
  8471. enumerable: true,
  8472. configurable: true
  8473. });
  8474. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8475. get: function () {
  8476. return Engine._DELAYLOADSTATE_NOTLOADED;
  8477. },
  8478. enumerable: true,
  8479. configurable: true
  8480. });
  8481. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8482. get: function () {
  8483. return Engine._TEXTUREFORMAT_ALPHA;
  8484. },
  8485. enumerable: true,
  8486. configurable: true
  8487. });
  8488. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8489. get: function () {
  8490. return Engine._TEXTUREFORMAT_LUMINANCE;
  8491. },
  8492. enumerable: true,
  8493. configurable: true
  8494. });
  8495. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8496. get: function () {
  8497. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8498. },
  8499. enumerable: true,
  8500. configurable: true
  8501. });
  8502. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8503. get: function () {
  8504. return Engine._TEXTUREFORMAT_RGB;
  8505. },
  8506. enumerable: true,
  8507. configurable: true
  8508. });
  8509. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8510. get: function () {
  8511. return Engine._TEXTUREFORMAT_RGBA;
  8512. },
  8513. enumerable: true,
  8514. configurable: true
  8515. });
  8516. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8517. get: function () {
  8518. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8519. },
  8520. enumerable: true,
  8521. configurable: true
  8522. });
  8523. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8524. get: function () {
  8525. return Engine._TEXTURETYPE_FLOAT;
  8526. },
  8527. enumerable: true,
  8528. configurable: true
  8529. });
  8530. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8531. get: function () {
  8532. return Engine._TEXTURETYPE_HALF_FLOAT;
  8533. },
  8534. enumerable: true,
  8535. configurable: true
  8536. });
  8537. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  8538. get: function () {
  8539. return Engine._SCALEMODE_FLOOR;
  8540. },
  8541. enumerable: true,
  8542. configurable: true
  8543. });
  8544. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  8545. get: function () {
  8546. return Engine._SCALEMODE_NEAREST;
  8547. },
  8548. enumerable: true,
  8549. configurable: true
  8550. });
  8551. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8552. get: function () {
  8553. return Engine._SCALEMODE_CEILING;
  8554. },
  8555. enumerable: true,
  8556. configurable: true
  8557. });
  8558. Object.defineProperty(Engine, "Version", {
  8559. get: function () {
  8560. return "3.1-beta-6";
  8561. },
  8562. enumerable: true,
  8563. configurable: true
  8564. });
  8565. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  8566. get: function () {
  8567. return this._vrExclusivePointerMode;
  8568. },
  8569. enumerable: true,
  8570. configurable: true
  8571. });
  8572. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  8573. get: function () {
  8574. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  8575. },
  8576. enumerable: true,
  8577. configurable: true
  8578. });
  8579. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8580. get: function () {
  8581. return this._webGLVersion < 2 || this.forcePOTTextures;
  8582. },
  8583. enumerable: true,
  8584. configurable: true
  8585. });
  8586. Object.defineProperty(Engine.prototype, "badOS", {
  8587. get: function () {
  8588. return this._badOS;
  8589. },
  8590. enumerable: true,
  8591. configurable: true
  8592. });
  8593. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8594. get: function () {
  8595. return this._badDesktopOS;
  8596. },
  8597. enumerable: true,
  8598. configurable: true
  8599. });
  8600. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8601. get: function () {
  8602. return this._performanceMonitor;
  8603. },
  8604. enumerable: true,
  8605. configurable: true
  8606. });
  8607. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8608. get: function () {
  8609. return this._texturesSupported;
  8610. },
  8611. enumerable: true,
  8612. configurable: true
  8613. });
  8614. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8615. get: function () {
  8616. return this._textureFormatInUse;
  8617. },
  8618. enumerable: true,
  8619. configurable: true
  8620. });
  8621. Object.defineProperty(Engine.prototype, "currentViewport", {
  8622. get: function () {
  8623. return this._cachedViewport;
  8624. },
  8625. enumerable: true,
  8626. configurable: true
  8627. });
  8628. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8629. // Empty texture
  8630. get: function () {
  8631. if (!this._emptyTexture) {
  8632. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8633. }
  8634. return this._emptyTexture;
  8635. },
  8636. enumerable: true,
  8637. configurable: true
  8638. });
  8639. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  8640. get: function () {
  8641. if (!this._emptyTexture3D) {
  8642. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8643. }
  8644. return this._emptyTexture3D;
  8645. },
  8646. enumerable: true,
  8647. configurable: true
  8648. });
  8649. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8650. get: function () {
  8651. if (!this._emptyCubeTexture) {
  8652. var faceData = new Uint8Array(4);
  8653. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8654. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8655. }
  8656. return this._emptyCubeTexture;
  8657. },
  8658. enumerable: true,
  8659. configurable: true
  8660. });
  8661. Engine.prototype._rebuildInternalTextures = function () {
  8662. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8663. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8664. var internalTexture = currentState_1[_i];
  8665. internalTexture._rebuild();
  8666. }
  8667. };
  8668. Engine.prototype._rebuildEffects = function () {
  8669. for (var key in this._compiledEffects) {
  8670. var effect = this._compiledEffects[key];
  8671. effect._prepareEffect();
  8672. }
  8673. BABYLON.Effect.ResetCache();
  8674. };
  8675. Engine.prototype._rebuildBuffers = function () {
  8676. // Index / Vertex
  8677. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8678. var scene = _a[_i];
  8679. scene.resetCachedMaterial();
  8680. scene._rebuildGeometries();
  8681. scene._rebuildTextures();
  8682. }
  8683. // Uniforms
  8684. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8685. var uniformBuffer = _c[_b];
  8686. uniformBuffer._rebuild();
  8687. }
  8688. };
  8689. Engine.prototype._initGLContext = function () {
  8690. // Caps
  8691. this._caps = new EngineCapabilities();
  8692. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8693. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8694. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8695. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8696. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8697. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8698. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8699. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8700. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8701. // Infos
  8702. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8703. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8704. if (rendererInfo != null) {
  8705. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8706. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8707. }
  8708. if (!this._glVendor) {
  8709. this._glVendor = "Unknown vendor";
  8710. }
  8711. if (!this._glRenderer) {
  8712. this._glRenderer = "Unknown renderer";
  8713. }
  8714. // Constants
  8715. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8716. if (this._gl.RGBA16F !== 0x881A) {
  8717. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8718. }
  8719. if (this._gl.RGBA32F !== 0x8814) {
  8720. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8721. }
  8722. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  8723. this._gl.DEPTH24_STENCIL8 = 35056;
  8724. }
  8725. // Extensions
  8726. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8727. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8728. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8729. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8730. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8731. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8732. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8733. 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');
  8734. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8735. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8736. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8737. this._caps.highPrecisionShaderSupported = true;
  8738. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  8739. if (this._caps.timerQuery) {
  8740. if (this._webGLVersion === 1) {
  8741. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  8742. }
  8743. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  8744. }
  8745. // Checks if some of the format renders first to allow the use of webgl inspector.
  8746. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8747. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8748. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8749. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8750. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8751. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8752. if (this._webGLVersion > 1) {
  8753. this._gl.HALF_FLOAT_OES = 0x140B;
  8754. }
  8755. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8756. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8757. // Draw buffers
  8758. if (this._webGLVersion > 1) {
  8759. this._caps.drawBuffersExtension = true;
  8760. }
  8761. else {
  8762. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  8763. if (drawBuffersExtension !== null) {
  8764. this._caps.drawBuffersExtension = true;
  8765. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  8766. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  8767. for (var i = 0; i < 16; i++) {
  8768. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  8769. }
  8770. }
  8771. else {
  8772. this._caps.drawBuffersExtension = false;
  8773. }
  8774. }
  8775. // Depth Texture
  8776. if (this._webGLVersion > 1) {
  8777. this._caps.depthTextureExtension = true;
  8778. }
  8779. else {
  8780. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  8781. if (depthTextureExtension != null) {
  8782. this._caps.depthTextureExtension = true;
  8783. }
  8784. }
  8785. // Vertex array object
  8786. if (this._webGLVersion > 1) {
  8787. this._caps.vertexArrayObject = true;
  8788. }
  8789. else {
  8790. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8791. if (vertexArrayObjectExtension != null) {
  8792. this._caps.vertexArrayObject = true;
  8793. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8794. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8795. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8796. }
  8797. else {
  8798. this._caps.vertexArrayObject = false;
  8799. }
  8800. }
  8801. // Instances count
  8802. if (this._webGLVersion > 1) {
  8803. this._caps.instancedArrays = true;
  8804. }
  8805. else {
  8806. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8807. if (instanceExtension != null) {
  8808. this._caps.instancedArrays = true;
  8809. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8810. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8811. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8812. }
  8813. else {
  8814. this._caps.instancedArrays = false;
  8815. }
  8816. }
  8817. // Intelligently add supported compressed formats in order to check for.
  8818. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8819. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8820. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8821. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8822. if (this._caps.astc)
  8823. this.texturesSupported.push('-astc.ktx');
  8824. if (this._caps.s3tc)
  8825. this.texturesSupported.push('-dxt.ktx');
  8826. if (this._caps.pvrtc)
  8827. this.texturesSupported.push('-pvrtc.ktx');
  8828. if (this._caps.etc2)
  8829. this.texturesSupported.push('-etc2.ktx');
  8830. if (this._caps.etc1)
  8831. this.texturesSupported.push('-etc1.ktx');
  8832. if (this._gl.getShaderPrecisionFormat) {
  8833. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8834. if (highp) {
  8835. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8836. }
  8837. }
  8838. // Depth buffer
  8839. this.setDepthBuffer(true);
  8840. this.setDepthFunctionToLessOrEqual();
  8841. this.setDepthWrite(true);
  8842. };
  8843. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8844. get: function () {
  8845. return this._webGLVersion;
  8846. },
  8847. enumerable: true,
  8848. configurable: true
  8849. });
  8850. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8851. /**
  8852. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8853. */
  8854. get: function () {
  8855. return this._isStencilEnable;
  8856. },
  8857. enumerable: true,
  8858. configurable: true
  8859. });
  8860. Engine.prototype._prepareWorkingCanvas = function () {
  8861. if (this._workingCanvas) {
  8862. return;
  8863. }
  8864. this._workingCanvas = document.createElement("canvas");
  8865. var context = this._workingCanvas.getContext("2d");
  8866. if (context) {
  8867. this._workingContext = context;
  8868. }
  8869. };
  8870. Engine.prototype.resetTextureCache = function () {
  8871. for (var key in this._boundTexturesCache) {
  8872. this._boundTexturesCache[key] = null;
  8873. }
  8874. };
  8875. Engine.prototype.isDeterministicLockStep = function () {
  8876. return this._deterministicLockstep;
  8877. };
  8878. Engine.prototype.getLockstepMaxSteps = function () {
  8879. return this._lockstepMaxSteps;
  8880. };
  8881. Engine.prototype.getGlInfo = function () {
  8882. return {
  8883. vendor: this._glVendor,
  8884. renderer: this._glRenderer,
  8885. version: this._glVersion
  8886. };
  8887. };
  8888. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8889. if (useScreen === void 0) { useScreen = false; }
  8890. var viewport = camera.viewport;
  8891. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8892. };
  8893. Engine.prototype.getRenderWidth = function (useScreen) {
  8894. if (useScreen === void 0) { useScreen = false; }
  8895. if (!useScreen && this._currentRenderTarget) {
  8896. return this._currentRenderTarget.width;
  8897. }
  8898. return this._gl.drawingBufferWidth;
  8899. };
  8900. Engine.prototype.getRenderHeight = function (useScreen) {
  8901. if (useScreen === void 0) { useScreen = false; }
  8902. if (!useScreen && this._currentRenderTarget) {
  8903. return this._currentRenderTarget.height;
  8904. }
  8905. return this._gl.drawingBufferHeight;
  8906. };
  8907. Engine.prototype.getRenderingCanvas = function () {
  8908. return this._renderingCanvas;
  8909. };
  8910. Engine.prototype.getRenderingCanvasClientRect = function () {
  8911. if (!this._renderingCanvas) {
  8912. return null;
  8913. }
  8914. return this._renderingCanvas.getBoundingClientRect();
  8915. };
  8916. Engine.prototype.setHardwareScalingLevel = function (level) {
  8917. this._hardwareScalingLevel = level;
  8918. this.resize();
  8919. };
  8920. Engine.prototype.getHardwareScalingLevel = function () {
  8921. return this._hardwareScalingLevel;
  8922. };
  8923. Engine.prototype.getLoadedTexturesCache = function () {
  8924. return this._internalTexturesCache;
  8925. };
  8926. Engine.prototype.getCaps = function () {
  8927. return this._caps;
  8928. };
  8929. Object.defineProperty(Engine.prototype, "drawCalls", {
  8930. /** The number of draw calls submitted last frame */
  8931. get: function () {
  8932. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  8933. return 0;
  8934. },
  8935. enumerable: true,
  8936. configurable: true
  8937. });
  8938. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8939. get: function () {
  8940. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  8941. return null;
  8942. },
  8943. enumerable: true,
  8944. configurable: true
  8945. });
  8946. Engine.prototype.getDepthFunction = function () {
  8947. return this._depthCullingState.depthFunc;
  8948. };
  8949. Engine.prototype.setDepthFunction = function (depthFunc) {
  8950. this._depthCullingState.depthFunc = depthFunc;
  8951. };
  8952. Engine.prototype.setDepthFunctionToGreater = function () {
  8953. this._depthCullingState.depthFunc = this._gl.GREATER;
  8954. };
  8955. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8956. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8957. };
  8958. Engine.prototype.setDepthFunctionToLess = function () {
  8959. this._depthCullingState.depthFunc = this._gl.LESS;
  8960. };
  8961. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8962. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8963. };
  8964. Engine.prototype.getStencilBuffer = function () {
  8965. return this._stencilState.stencilTest;
  8966. };
  8967. Engine.prototype.setStencilBuffer = function (enable) {
  8968. this._stencilState.stencilTest = enable;
  8969. };
  8970. Engine.prototype.getStencilMask = function () {
  8971. return this._stencilState.stencilMask;
  8972. };
  8973. Engine.prototype.setStencilMask = function (mask) {
  8974. this._stencilState.stencilMask = mask;
  8975. };
  8976. Engine.prototype.getStencilFunction = function () {
  8977. return this._stencilState.stencilFunc;
  8978. };
  8979. Engine.prototype.getStencilFunctionReference = function () {
  8980. return this._stencilState.stencilFuncRef;
  8981. };
  8982. Engine.prototype.getStencilFunctionMask = function () {
  8983. return this._stencilState.stencilFuncMask;
  8984. };
  8985. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8986. this._stencilState.stencilFunc = stencilFunc;
  8987. };
  8988. Engine.prototype.setStencilFunctionReference = function (reference) {
  8989. this._stencilState.stencilFuncRef = reference;
  8990. };
  8991. Engine.prototype.setStencilFunctionMask = function (mask) {
  8992. this._stencilState.stencilFuncMask = mask;
  8993. };
  8994. Engine.prototype.getStencilOperationFail = function () {
  8995. return this._stencilState.stencilOpStencilFail;
  8996. };
  8997. Engine.prototype.getStencilOperationDepthFail = function () {
  8998. return this._stencilState.stencilOpDepthFail;
  8999. };
  9000. Engine.prototype.getStencilOperationPass = function () {
  9001. return this._stencilState.stencilOpStencilDepthPass;
  9002. };
  9003. Engine.prototype.setStencilOperationFail = function (operation) {
  9004. this._stencilState.stencilOpStencilFail = operation;
  9005. };
  9006. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  9007. this._stencilState.stencilOpDepthFail = operation;
  9008. };
  9009. Engine.prototype.setStencilOperationPass = function (operation) {
  9010. this._stencilState.stencilOpStencilDepthPass = operation;
  9011. };
  9012. Engine.prototype.setDitheringState = function (value) {
  9013. if (value) {
  9014. this._gl.enable(this._gl.DITHER);
  9015. }
  9016. else {
  9017. this._gl.disable(this._gl.DITHER);
  9018. }
  9019. };
  9020. Engine.prototype.setRasterizerState = function (value) {
  9021. if (value) {
  9022. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  9023. }
  9024. else {
  9025. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  9026. }
  9027. };
  9028. /**
  9029. * stop executing a render loop function and remove it from the execution array
  9030. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  9031. */
  9032. Engine.prototype.stopRenderLoop = function (renderFunction) {
  9033. if (!renderFunction) {
  9034. this._activeRenderLoops = [];
  9035. return;
  9036. }
  9037. var index = this._activeRenderLoops.indexOf(renderFunction);
  9038. if (index >= 0) {
  9039. this._activeRenderLoops.splice(index, 1);
  9040. }
  9041. };
  9042. Engine.prototype._renderLoop = function () {
  9043. if (!this._contextWasLost) {
  9044. var shouldRender = true;
  9045. if (!this.renderEvenInBackground && this._windowIsBackground) {
  9046. shouldRender = false;
  9047. }
  9048. if (shouldRender) {
  9049. // Start new frame
  9050. this.beginFrame();
  9051. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  9052. var renderFunction = this._activeRenderLoops[index];
  9053. renderFunction();
  9054. }
  9055. // Present
  9056. this.endFrame();
  9057. }
  9058. }
  9059. if (this._activeRenderLoops.length > 0) {
  9060. // Register new frame
  9061. var requester = null;
  9062. if (this._vrDisplay && this._vrDisplay.isPresenting)
  9063. requester = this._vrDisplay;
  9064. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  9065. }
  9066. else {
  9067. this._renderingQueueLaunched = false;
  9068. }
  9069. };
  9070. /**
  9071. * Register and execute a render loop. The engine can have more than one render function.
  9072. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  9073. * @example
  9074. * engine.runRenderLoop(function () {
  9075. * scene.render()
  9076. * })
  9077. */
  9078. Engine.prototype.runRenderLoop = function (renderFunction) {
  9079. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  9080. return;
  9081. }
  9082. this._activeRenderLoops.push(renderFunction);
  9083. if (!this._renderingQueueLaunched) {
  9084. this._renderingQueueLaunched = true;
  9085. this._bindedRenderFunction = this._renderLoop.bind(this);
  9086. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  9087. }
  9088. };
  9089. /**
  9090. * Toggle full screen mode.
  9091. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  9092. * @param {any} options - an options object to be sent to the requestFullscreen function
  9093. */
  9094. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  9095. if (this.isFullscreen) {
  9096. BABYLON.Tools.ExitFullscreen();
  9097. }
  9098. else {
  9099. this._pointerLockRequested = requestPointerLock;
  9100. if (this._renderingCanvas) {
  9101. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  9102. }
  9103. }
  9104. };
  9105. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  9106. if (stencil === void 0) { stencil = false; }
  9107. this.applyStates();
  9108. var mode = 0;
  9109. if (backBuffer && color) {
  9110. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  9111. mode |= this._gl.COLOR_BUFFER_BIT;
  9112. }
  9113. if (depth) {
  9114. this._gl.clearDepth(1.0);
  9115. mode |= this._gl.DEPTH_BUFFER_BIT;
  9116. }
  9117. if (stencil) {
  9118. this._gl.clearStencil(0);
  9119. mode |= this._gl.STENCIL_BUFFER_BIT;
  9120. }
  9121. this._gl.clear(mode);
  9122. };
  9123. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  9124. var gl = this._gl;
  9125. // Save state
  9126. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  9127. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  9128. // Change state
  9129. gl.enable(gl.SCISSOR_TEST);
  9130. gl.scissor(x, y, width, height);
  9131. // Clear
  9132. this.clear(clearColor, true, true, true);
  9133. // Restore state
  9134. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  9135. if (curScissor === true) {
  9136. gl.enable(gl.SCISSOR_TEST);
  9137. }
  9138. else {
  9139. gl.disable(gl.SCISSOR_TEST);
  9140. }
  9141. };
  9142. /**
  9143. * Set the WebGL's viewport
  9144. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  9145. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  9146. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  9147. */
  9148. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  9149. var width = requiredWidth || this.getRenderWidth();
  9150. var height = requiredHeight || this.getRenderHeight();
  9151. var x = viewport.x || 0;
  9152. var y = viewport.y || 0;
  9153. this._cachedViewport = viewport;
  9154. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  9155. };
  9156. /**
  9157. * Directly set the WebGL Viewport
  9158. * The x, y, width & height are directly passed to the WebGL call
  9159. * @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.
  9160. */
  9161. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  9162. var currentViewport = this._cachedViewport;
  9163. this._cachedViewport = null;
  9164. this._gl.viewport(x, y, width, height);
  9165. return currentViewport;
  9166. };
  9167. Engine.prototype.beginFrame = function () {
  9168. this.onBeginFrameObservable.notifyObservers(this);
  9169. this._measureFps();
  9170. };
  9171. Engine.prototype.endFrame = function () {
  9172. //force a flush in case we are using a bad OS.
  9173. if (this._badOS) {
  9174. this.flushFramebuffer();
  9175. }
  9176. //submit frame to the vr device, if enabled
  9177. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9178. // TODO: We should only submit the frame if we read frameData successfully.
  9179. this._vrDisplay.submitFrame();
  9180. }
  9181. this.onEndFrameObservable.notifyObservers(this);
  9182. };
  9183. /**
  9184. * resize the view according to the canvas' size.
  9185. * @example
  9186. * window.addEventListener("resize", function () {
  9187. * engine.resize();
  9188. * });
  9189. */
  9190. Engine.prototype.resize = function () {
  9191. // We're not resizing the size of the canvas while in VR mode & presenting
  9192. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  9193. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  9194. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  9195. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  9196. }
  9197. };
  9198. /**
  9199. * force a specific size of the canvas
  9200. * @param {number} width - the new canvas' width
  9201. * @param {number} height - the new canvas' height
  9202. */
  9203. Engine.prototype.setSize = function (width, height) {
  9204. if (!this._renderingCanvas) {
  9205. return;
  9206. }
  9207. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  9208. return;
  9209. }
  9210. this._renderingCanvas.width = width;
  9211. this._renderingCanvas.height = height;
  9212. for (var index = 0; index < this.scenes.length; index++) {
  9213. var scene = this.scenes[index];
  9214. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  9215. var cam = scene.cameras[camIndex];
  9216. cam._currentRenderId = 0;
  9217. }
  9218. }
  9219. if (this.onResizeObservable.hasObservers) {
  9220. this.onResizeObservable.notifyObservers(this);
  9221. }
  9222. };
  9223. // WebVR functions
  9224. Engine.prototype.isVRDevicePresent = function () {
  9225. return !!this._vrDisplay;
  9226. };
  9227. Engine.prototype.getVRDevice = function () {
  9228. return this._vrDisplay;
  9229. };
  9230. Engine.prototype.initWebVR = function () {
  9231. var _this = this;
  9232. var notifyObservers = function () {
  9233. var eventArgs = {
  9234. vrDisplay: _this._vrDisplay,
  9235. vrSupported: _this._vrSupported
  9236. };
  9237. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  9238. };
  9239. if (!this._onVrDisplayConnect) {
  9240. this._onVrDisplayConnect = function (event) {
  9241. _this._vrDisplay = event.display;
  9242. notifyObservers();
  9243. };
  9244. this._onVrDisplayDisconnect = function () {
  9245. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  9246. _this._vrDisplay = undefined;
  9247. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  9248. notifyObservers();
  9249. };
  9250. this._onVrDisplayPresentChange = function () {
  9251. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  9252. };
  9253. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  9254. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  9255. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  9256. }
  9257. this._getVRDisplays(notifyObservers);
  9258. return this.onVRDisplayChangedObservable;
  9259. };
  9260. Engine.prototype.enableVR = function () {
  9261. var _this = this;
  9262. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  9263. var onResolved = function () {
  9264. _this.onVRRequestPresentComplete.notifyObservers(true);
  9265. _this._onVRFullScreenTriggered();
  9266. };
  9267. var onRejected = function () {
  9268. _this.onVRRequestPresentComplete.notifyObservers(false);
  9269. };
  9270. this.onVRRequestPresentStart.notifyObservers(this);
  9271. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  9272. }
  9273. };
  9274. Engine.prototype.disableVR = function () {
  9275. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9276. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  9277. }
  9278. };
  9279. Engine.prototype._getVRDisplays = function (callback) {
  9280. var _this = this;
  9281. var getWebVRDevices = function (devices) {
  9282. _this._vrSupported = true;
  9283. // note that devices may actually be an empty array. This is fine;
  9284. // we expect this._vrDisplay to be undefined in this case.
  9285. return _this._vrDisplay = devices[0];
  9286. };
  9287. if (navigator.getVRDisplays) {
  9288. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  9289. // TODO: System CANNOT support WebVR, despite API presence.
  9290. _this._vrSupported = false;
  9291. callback();
  9292. });
  9293. }
  9294. else {
  9295. // TODO: Browser does not support WebVR
  9296. this._vrDisplay = undefined;
  9297. this._vrSupported = false;
  9298. callback();
  9299. }
  9300. };
  9301. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  9302. if (this._currentRenderTarget) {
  9303. this.unBindFramebuffer(this._currentRenderTarget);
  9304. }
  9305. this._currentRenderTarget = texture;
  9306. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  9307. var gl = this._gl;
  9308. if (texture.isCube) {
  9309. if (faceIndex === undefined) {
  9310. faceIndex = 0;
  9311. }
  9312. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  9313. }
  9314. if (this._cachedViewport && !forceFullscreenViewport) {
  9315. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  9316. }
  9317. else {
  9318. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  9319. }
  9320. this.wipeCaches();
  9321. };
  9322. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  9323. if (this._currentFramebuffer !== framebuffer) {
  9324. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  9325. this._currentFramebuffer = framebuffer;
  9326. }
  9327. };
  9328. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  9329. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  9330. this._currentRenderTarget = null;
  9331. // If MSAA, we need to bitblt back to main texture
  9332. var gl = this._gl;
  9333. if (texture._MSAAFramebuffer) {
  9334. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  9335. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  9336. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  9337. }
  9338. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  9339. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9340. gl.generateMipmap(gl.TEXTURE_2D);
  9341. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9342. }
  9343. if (onBeforeUnbind) {
  9344. if (texture._MSAAFramebuffer) {
  9345. // Bind the correct framebuffer
  9346. this.bindUnboundFramebuffer(texture._framebuffer);
  9347. }
  9348. onBeforeUnbind();
  9349. }
  9350. this.bindUnboundFramebuffer(null);
  9351. };
  9352. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  9353. if (texture.generateMipMaps) {
  9354. var gl = this._gl;
  9355. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9356. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9357. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9358. }
  9359. };
  9360. Engine.prototype.flushFramebuffer = function () {
  9361. this._gl.flush();
  9362. };
  9363. Engine.prototype.restoreDefaultFramebuffer = function () {
  9364. if (this._currentRenderTarget) {
  9365. this.unBindFramebuffer(this._currentRenderTarget);
  9366. }
  9367. else {
  9368. this.bindUnboundFramebuffer(null);
  9369. }
  9370. if (this._cachedViewport) {
  9371. this.setViewport(this._cachedViewport);
  9372. }
  9373. this.wipeCaches();
  9374. };
  9375. // UBOs
  9376. Engine.prototype.createUniformBuffer = function (elements) {
  9377. var ubo = this._gl.createBuffer();
  9378. if (!ubo) {
  9379. throw new Error("Unable to create uniform buffer");
  9380. }
  9381. this.bindUniformBuffer(ubo);
  9382. if (elements instanceof Float32Array) {
  9383. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  9384. }
  9385. else {
  9386. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  9387. }
  9388. this.bindUniformBuffer(null);
  9389. ubo.references = 1;
  9390. return ubo;
  9391. };
  9392. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  9393. var ubo = this._gl.createBuffer();
  9394. if (!ubo) {
  9395. throw new Error("Unable to create dynamic uniform buffer");
  9396. }
  9397. this.bindUniformBuffer(ubo);
  9398. if (elements instanceof Float32Array) {
  9399. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  9400. }
  9401. else {
  9402. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  9403. }
  9404. this.bindUniformBuffer(null);
  9405. ubo.references = 1;
  9406. return ubo;
  9407. };
  9408. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  9409. this.bindUniformBuffer(uniformBuffer);
  9410. if (offset === undefined) {
  9411. offset = 0;
  9412. }
  9413. if (count === undefined) {
  9414. if (elements instanceof Float32Array) {
  9415. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  9416. }
  9417. else {
  9418. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  9419. }
  9420. }
  9421. else {
  9422. if (elements instanceof Float32Array) {
  9423. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  9424. }
  9425. else {
  9426. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  9427. }
  9428. }
  9429. this.bindUniformBuffer(null);
  9430. };
  9431. // VBOs
  9432. Engine.prototype._resetVertexBufferBinding = function () {
  9433. this.bindArrayBuffer(null);
  9434. this._cachedVertexBuffers = null;
  9435. };
  9436. Engine.prototype.createVertexBuffer = function (vertices) {
  9437. var vbo = this._gl.createBuffer();
  9438. if (!vbo) {
  9439. throw new Error("Unable to create vertex buffer");
  9440. }
  9441. this.bindArrayBuffer(vbo);
  9442. if (vertices instanceof Float32Array) {
  9443. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  9444. }
  9445. else {
  9446. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  9447. }
  9448. this._resetVertexBufferBinding();
  9449. vbo.references = 1;
  9450. return vbo;
  9451. };
  9452. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  9453. var vbo = this._gl.createBuffer();
  9454. if (!vbo) {
  9455. throw new Error("Unable to create dynamic vertex buffer");
  9456. }
  9457. this.bindArrayBuffer(vbo);
  9458. if (vertices instanceof Float32Array) {
  9459. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  9460. }
  9461. else {
  9462. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  9463. }
  9464. this._resetVertexBufferBinding();
  9465. vbo.references = 1;
  9466. return vbo;
  9467. };
  9468. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  9469. if (offset === void 0) { offset = 0; }
  9470. // Force cache update
  9471. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  9472. this.bindIndexBuffer(indexBuffer);
  9473. var arrayBuffer;
  9474. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  9475. arrayBuffer = indices;
  9476. }
  9477. else {
  9478. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9479. }
  9480. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  9481. this._resetIndexBufferBinding();
  9482. };
  9483. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  9484. this.bindArrayBuffer(vertexBuffer);
  9485. if (offset === undefined) {
  9486. offset = 0;
  9487. }
  9488. if (count === undefined) {
  9489. if (vertices instanceof Float32Array) {
  9490. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  9491. }
  9492. else {
  9493. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  9494. }
  9495. }
  9496. else {
  9497. if (vertices instanceof Float32Array) {
  9498. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  9499. }
  9500. else {
  9501. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  9502. }
  9503. }
  9504. this._resetVertexBufferBinding();
  9505. };
  9506. Engine.prototype._resetIndexBufferBinding = function () {
  9507. this.bindIndexBuffer(null);
  9508. this._cachedIndexBuffer = null;
  9509. };
  9510. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  9511. var vbo = this._gl.createBuffer();
  9512. if (!vbo) {
  9513. throw new Error("Unable to create index buffer");
  9514. }
  9515. this.bindIndexBuffer(vbo);
  9516. // Check for 32 bits indices
  9517. var arrayBuffer;
  9518. var need32Bits = false;
  9519. if (indices instanceof Uint16Array) {
  9520. arrayBuffer = indices;
  9521. }
  9522. else {
  9523. //check 32 bit support
  9524. if (this._caps.uintIndices) {
  9525. if (indices instanceof Uint32Array) {
  9526. arrayBuffer = indices;
  9527. need32Bits = true;
  9528. }
  9529. else {
  9530. //number[] or Int32Array, check if 32 bit is necessary
  9531. for (var index = 0; index < indices.length; index++) {
  9532. if (indices[index] > 65535) {
  9533. need32Bits = true;
  9534. break;
  9535. }
  9536. }
  9537. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9538. }
  9539. }
  9540. else {
  9541. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  9542. arrayBuffer = new Uint16Array(indices);
  9543. }
  9544. }
  9545. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  9546. this._resetIndexBufferBinding();
  9547. vbo.references = 1;
  9548. vbo.is32Bits = need32Bits;
  9549. return vbo;
  9550. };
  9551. Engine.prototype.bindArrayBuffer = function (buffer) {
  9552. if (!this._vaoRecordInProgress) {
  9553. this._unbindVertexArrayObject();
  9554. }
  9555. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  9556. };
  9557. Engine.prototype.bindUniformBuffer = function (buffer) {
  9558. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  9559. };
  9560. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  9561. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  9562. };
  9563. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  9564. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  9565. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  9566. };
  9567. ;
  9568. Engine.prototype.bindIndexBuffer = function (buffer) {
  9569. if (!this._vaoRecordInProgress) {
  9570. this._unbindVertexArrayObject();
  9571. }
  9572. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  9573. };
  9574. Engine.prototype.bindBuffer = function (buffer, target) {
  9575. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  9576. this._gl.bindBuffer(target, buffer);
  9577. this._currentBoundBuffer[target] = buffer;
  9578. }
  9579. };
  9580. Engine.prototype.updateArrayBuffer = function (data) {
  9581. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9582. };
  9583. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  9584. var pointer = this._currentBufferPointers[indx];
  9585. var changed = false;
  9586. if (!pointer.active) {
  9587. changed = true;
  9588. pointer.active = true;
  9589. pointer.index = indx;
  9590. pointer.size = size;
  9591. pointer.type = type;
  9592. pointer.normalized = normalized;
  9593. pointer.stride = stride;
  9594. pointer.offset = offset;
  9595. pointer.buffer = buffer;
  9596. }
  9597. else {
  9598. if (pointer.buffer !== buffer) {
  9599. pointer.buffer = buffer;
  9600. changed = true;
  9601. }
  9602. if (pointer.size !== size) {
  9603. pointer.size = size;
  9604. changed = true;
  9605. }
  9606. if (pointer.type !== type) {
  9607. pointer.type = type;
  9608. changed = true;
  9609. }
  9610. if (pointer.normalized !== normalized) {
  9611. pointer.normalized = normalized;
  9612. changed = true;
  9613. }
  9614. if (pointer.stride !== stride) {
  9615. pointer.stride = stride;
  9616. changed = true;
  9617. }
  9618. if (pointer.offset !== offset) {
  9619. pointer.offset = offset;
  9620. changed = true;
  9621. }
  9622. }
  9623. if (changed || this._vaoRecordInProgress) {
  9624. this.bindArrayBuffer(buffer);
  9625. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9626. }
  9627. };
  9628. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9629. if (indexBuffer == null) {
  9630. return;
  9631. }
  9632. if (this._cachedIndexBuffer !== indexBuffer) {
  9633. this._cachedIndexBuffer = indexBuffer;
  9634. this.bindIndexBuffer(indexBuffer);
  9635. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9636. }
  9637. };
  9638. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9639. var attributes = effect.getAttributesNames();
  9640. if (!this._vaoRecordInProgress) {
  9641. this._unbindVertexArrayObject();
  9642. }
  9643. this.unbindAllAttributes();
  9644. for (var index = 0; index < attributes.length; index++) {
  9645. var order = effect.getAttributeLocation(index);
  9646. if (order >= 0) {
  9647. var vertexBuffer = vertexBuffers[attributes[index]];
  9648. if (!vertexBuffer) {
  9649. continue;
  9650. }
  9651. this._gl.enableVertexAttribArray(order);
  9652. if (!this._vaoRecordInProgress) {
  9653. this._vertexAttribArraysEnabled[order] = true;
  9654. }
  9655. var buffer = vertexBuffer.getBuffer();
  9656. if (buffer) {
  9657. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9658. if (vertexBuffer.getIsInstanced()) {
  9659. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  9660. if (!this._vaoRecordInProgress) {
  9661. this._currentInstanceLocations.push(order);
  9662. this._currentInstanceBuffers.push(buffer);
  9663. }
  9664. }
  9665. }
  9666. }
  9667. }
  9668. };
  9669. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9670. var vao = this._gl.createVertexArray();
  9671. this._vaoRecordInProgress = true;
  9672. this._gl.bindVertexArray(vao);
  9673. this._mustWipeVertexAttributes = true;
  9674. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9675. this.bindIndexBuffer(indexBuffer);
  9676. this._vaoRecordInProgress = false;
  9677. this._gl.bindVertexArray(null);
  9678. return vao;
  9679. };
  9680. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9681. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9682. this._cachedVertexArrayObject = vertexArrayObject;
  9683. this._gl.bindVertexArray(vertexArrayObject);
  9684. this._cachedVertexBuffers = null;
  9685. this._cachedIndexBuffer = null;
  9686. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9687. this._mustWipeVertexAttributes = true;
  9688. }
  9689. };
  9690. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9691. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9692. this._cachedVertexBuffers = vertexBuffer;
  9693. this._cachedEffectForVertexBuffers = effect;
  9694. var attributesCount = effect.getAttributesCount();
  9695. this._unbindVertexArrayObject();
  9696. this.unbindAllAttributes();
  9697. var offset = 0;
  9698. for (var index = 0; index < attributesCount; index++) {
  9699. if (index < vertexDeclaration.length) {
  9700. var order = effect.getAttributeLocation(index);
  9701. if (order >= 0) {
  9702. this._gl.enableVertexAttribArray(order);
  9703. this._vertexAttribArraysEnabled[order] = true;
  9704. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9705. }
  9706. offset += vertexDeclaration[index] * 4;
  9707. }
  9708. }
  9709. }
  9710. this._bindIndexBufferWithCache(indexBuffer);
  9711. };
  9712. Engine.prototype._unbindVertexArrayObject = function () {
  9713. if (!this._cachedVertexArrayObject) {
  9714. return;
  9715. }
  9716. this._cachedVertexArrayObject = null;
  9717. this._gl.bindVertexArray(null);
  9718. };
  9719. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9720. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9721. this._cachedVertexBuffers = vertexBuffers;
  9722. this._cachedEffectForVertexBuffers = effect;
  9723. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9724. }
  9725. this._bindIndexBufferWithCache(indexBuffer);
  9726. };
  9727. Engine.prototype.unbindInstanceAttributes = function () {
  9728. var boundBuffer;
  9729. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9730. var instancesBuffer = this._currentInstanceBuffers[i];
  9731. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9732. boundBuffer = instancesBuffer;
  9733. this.bindArrayBuffer(instancesBuffer);
  9734. }
  9735. var offsetLocation = this._currentInstanceLocations[i];
  9736. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9737. }
  9738. this._currentInstanceBuffers.length = 0;
  9739. this._currentInstanceLocations.length = 0;
  9740. };
  9741. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9742. this._gl.deleteVertexArray(vao);
  9743. };
  9744. Engine.prototype._releaseBuffer = function (buffer) {
  9745. buffer.references--;
  9746. if (buffer.references === 0) {
  9747. this._gl.deleteBuffer(buffer);
  9748. return true;
  9749. }
  9750. return false;
  9751. };
  9752. Engine.prototype.createInstancesBuffer = function (capacity) {
  9753. var buffer = this._gl.createBuffer();
  9754. if (!buffer) {
  9755. throw new Error("Unable to create instance buffer");
  9756. }
  9757. buffer.capacity = capacity;
  9758. this.bindArrayBuffer(buffer);
  9759. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9760. return buffer;
  9761. };
  9762. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9763. this._gl.deleteBuffer(buffer);
  9764. };
  9765. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9766. this.bindArrayBuffer(instancesBuffer);
  9767. if (data) {
  9768. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9769. }
  9770. if (offsetLocations[0].index !== undefined) {
  9771. var stride = 0;
  9772. for (var i = 0; i < offsetLocations.length; i++) {
  9773. var ai = offsetLocations[i];
  9774. stride += ai.attributeSize * 4;
  9775. }
  9776. for (var i = 0; i < offsetLocations.length; i++) {
  9777. var ai = offsetLocations[i];
  9778. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9779. this._gl.enableVertexAttribArray(ai.index);
  9780. this._vertexAttribArraysEnabled[ai.index] = true;
  9781. }
  9782. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9783. this._gl.vertexAttribDivisor(ai.index, 1);
  9784. this._currentInstanceLocations.push(ai.index);
  9785. this._currentInstanceBuffers.push(instancesBuffer);
  9786. }
  9787. }
  9788. else {
  9789. for (var index = 0; index < 4; index++) {
  9790. var offsetLocation = offsetLocations[index];
  9791. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9792. this._gl.enableVertexAttribArray(offsetLocation);
  9793. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9794. }
  9795. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9796. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9797. this._currentInstanceLocations.push(offsetLocation);
  9798. this._currentInstanceBuffers.push(instancesBuffer);
  9799. }
  9800. }
  9801. };
  9802. Engine.prototype.applyStates = function () {
  9803. this._depthCullingState.apply(this._gl);
  9804. this._stencilState.apply(this._gl);
  9805. this._alphaState.apply(this._gl);
  9806. };
  9807. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9808. // Apply states
  9809. this.applyStates();
  9810. this._drawCalls.addCount(1, false);
  9811. // Render
  9812. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9813. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9814. if (instancesCount) {
  9815. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9816. return;
  9817. }
  9818. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9819. };
  9820. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9821. // Apply states
  9822. this.applyStates();
  9823. this._drawCalls.addCount(1, false);
  9824. if (instancesCount) {
  9825. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9826. return;
  9827. }
  9828. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9829. };
  9830. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9831. // Apply states
  9832. this.applyStates();
  9833. this._drawCalls.addCount(1, false);
  9834. if (instancesCount) {
  9835. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9836. return;
  9837. }
  9838. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9839. };
  9840. // Shaders
  9841. Engine.prototype._releaseEffect = function (effect) {
  9842. if (this._compiledEffects[effect._key]) {
  9843. delete this._compiledEffects[effect._key];
  9844. this._deleteProgram(effect.getProgram());
  9845. }
  9846. };
  9847. Engine.prototype._deleteProgram = function (program) {
  9848. if (program) {
  9849. program.__SPECTOR_rebuildProgram = null;
  9850. if (program.transformFeedback) {
  9851. this.deleteTransformFeedback(program.transformFeedback);
  9852. program.transformFeedback = null;
  9853. }
  9854. this._gl.deleteProgram(program);
  9855. }
  9856. };
  9857. /**
  9858. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9859. * @param samplers An array of string used to represent textures
  9860. */
  9861. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9862. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9863. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9864. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9865. if (this._compiledEffects[name]) {
  9866. var compiledEffect = this._compiledEffects[name];
  9867. if (onCompiled && compiledEffect.isReady()) {
  9868. onCompiled(compiledEffect);
  9869. }
  9870. return compiledEffect;
  9871. }
  9872. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9873. effect._key = name;
  9874. this._compiledEffects[name] = effect;
  9875. return effect;
  9876. };
  9877. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9878. if (uniformsNames === void 0) { uniformsNames = []; }
  9879. if (samplers === void 0) { samplers = []; }
  9880. if (defines === void 0) { defines = ""; }
  9881. return this.createEffect({
  9882. vertex: "particles",
  9883. fragmentElement: fragmentName
  9884. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9885. };
  9886. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  9887. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9888. context = context || this._gl;
  9889. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  9890. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  9891. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  9892. };
  9893. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  9894. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9895. context = context || this._gl;
  9896. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  9897. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9898. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9899. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9900. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  9901. this.onAfterShaderCompilationObservable.notifyObservers(this);
  9902. return program;
  9903. };
  9904. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  9905. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9906. var shaderProgram = context.createProgram();
  9907. if (!shaderProgram) {
  9908. throw new Error("Unable to create program");
  9909. }
  9910. context.attachShader(shaderProgram, vertexShader);
  9911. context.attachShader(shaderProgram, fragmentShader);
  9912. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  9913. var transformFeedback = this.createTransformFeedback();
  9914. this.bindTransformFeedback(transformFeedback);
  9915. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  9916. shaderProgram.transformFeedback = transformFeedback;
  9917. }
  9918. context.linkProgram(shaderProgram);
  9919. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  9920. this.bindTransformFeedback(null);
  9921. }
  9922. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9923. if (!linked) {
  9924. context.validateProgram(shaderProgram);
  9925. var error = context.getProgramInfoLog(shaderProgram);
  9926. if (error) {
  9927. throw new Error(error);
  9928. }
  9929. }
  9930. context.deleteShader(vertexShader);
  9931. context.deleteShader(fragmentShader);
  9932. return shaderProgram;
  9933. };
  9934. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9935. var results = new Array();
  9936. for (var index = 0; index < uniformsNames.length; index++) {
  9937. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9938. }
  9939. return results;
  9940. };
  9941. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9942. var results = [];
  9943. for (var index = 0; index < attributesNames.length; index++) {
  9944. try {
  9945. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9946. }
  9947. catch (e) {
  9948. results.push(-1);
  9949. }
  9950. }
  9951. return results;
  9952. };
  9953. Engine.prototype.enableEffect = function (effect) {
  9954. if (!effect) {
  9955. return;
  9956. }
  9957. // Use program
  9958. this.setProgram(effect.getProgram());
  9959. this._currentEffect = effect;
  9960. if (effect.onBind) {
  9961. effect.onBind(effect);
  9962. }
  9963. effect.onBindObservable.notifyObservers(effect);
  9964. };
  9965. Engine.prototype.setIntArray = function (uniform, array) {
  9966. if (!uniform)
  9967. return;
  9968. this._gl.uniform1iv(uniform, array);
  9969. };
  9970. Engine.prototype.setIntArray2 = function (uniform, array) {
  9971. if (!uniform || array.length % 2 !== 0)
  9972. return;
  9973. this._gl.uniform2iv(uniform, array);
  9974. };
  9975. Engine.prototype.setIntArray3 = function (uniform, array) {
  9976. if (!uniform || array.length % 3 !== 0)
  9977. return;
  9978. this._gl.uniform3iv(uniform, array);
  9979. };
  9980. Engine.prototype.setIntArray4 = function (uniform, array) {
  9981. if (!uniform || array.length % 4 !== 0)
  9982. return;
  9983. this._gl.uniform4iv(uniform, array);
  9984. };
  9985. Engine.prototype.setFloatArray = function (uniform, array) {
  9986. if (!uniform)
  9987. return;
  9988. this._gl.uniform1fv(uniform, array);
  9989. };
  9990. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9991. if (!uniform || array.length % 2 !== 0)
  9992. return;
  9993. this._gl.uniform2fv(uniform, array);
  9994. };
  9995. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9996. if (!uniform || array.length % 3 !== 0)
  9997. return;
  9998. this._gl.uniform3fv(uniform, array);
  9999. };
  10000. Engine.prototype.setFloatArray4 = function (uniform, array) {
  10001. if (!uniform || array.length % 4 !== 0)
  10002. return;
  10003. this._gl.uniform4fv(uniform, array);
  10004. };
  10005. Engine.prototype.setArray = function (uniform, array) {
  10006. if (!uniform)
  10007. return;
  10008. this._gl.uniform1fv(uniform, array);
  10009. };
  10010. Engine.prototype.setArray2 = function (uniform, array) {
  10011. if (!uniform || array.length % 2 !== 0)
  10012. return;
  10013. this._gl.uniform2fv(uniform, array);
  10014. };
  10015. Engine.prototype.setArray3 = function (uniform, array) {
  10016. if (!uniform || array.length % 3 !== 0)
  10017. return;
  10018. this._gl.uniform3fv(uniform, array);
  10019. };
  10020. Engine.prototype.setArray4 = function (uniform, array) {
  10021. if (!uniform || array.length % 4 !== 0)
  10022. return;
  10023. this._gl.uniform4fv(uniform, array);
  10024. };
  10025. Engine.prototype.setMatrices = function (uniform, matrices) {
  10026. if (!uniform)
  10027. return;
  10028. this._gl.uniformMatrix4fv(uniform, false, matrices);
  10029. };
  10030. Engine.prototype.setMatrix = function (uniform, matrix) {
  10031. if (!uniform)
  10032. return;
  10033. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  10034. };
  10035. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  10036. if (!uniform)
  10037. return;
  10038. this._gl.uniformMatrix3fv(uniform, false, matrix);
  10039. };
  10040. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  10041. if (!uniform)
  10042. return;
  10043. this._gl.uniformMatrix2fv(uniform, false, matrix);
  10044. };
  10045. Engine.prototype.setFloat = function (uniform, value) {
  10046. if (!uniform)
  10047. return;
  10048. this._gl.uniform1f(uniform, value);
  10049. };
  10050. Engine.prototype.setFloat2 = function (uniform, x, y) {
  10051. if (!uniform)
  10052. return;
  10053. this._gl.uniform2f(uniform, x, y);
  10054. };
  10055. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  10056. if (!uniform)
  10057. return;
  10058. this._gl.uniform3f(uniform, x, y, z);
  10059. };
  10060. Engine.prototype.setBool = function (uniform, bool) {
  10061. if (!uniform)
  10062. return;
  10063. this._gl.uniform1i(uniform, bool);
  10064. };
  10065. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  10066. if (!uniform)
  10067. return;
  10068. this._gl.uniform4f(uniform, x, y, z, w);
  10069. };
  10070. Engine.prototype.setColor3 = function (uniform, color3) {
  10071. if (!uniform)
  10072. return;
  10073. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  10074. };
  10075. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  10076. if (!uniform)
  10077. return;
  10078. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  10079. };
  10080. // States
  10081. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  10082. if (zOffset === void 0) { zOffset = 0; }
  10083. if (reverseSide === void 0) { reverseSide = false; }
  10084. // Culling
  10085. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  10086. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  10087. var cullFace = this.cullBackFaces ? showSide : hideSide;
  10088. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  10089. if (culling) {
  10090. this._depthCullingState.cullFace = cullFace;
  10091. this._depthCullingState.cull = true;
  10092. }
  10093. else {
  10094. this._depthCullingState.cull = false;
  10095. }
  10096. }
  10097. // Z offset
  10098. this.setZOffset(zOffset);
  10099. };
  10100. Engine.prototype.setZOffset = function (value) {
  10101. this._depthCullingState.zOffset = value;
  10102. };
  10103. Engine.prototype.getZOffset = function () {
  10104. return this._depthCullingState.zOffset;
  10105. };
  10106. Engine.prototype.setDepthBuffer = function (enable) {
  10107. this._depthCullingState.depthTest = enable;
  10108. };
  10109. Engine.prototype.getDepthWrite = function () {
  10110. return this._depthCullingState.depthMask;
  10111. };
  10112. Engine.prototype.setDepthWrite = function (enable) {
  10113. this._depthCullingState.depthMask = enable;
  10114. };
  10115. Engine.prototype.setColorWrite = function (enable) {
  10116. this._gl.colorMask(enable, enable, enable, enable);
  10117. this._colorWrite = enable;
  10118. };
  10119. Engine.prototype.getColorWrite = function () {
  10120. return this._colorWrite;
  10121. };
  10122. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  10123. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  10124. };
  10125. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  10126. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  10127. if (this._alphaMode === mode) {
  10128. return;
  10129. }
  10130. switch (mode) {
  10131. case Engine.ALPHA_DISABLE:
  10132. this._alphaState.alphaBlend = false;
  10133. break;
  10134. case Engine.ALPHA_PREMULTIPLIED:
  10135. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  10136. this._alphaState.alphaBlend = true;
  10137. break;
  10138. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  10139. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  10140. this._alphaState.alphaBlend = true;
  10141. break;
  10142. case Engine.ALPHA_COMBINE:
  10143. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  10144. this._alphaState.alphaBlend = true;
  10145. break;
  10146. case Engine.ALPHA_ONEONE:
  10147. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10148. this._alphaState.alphaBlend = true;
  10149. break;
  10150. case Engine.ALPHA_ADD:
  10151. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10152. this._alphaState.alphaBlend = true;
  10153. break;
  10154. case Engine.ALPHA_SUBTRACT:
  10155. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10156. this._alphaState.alphaBlend = true;
  10157. break;
  10158. case Engine.ALPHA_MULTIPLY:
  10159. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  10160. this._alphaState.alphaBlend = true;
  10161. break;
  10162. case Engine.ALPHA_MAXIMIZED:
  10163. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10164. this._alphaState.alphaBlend = true;
  10165. break;
  10166. case Engine.ALPHA_INTERPOLATE:
  10167. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  10168. this._alphaState.alphaBlend = true;
  10169. break;
  10170. case Engine.ALPHA_SCREENMODE:
  10171. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  10172. this._alphaState.alphaBlend = true;
  10173. break;
  10174. }
  10175. if (!noDepthWriteChange) {
  10176. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  10177. }
  10178. this._alphaMode = mode;
  10179. };
  10180. Engine.prototype.getAlphaMode = function () {
  10181. return this._alphaMode;
  10182. };
  10183. Engine.prototype.setAlphaTesting = function (enable) {
  10184. this._alphaTest = enable;
  10185. };
  10186. Engine.prototype.getAlphaTesting = function () {
  10187. return !!this._alphaTest;
  10188. };
  10189. // Textures
  10190. Engine.prototype.wipeCaches = function (bruteForce) {
  10191. if (this.preventCacheWipeBetweenFrames) {
  10192. return;
  10193. }
  10194. this.resetTextureCache();
  10195. this._currentEffect = null;
  10196. // 6/8/2017: deltakosh: Should not be required anymore.
  10197. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  10198. if (bruteForce) {
  10199. this._currentProgram = null;
  10200. this._stencilState.reset();
  10201. this._depthCullingState.reset();
  10202. this.setDepthFunctionToLessOrEqual();
  10203. this._alphaState.reset();
  10204. }
  10205. this._cachedVertexBuffers = null;
  10206. this._cachedIndexBuffer = null;
  10207. this._cachedEffectForVertexBuffers = null;
  10208. this._unbindVertexArrayObject();
  10209. this.bindIndexBuffer(null);
  10210. this.bindArrayBuffer(null);
  10211. };
  10212. /**
  10213. * Set the compressed texture format to use, based on the formats you have, and the formats
  10214. * supported by the hardware / browser.
  10215. *
  10216. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  10217. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  10218. * to API arguments needed to compressed textures. This puts the burden on the container
  10219. * generator to house the arcane code for determining these for current & future formats.
  10220. *
  10221. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  10222. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  10223. *
  10224. * Note: The result of this call is not taken into account when a texture is base64.
  10225. *
  10226. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  10227. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  10228. *
  10229. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  10230. * @returns The extension selected.
  10231. */
  10232. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  10233. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  10234. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  10235. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  10236. return this._textureFormatInUse = this._texturesSupported[i];
  10237. }
  10238. }
  10239. }
  10240. // actively set format to nothing, to allow this to be called more than once
  10241. // and possibly fail the 2nd time
  10242. this._textureFormatInUse = null;
  10243. return null;
  10244. };
  10245. Engine.prototype._createTexture = function () {
  10246. var texture = this._gl.createTexture();
  10247. if (!texture) {
  10248. throw new Error("Unable to create texture");
  10249. }
  10250. return texture;
  10251. };
  10252. /**
  10253. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  10254. * @param {string} urlArg- This contains one of the following:
  10255. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  10256. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  10257. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  10258. *
  10259. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  10260. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  10261. * @param {Scene} scene- Needed for loading to the correct scene.
  10262. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  10263. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  10264. * @param {callback} onError- Optional callback to be called upon failure.
  10265. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  10266. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  10267. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  10268. *
  10269. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  10270. */
  10271. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  10272. var _this = this;
  10273. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10274. if (onLoad === void 0) { onLoad = null; }
  10275. if (onError === void 0) { onError = null; }
  10276. if (buffer === void 0) { buffer = null; }
  10277. if (fallBack === void 0) { fallBack = null; }
  10278. if (format === void 0) { format = null; }
  10279. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  10280. var fromData = url.substr(0, 5) === "data:";
  10281. var fromBlob = url.substr(0, 5) === "blob:";
  10282. var isBase64 = fromData && url.indexOf("base64") !== -1;
  10283. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  10284. // establish the file extension, if possible
  10285. var lastDot = url.lastIndexOf('.');
  10286. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  10287. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  10288. var isTGA = (extension === ".tga");
  10289. // determine if a ktx file should be substituted
  10290. var isKTX = false;
  10291. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  10292. url = url.substring(0, lastDot) + this._textureFormatInUse;
  10293. isKTX = true;
  10294. }
  10295. if (scene) {
  10296. scene._addPendingData(texture);
  10297. }
  10298. texture.url = url;
  10299. texture.generateMipMaps = !noMipmap;
  10300. texture.samplingMode = samplingMode;
  10301. texture.invertY = invertY;
  10302. if (!this._doNotHandleContextLost) {
  10303. // Keep a link to the buffer only if we plan to handle context lost
  10304. texture._buffer = buffer;
  10305. }
  10306. var onLoadObserver = null;
  10307. if (onLoad && !fallBack) {
  10308. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  10309. }
  10310. if (!fallBack)
  10311. this._internalTexturesCache.push(texture);
  10312. var onerror = function (message, exception) {
  10313. if (scene) {
  10314. scene._removePendingData(texture);
  10315. }
  10316. if (onLoadObserver) {
  10317. texture.onLoadedObservable.remove(onLoadObserver);
  10318. }
  10319. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  10320. if (isKTX) {
  10321. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10322. }
  10323. else if (BABYLON.Tools.UseFallbackTexture) {
  10324. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10325. }
  10326. if (onError) {
  10327. onError(message || "Unknown error", exception);
  10328. }
  10329. };
  10330. var callback = null;
  10331. // processing for non-image formats
  10332. if (isKTX || isTGA || isDDS) {
  10333. if (isKTX) {
  10334. callback = function (data) {
  10335. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  10336. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  10337. ktx.uploadLevels(_this._gl, !noMipmap);
  10338. return false;
  10339. }, samplingMode);
  10340. };
  10341. }
  10342. else if (isTGA) {
  10343. callback = function (arrayBuffer) {
  10344. var data = new Uint8Array(arrayBuffer);
  10345. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  10346. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  10347. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  10348. return false;
  10349. }, samplingMode);
  10350. };
  10351. }
  10352. else if (isDDS) {
  10353. callback = function (data) {
  10354. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10355. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  10356. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  10357. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  10358. return false;
  10359. }, samplingMode);
  10360. };
  10361. }
  10362. if (!buffer) {
  10363. BABYLON.Tools.LoadFile(url, function (data) {
  10364. if (callback) {
  10365. callback(data);
  10366. }
  10367. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  10368. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  10369. });
  10370. }
  10371. else {
  10372. if (callback) {
  10373. callback(buffer);
  10374. }
  10375. }
  10376. // image format processing
  10377. }
  10378. else {
  10379. var onload = function (img) {
  10380. if (fromBlob && !_this._doNotHandleContextLost) {
  10381. // We need to store the image if we need to rebuild the texture
  10382. // in case of a webgl context lost
  10383. texture._buffer = img;
  10384. }
  10385. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  10386. var gl = _this._gl;
  10387. var isPot = (img.width === potWidth && img.height === potHeight);
  10388. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  10389. if (isPot) {
  10390. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10391. return false;
  10392. }
  10393. // Using shaders to rescale because canvas.drawImage is lossy
  10394. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10395. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  10396. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10397. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10398. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10399. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10400. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10401. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  10402. _this._releaseTexture(source);
  10403. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10404. continuationCallback();
  10405. });
  10406. return true;
  10407. }, samplingMode);
  10408. };
  10409. if (!fromData || isBase64)
  10410. if (buffer instanceof HTMLImageElement) {
  10411. onload(buffer);
  10412. }
  10413. else {
  10414. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10415. }
  10416. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  10417. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  10418. else
  10419. onload(buffer);
  10420. }
  10421. return texture;
  10422. };
  10423. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  10424. var _this = this;
  10425. var rtt = this.createRenderTargetTexture({
  10426. width: destination.width,
  10427. height: destination.height,
  10428. }, {
  10429. generateMipMaps: false,
  10430. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  10431. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  10432. generateDepthBuffer: false,
  10433. generateStencilBuffer: false
  10434. });
  10435. if (!this._rescalePostProcess) {
  10436. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  10437. }
  10438. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  10439. _this._rescalePostProcess.onApply = function (effect) {
  10440. effect._bindTexture("textureSampler", source);
  10441. };
  10442. var hostingScene = scene;
  10443. if (!hostingScene) {
  10444. hostingScene = _this.scenes[_this.scenes.length - 1];
  10445. }
  10446. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  10447. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  10448. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  10449. _this.unBindFramebuffer(rtt);
  10450. _this._releaseTexture(rtt);
  10451. if (onComplete) {
  10452. onComplete();
  10453. }
  10454. });
  10455. };
  10456. Engine.prototype._getInternalFormat = function (format) {
  10457. var internalFormat = this._gl.RGBA;
  10458. switch (format) {
  10459. case Engine.TEXTUREFORMAT_ALPHA:
  10460. internalFormat = this._gl.ALPHA;
  10461. break;
  10462. case Engine.TEXTUREFORMAT_LUMINANCE:
  10463. internalFormat = this._gl.LUMINANCE;
  10464. break;
  10465. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  10466. internalFormat = this._gl.LUMINANCE_ALPHA;
  10467. break;
  10468. case Engine.TEXTUREFORMAT_RGB:
  10469. internalFormat = this._gl.RGB;
  10470. break;
  10471. case Engine.TEXTUREFORMAT_RGBA:
  10472. internalFormat = this._gl.RGBA;
  10473. break;
  10474. }
  10475. return internalFormat;
  10476. };
  10477. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  10478. if (compression === void 0) { compression = null; }
  10479. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  10480. if (!texture) {
  10481. return;
  10482. }
  10483. var internalFormat = this._getInternalFormat(format);
  10484. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10485. var textureType = this._getWebGLTextureType(type);
  10486. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10487. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10488. if (!this._doNotHandleContextLost) {
  10489. texture._bufferView = data;
  10490. texture.format = format;
  10491. texture.type = type;
  10492. texture.invertY = invertY;
  10493. texture._compression = compression;
  10494. }
  10495. if (texture.width % 4 !== 0) {
  10496. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  10497. }
  10498. if (compression && data) {
  10499. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  10500. }
  10501. else {
  10502. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  10503. }
  10504. if (texture.generateMipMaps) {
  10505. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10506. }
  10507. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10508. this.resetTextureCache();
  10509. texture.isReady = true;
  10510. };
  10511. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  10512. if (compression === void 0) { compression = null; }
  10513. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  10514. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  10515. texture.baseWidth = width;
  10516. texture.baseHeight = height;
  10517. texture.width = width;
  10518. texture.height = height;
  10519. texture.format = format;
  10520. texture.generateMipMaps = generateMipMaps;
  10521. texture.samplingMode = samplingMode;
  10522. texture.invertY = invertY;
  10523. texture._compression = compression;
  10524. texture.type = type;
  10525. if (!this._doNotHandleContextLost) {
  10526. texture._bufferView = data;
  10527. }
  10528. this.updateRawTexture(texture, data, format, invertY, compression, type);
  10529. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10530. // Filters
  10531. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  10532. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10533. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10534. if (generateMipMaps) {
  10535. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10536. }
  10537. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10538. this._internalTexturesCache.push(texture);
  10539. return texture;
  10540. };
  10541. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  10542. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  10543. texture.baseWidth = width;
  10544. texture.baseHeight = height;
  10545. if (generateMipMaps) {
  10546. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  10547. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  10548. }
  10549. this.resetTextureCache();
  10550. texture.width = width;
  10551. texture.height = height;
  10552. texture.isReady = false;
  10553. texture.generateMipMaps = generateMipMaps;
  10554. texture.samplingMode = samplingMode;
  10555. this.updateTextureSamplingMode(samplingMode, texture);
  10556. this._internalTexturesCache.push(texture);
  10557. return texture;
  10558. };
  10559. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  10560. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  10561. if (texture.isCube) {
  10562. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10563. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10564. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10565. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10566. }
  10567. else if (texture.is3D) {
  10568. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  10569. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10570. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10571. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  10572. }
  10573. else {
  10574. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10575. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10576. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10577. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10578. }
  10579. texture.samplingMode = samplingMode;
  10580. };
  10581. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  10582. if (premulAlpha === void 0) { premulAlpha = false; }
  10583. if (!texture) {
  10584. return;
  10585. }
  10586. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10587. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  10588. if (premulAlpha) {
  10589. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  10590. }
  10591. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  10592. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  10593. if (texture.generateMipMaps) {
  10594. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10595. }
  10596. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10597. if (premulAlpha) {
  10598. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  10599. }
  10600. this.resetTextureCache();
  10601. texture.isReady = true;
  10602. };
  10603. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  10604. if (!texture || texture._isDisabled) {
  10605. return;
  10606. }
  10607. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10608. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  10609. try {
  10610. // Testing video texture support
  10611. if (this._videoTextureSupported === undefined) {
  10612. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10613. if (this._gl.getError() !== 0) {
  10614. this._videoTextureSupported = false;
  10615. }
  10616. else {
  10617. this._videoTextureSupported = true;
  10618. }
  10619. }
  10620. // Copy video through the current working canvas if video texture is not supported
  10621. if (!this._videoTextureSupported) {
  10622. if (!texture._workingCanvas) {
  10623. texture._workingCanvas = document.createElement("canvas");
  10624. var context = texture._workingCanvas.getContext("2d");
  10625. if (!context) {
  10626. throw new Error("Unable to get 2d context");
  10627. }
  10628. texture._workingContext = context;
  10629. texture._workingCanvas.width = texture.width;
  10630. texture._workingCanvas.height = texture.height;
  10631. }
  10632. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  10633. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  10634. }
  10635. else {
  10636. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10637. }
  10638. if (texture.generateMipMaps) {
  10639. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10640. }
  10641. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10642. this.resetTextureCache();
  10643. texture.isReady = true;
  10644. }
  10645. catch (ex) {
  10646. // Something unexpected
  10647. // Let's disable the texture
  10648. texture._isDisabled = true;
  10649. }
  10650. };
  10651. Engine.prototype.createRenderTargetTexture = function (size, options) {
  10652. var fullOptions = new RenderTargetCreationOptions();
  10653. if (options !== undefined && typeof options === "object") {
  10654. fullOptions.generateMipMaps = options.generateMipMaps;
  10655. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10656. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  10657. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  10658. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  10659. }
  10660. else {
  10661. fullOptions.generateMipMaps = options;
  10662. fullOptions.generateDepthBuffer = true;
  10663. fullOptions.generateStencilBuffer = false;
  10664. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10665. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10666. }
  10667. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10668. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10669. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10670. }
  10671. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10672. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10673. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10674. }
  10675. var gl = this._gl;
  10676. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10677. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10678. var width = size.width || size;
  10679. var height = size.height || size;
  10680. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  10681. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10682. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10683. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10684. }
  10685. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10686. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10687. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10688. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10689. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  10690. // Create the framebuffer
  10691. var framebuffer = gl.createFramebuffer();
  10692. this.bindUnboundFramebuffer(framebuffer);
  10693. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10694. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  10695. if (fullOptions.generateMipMaps) {
  10696. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10697. }
  10698. // Unbind
  10699. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10700. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10701. this.bindUnboundFramebuffer(null);
  10702. texture._framebuffer = framebuffer;
  10703. texture.baseWidth = width;
  10704. texture.baseHeight = height;
  10705. texture.width = width;
  10706. texture.height = height;
  10707. texture.isReady = true;
  10708. texture.samples = 1;
  10709. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  10710. texture.samplingMode = fullOptions.samplingMode;
  10711. texture.type = fullOptions.type;
  10712. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  10713. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  10714. this.resetTextureCache();
  10715. this._internalTexturesCache.push(texture);
  10716. return texture;
  10717. };
  10718. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  10719. var generateMipMaps = false;
  10720. var generateDepthBuffer = true;
  10721. var generateStencilBuffer = false;
  10722. var generateDepthTexture = false;
  10723. var textureCount = 1;
  10724. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  10725. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10726. var types = [], samplingModes = [];
  10727. if (options !== undefined) {
  10728. generateMipMaps = options.generateMipMaps;
  10729. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10730. generateStencilBuffer = options.generateStencilBuffer;
  10731. generateDepthTexture = options.generateDepthTexture;
  10732. textureCount = options.textureCount || 1;
  10733. if (options.types) {
  10734. types = options.types;
  10735. }
  10736. if (options.samplingModes) {
  10737. samplingModes = options.samplingModes;
  10738. }
  10739. }
  10740. var gl = this._gl;
  10741. // Create the framebuffer
  10742. var framebuffer = gl.createFramebuffer();
  10743. this.bindUnboundFramebuffer(framebuffer);
  10744. var width = size.width || size;
  10745. var height = size.height || size;
  10746. var textures = [];
  10747. var attachments = [];
  10748. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  10749. for (var i = 0; i < textureCount; i++) {
  10750. var samplingMode = samplingModes[i] || defaultSamplingMode;
  10751. var type = types[i] || defaultType;
  10752. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10753. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10754. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10755. }
  10756. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10757. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10758. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10759. }
  10760. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10761. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10762. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10763. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10764. }
  10765. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10766. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10767. textures.push(texture);
  10768. attachments.push(attachment);
  10769. gl.activeTexture(gl["TEXTURE" + i]);
  10770. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  10771. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10772. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10773. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10774. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10775. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10776. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10777. if (generateMipMaps) {
  10778. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10779. }
  10780. // Unbind
  10781. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10782. texture._framebuffer = framebuffer;
  10783. texture._depthStencilBuffer = depthStencilBuffer;
  10784. texture.baseWidth = width;
  10785. texture.baseHeight = height;
  10786. texture.width = width;
  10787. texture.height = height;
  10788. texture.isReady = true;
  10789. texture.samples = 1;
  10790. texture.generateMipMaps = generateMipMaps;
  10791. texture.samplingMode = samplingMode;
  10792. texture.type = type;
  10793. texture._generateDepthBuffer = generateDepthBuffer;
  10794. texture._generateStencilBuffer = generateStencilBuffer;
  10795. this._internalTexturesCache.push(texture);
  10796. }
  10797. if (generateDepthTexture && this._caps.depthTextureExtension) {
  10798. // Depth texture
  10799. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10800. gl.activeTexture(gl.TEXTURE0);
  10801. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  10802. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10803. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10804. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10805. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10806. 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);
  10807. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10808. depthTexture._framebuffer = framebuffer;
  10809. depthTexture.baseWidth = width;
  10810. depthTexture.baseHeight = height;
  10811. depthTexture.width = width;
  10812. depthTexture.height = height;
  10813. depthTexture.isReady = true;
  10814. depthTexture.samples = 1;
  10815. depthTexture.generateMipMaps = generateMipMaps;
  10816. depthTexture.samplingMode = gl.NEAREST;
  10817. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10818. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10819. textures.push(depthTexture);
  10820. this._internalTexturesCache.push(depthTexture);
  10821. }
  10822. gl.drawBuffers(attachments);
  10823. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10824. this.bindUnboundFramebuffer(null);
  10825. this.resetTextureCache();
  10826. return textures;
  10827. };
  10828. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10829. if (samples === void 0) { samples = 1; }
  10830. var depthStencilBuffer = null;
  10831. var gl = this._gl;
  10832. // Create the depth/stencil buffer
  10833. if (generateStencilBuffer) {
  10834. depthStencilBuffer = gl.createRenderbuffer();
  10835. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10836. if (samples > 1) {
  10837. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10838. }
  10839. else {
  10840. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10841. }
  10842. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10843. }
  10844. else if (generateDepthBuffer) {
  10845. depthStencilBuffer = gl.createRenderbuffer();
  10846. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10847. if (samples > 1) {
  10848. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10849. }
  10850. else {
  10851. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10852. }
  10853. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10854. }
  10855. return depthStencilBuffer;
  10856. };
  10857. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10858. if (this.webGLVersion < 2 || !texture) {
  10859. return 1;
  10860. }
  10861. if (texture.samples === samples) {
  10862. return samples;
  10863. }
  10864. var gl = this._gl;
  10865. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10866. // Dispose previous render buffers
  10867. if (texture._depthStencilBuffer) {
  10868. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10869. }
  10870. if (texture._MSAAFramebuffer) {
  10871. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10872. }
  10873. if (texture._MSAARenderBuffer) {
  10874. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10875. }
  10876. if (samples > 1) {
  10877. var framebuffer = gl.createFramebuffer();
  10878. if (!framebuffer) {
  10879. throw new Error("Unable to create multi sampled framebuffer");
  10880. }
  10881. texture._MSAAFramebuffer = framebuffer;
  10882. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10883. var colorRenderbuffer = gl.createRenderbuffer();
  10884. if (!colorRenderbuffer) {
  10885. throw new Error("Unable to create multi sampled framebuffer");
  10886. }
  10887. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10888. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  10889. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10890. texture._MSAARenderBuffer = colorRenderbuffer;
  10891. }
  10892. else {
  10893. this.bindUnboundFramebuffer(texture._framebuffer);
  10894. }
  10895. texture.samples = samples;
  10896. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  10897. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10898. this.bindUnboundFramebuffer(null);
  10899. return samples;
  10900. };
  10901. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  10902. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  10903. };
  10904. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  10905. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  10906. };
  10907. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  10908. var gl = this._gl;
  10909. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10910. var generateMipMaps = true;
  10911. var generateDepthBuffer = true;
  10912. var generateStencilBuffer = false;
  10913. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10914. if (options !== undefined) {
  10915. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  10916. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10917. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  10918. if (options.samplingMode !== undefined) {
  10919. samplingMode = options.samplingMode;
  10920. }
  10921. }
  10922. texture.isCube = true;
  10923. texture.generateMipMaps = generateMipMaps;
  10924. texture.samples = 1;
  10925. texture.samplingMode = samplingMode;
  10926. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10927. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10928. for (var face = 0; face < 6; face++) {
  10929. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10930. }
  10931. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10932. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10933. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10934. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10935. // Create the framebuffer
  10936. var framebuffer = gl.createFramebuffer();
  10937. this.bindUnboundFramebuffer(framebuffer);
  10938. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10939. // Mipmaps
  10940. if (texture.generateMipMaps) {
  10941. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10942. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10943. }
  10944. // Unbind
  10945. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10946. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10947. this.bindUnboundFramebuffer(null);
  10948. texture._framebuffer = framebuffer;
  10949. texture.width = size;
  10950. texture.height = size;
  10951. texture.isReady = true;
  10952. this.resetTextureCache();
  10953. this._internalTexturesCache.push(texture);
  10954. return texture;
  10955. };
  10956. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  10957. var _this = this;
  10958. if (onLoad === void 0) { onLoad = null; }
  10959. if (onError === void 0) { onError = null; }
  10960. if (forcedExtension === void 0) { forcedExtension = null; }
  10961. var callback = function (loadData) {
  10962. if (!loadData) {
  10963. if (onLoad) {
  10964. onLoad(null);
  10965. }
  10966. return;
  10967. }
  10968. var texture = loadData.texture;
  10969. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  10970. texture._lodGenerationScale = scale;
  10971. texture._lodGenerationOffset = offset;
  10972. if (_this._caps.textureLOD) {
  10973. // Do not add extra process if texture lod is supported.
  10974. if (onLoad) {
  10975. onLoad(texture);
  10976. }
  10977. return;
  10978. }
  10979. var mipSlices = 3;
  10980. var gl = _this._gl;
  10981. var width = loadData.width;
  10982. if (!width) {
  10983. return;
  10984. }
  10985. var textures = [];
  10986. for (var i = 0; i < mipSlices; i++) {
  10987. //compute LOD from even spacing in smoothness (matching shader calculation)
  10988. var smoothness = i / (mipSlices - 1);
  10989. var roughness = 1 - smoothness;
  10990. var minLODIndex = offset; // roughness = 0
  10991. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  10992. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  10993. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  10994. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10995. glTextureFromLod.isCube = true;
  10996. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  10997. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10998. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10999. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11000. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11001. if (loadData.isDDS) {
  11002. var info = loadData.info;
  11003. var data = loadData.data;
  11004. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  11005. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  11006. }
  11007. else {
  11008. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  11009. }
  11010. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11011. // Wrap in a base texture for easy binding.
  11012. var lodTexture = new BABYLON.BaseTexture(scene);
  11013. lodTexture.isCube = true;
  11014. lodTexture._texture = glTextureFromLod;
  11015. glTextureFromLod.isReady = true;
  11016. textures.push(lodTexture);
  11017. }
  11018. texture._lodTextureHigh = textures[2];
  11019. texture._lodTextureMid = textures[1];
  11020. texture._lodTextureLow = textures[0];
  11021. if (onLoad) {
  11022. onLoad(texture);
  11023. }
  11024. };
  11025. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  11026. };
  11027. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  11028. var _this = this;
  11029. if (onLoad === void 0) { onLoad = null; }
  11030. if (onError === void 0) { onError = null; }
  11031. if (forcedExtension === void 0) { forcedExtension = null; }
  11032. var gl = this._gl;
  11033. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  11034. texture.isCube = true;
  11035. texture.url = rootUrl;
  11036. texture.generateMipMaps = !noMipmap;
  11037. if (!this._doNotHandleContextLost) {
  11038. texture._extension = forcedExtension;
  11039. texture._files = files;
  11040. }
  11041. var isKTX = false;
  11042. var isDDS = false;
  11043. var lastDot = rootUrl.lastIndexOf('.');
  11044. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  11045. if (this._textureFormatInUse) {
  11046. extension = this._textureFormatInUse;
  11047. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  11048. isKTX = true;
  11049. }
  11050. else {
  11051. isDDS = (extension === ".dds");
  11052. }
  11053. var onerror = function (request, exception) {
  11054. if (onError && request) {
  11055. onError(request.status + " " + request.statusText, exception);
  11056. }
  11057. };
  11058. if (isKTX) {
  11059. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  11060. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  11061. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  11062. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11063. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  11064. ktx.uploadLevels(_this._gl, !noMipmap);
  11065. _this.setCubeMapTextureParams(gl, loadMipmap);
  11066. texture.width = ktx.pixelWidth;
  11067. texture.height = ktx.pixelHeight;
  11068. texture.isReady = true;
  11069. }, undefined, undefined, true, onerror);
  11070. }
  11071. else if (isDDS) {
  11072. if (files && files.length === 6) {
  11073. cascadeLoadFiles(rootUrl, scene, function (imgs) {
  11074. var info;
  11075. var loadMipmap = false;
  11076. var width = 0;
  11077. for (var index = 0; index < imgs.length; index++) {
  11078. var data = imgs[index];
  11079. info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  11080. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  11081. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11082. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  11083. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  11084. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  11085. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11086. }
  11087. texture.width = info.width;
  11088. texture.height = info.height;
  11089. texture.type = info.textureType;
  11090. width = info.width;
  11091. }
  11092. _this.setCubeMapTextureParams(gl, loadMipmap);
  11093. texture.isReady = true;
  11094. if (onLoad) {
  11095. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  11096. }
  11097. }, files, onError);
  11098. }
  11099. else {
  11100. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  11101. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  11102. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  11103. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11104. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  11105. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  11106. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  11107. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11108. }
  11109. _this.setCubeMapTextureParams(gl, loadMipmap);
  11110. texture.width = info.width;
  11111. texture.height = info.height;
  11112. texture.isReady = true;
  11113. texture.type = info.textureType;
  11114. if (onLoad) {
  11115. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  11116. }
  11117. }, undefined, undefined, true, onerror);
  11118. }
  11119. }
  11120. else {
  11121. if (!files) {
  11122. throw new Error("Cannot load cubemap because files were not defined");
  11123. }
  11124. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  11125. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  11126. var height = width;
  11127. _this._prepareWorkingCanvas();
  11128. if (!_this._workingCanvas || !_this._workingContext) {
  11129. return;
  11130. }
  11131. _this._workingCanvas.width = width;
  11132. _this._workingCanvas.height = height;
  11133. var faces = [
  11134. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  11135. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  11136. ];
  11137. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11138. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  11139. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  11140. for (var index = 0; index < faces.length; index++) {
  11141. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  11142. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  11143. }
  11144. if (!noMipmap) {
  11145. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11146. }
  11147. _this.setCubeMapTextureParams(gl, !noMipmap);
  11148. texture.width = width;
  11149. texture.height = height;
  11150. texture.isReady = true;
  11151. if (format) {
  11152. texture.format = format;
  11153. }
  11154. texture.onLoadedObservable.notifyObservers(texture);
  11155. texture.onLoadedObservable.clear();
  11156. if (onLoad) {
  11157. onLoad();
  11158. }
  11159. }, files, onError);
  11160. }
  11161. this._internalTexturesCache.push(texture);
  11162. return texture;
  11163. };
  11164. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  11165. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11166. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  11167. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11168. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11169. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11170. this.resetTextureCache();
  11171. };
  11172. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  11173. if (compression === void 0) { compression = null; }
  11174. if (level === void 0) { level = 0; }
  11175. texture._bufferViewArray = data;
  11176. texture.format = format;
  11177. texture.type = type;
  11178. texture.invertY = invertY;
  11179. texture._compression = compression;
  11180. var gl = this._gl;
  11181. var textureType = this._getWebGLTextureType(type);
  11182. var internalFormat = this._getInternalFormat(format);
  11183. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  11184. var needConversion = false;
  11185. if (internalFormat === gl.RGB) {
  11186. internalFormat = gl.RGBA;
  11187. needConversion = true;
  11188. }
  11189. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11190. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11191. if (texture.width % 4 !== 0) {
  11192. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  11193. }
  11194. // Data are known to be in +X +Y +Z -X -Y -Z
  11195. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11196. var faceData = data[faceIndex];
  11197. if (compression) {
  11198. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  11199. }
  11200. else {
  11201. if (needConversion) {
  11202. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  11203. }
  11204. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  11205. }
  11206. }
  11207. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11208. if (isPot && texture.generateMipMaps && level === 0) {
  11209. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11210. }
  11211. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11212. this.resetTextureCache();
  11213. texture.isReady = true;
  11214. };
  11215. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  11216. if (compression === void 0) { compression = null; }
  11217. var gl = this._gl;
  11218. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  11219. texture.isCube = true;
  11220. texture.generateMipMaps = generateMipMaps;
  11221. texture.format = format;
  11222. texture.type = type;
  11223. if (!this._doNotHandleContextLost) {
  11224. texture._bufferViewArray = data;
  11225. }
  11226. var textureType = this._getWebGLTextureType(type);
  11227. var internalFormat = this._getInternalFormat(format);
  11228. if (internalFormat === gl.RGB) {
  11229. internalFormat = gl.RGBA;
  11230. }
  11231. var width = size;
  11232. var height = width;
  11233. texture.width = width;
  11234. texture.height = height;
  11235. // Double check on POT to generate Mips.
  11236. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11237. if (!isPot) {
  11238. generateMipMaps = false;
  11239. }
  11240. // Upload data if needed. The texture won't be ready until then.
  11241. if (data) {
  11242. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  11243. }
  11244. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  11245. // Filters
  11246. if (data && generateMipMaps) {
  11247. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11248. }
  11249. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  11250. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11251. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11252. }
  11253. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  11254. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11255. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11256. }
  11257. else {
  11258. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11259. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  11260. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  11261. }
  11262. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11263. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11264. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11265. return texture;
  11266. };
  11267. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  11268. var _this = this;
  11269. if (onLoad === void 0) { onLoad = null; }
  11270. if (onError === void 0) { onError = null; }
  11271. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11272. if (invertY === void 0) { invertY = false; }
  11273. var gl = this._gl;
  11274. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  11275. scene._addPendingData(texture);
  11276. texture.url = url;
  11277. this._internalTexturesCache.push(texture);
  11278. var onerror = function (request, exception) {
  11279. scene._removePendingData(texture);
  11280. if (onError && request) {
  11281. onError(request.status + " " + request.statusText, exception);
  11282. }
  11283. };
  11284. var internalCallback = function (data) {
  11285. var width = texture.width;
  11286. var faceDataArrays = callback(data);
  11287. if (!faceDataArrays) {
  11288. return;
  11289. }
  11290. if (mipmmapGenerator) {
  11291. var textureType = _this._getWebGLTextureType(type);
  11292. var internalFormat = _this._getInternalFormat(format);
  11293. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  11294. var needConversion = false;
  11295. if (internalFormat === gl.RGB) {
  11296. internalFormat = gl.RGBA;
  11297. needConversion = true;
  11298. }
  11299. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11300. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  11301. var mipData = mipmmapGenerator(faceDataArrays);
  11302. for (var level = 0; level < mipData.length; level++) {
  11303. var mipSize = width >> level;
  11304. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11305. var mipFaceData = mipData[level][faceIndex];
  11306. if (needConversion) {
  11307. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  11308. }
  11309. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  11310. }
  11311. }
  11312. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11313. }
  11314. else {
  11315. texture.generateMipMaps = !noMipmap;
  11316. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  11317. }
  11318. texture.isReady = true;
  11319. _this.resetTextureCache();
  11320. scene._removePendingData(texture);
  11321. if (onLoad) {
  11322. onLoad();
  11323. }
  11324. };
  11325. BABYLON.Tools.LoadFile(url, function (data) {
  11326. internalCallback(data);
  11327. }, undefined, scene.database, true, onerror);
  11328. return texture;
  11329. };
  11330. ;
  11331. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  11332. if (compression === void 0) { compression = null; }
  11333. var internalFormat = this._getInternalFormat(format);
  11334. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11335. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11336. if (!this._doNotHandleContextLost) {
  11337. texture._bufferView = data;
  11338. texture.format = format;
  11339. texture.invertY = invertY;
  11340. texture._compression = compression;
  11341. }
  11342. if (texture.width % 4 !== 0) {
  11343. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  11344. }
  11345. if (compression && data) {
  11346. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  11347. }
  11348. else {
  11349. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  11350. }
  11351. if (texture.generateMipMaps) {
  11352. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11353. }
  11354. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11355. this.resetTextureCache();
  11356. texture.isReady = true;
  11357. };
  11358. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  11359. if (compression === void 0) { compression = null; }
  11360. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  11361. texture.baseWidth = width;
  11362. texture.baseHeight = height;
  11363. texture.baseDepth = depth;
  11364. texture.width = width;
  11365. texture.height = height;
  11366. texture.depth = depth;
  11367. texture.format = format;
  11368. texture.generateMipMaps = generateMipMaps;
  11369. texture.samplingMode = samplingMode;
  11370. texture.is3D = true;
  11371. if (!this._doNotHandleContextLost) {
  11372. texture._bufferView = data;
  11373. }
  11374. this.updateRawTexture3D(texture, data, format, invertY, compression);
  11375. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11376. // Filters
  11377. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  11378. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11379. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11380. if (generateMipMaps) {
  11381. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11382. }
  11383. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11384. this._internalTexturesCache.push(texture);
  11385. return texture;
  11386. };
  11387. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  11388. var gl = this._gl;
  11389. if (!gl) {
  11390. return;
  11391. }
  11392. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  11393. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11394. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11395. if (!noMipmap && !isCompressed) {
  11396. gl.generateMipmap(gl.TEXTURE_2D);
  11397. }
  11398. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11399. this.resetTextureCache();
  11400. if (scene) {
  11401. scene._removePendingData(texture);
  11402. }
  11403. texture.onLoadedObservable.notifyObservers(texture);
  11404. texture.onLoadedObservable.clear();
  11405. };
  11406. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  11407. var _this = this;
  11408. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11409. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  11410. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  11411. var gl = this._gl;
  11412. if (!gl) {
  11413. return;
  11414. }
  11415. if (!texture._webGLTexture) {
  11416. this.resetTextureCache();
  11417. if (scene) {
  11418. scene._removePendingData(texture);
  11419. }
  11420. return;
  11421. }
  11422. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11423. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11424. texture.baseWidth = width;
  11425. texture.baseHeight = height;
  11426. texture.width = potWidth;
  11427. texture.height = potHeight;
  11428. texture.isReady = true;
  11429. if (processFunction(potWidth, potHeight, function () {
  11430. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11431. })) {
  11432. // Returning as texture needs extra async steps
  11433. return;
  11434. }
  11435. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11436. };
  11437. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  11438. // Create new RGBA data container.
  11439. var rgbaData;
  11440. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  11441. rgbaData = new Float32Array(width * height * 4);
  11442. }
  11443. else {
  11444. rgbaData = new Uint32Array(width * height * 4);
  11445. }
  11446. // Convert each pixel.
  11447. for (var x = 0; x < width; x++) {
  11448. for (var y = 0; y < height; y++) {
  11449. var index = (y * width + x) * 3;
  11450. var newIndex = (y * width + x) * 4;
  11451. // Map Old Value to new value.
  11452. rgbaData[newIndex + 0] = rgbData[index + 0];
  11453. rgbaData[newIndex + 1] = rgbData[index + 1];
  11454. rgbaData[newIndex + 2] = rgbData[index + 2];
  11455. // Add fully opaque alpha channel.
  11456. rgbaData[newIndex + 3] = 1;
  11457. }
  11458. }
  11459. return rgbaData;
  11460. };
  11461. Engine.prototype._releaseFramebufferObjects = function (texture) {
  11462. var gl = this._gl;
  11463. if (texture._framebuffer) {
  11464. gl.deleteFramebuffer(texture._framebuffer);
  11465. texture._framebuffer = null;
  11466. }
  11467. if (texture._depthStencilBuffer) {
  11468. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  11469. texture._depthStencilBuffer = null;
  11470. }
  11471. if (texture._MSAAFramebuffer) {
  11472. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  11473. texture._MSAAFramebuffer = null;
  11474. }
  11475. if (texture._MSAARenderBuffer) {
  11476. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  11477. texture._MSAARenderBuffer = null;
  11478. }
  11479. };
  11480. Engine.prototype._releaseTexture = function (texture) {
  11481. var gl = this._gl;
  11482. this._releaseFramebufferObjects(texture);
  11483. gl.deleteTexture(texture._webGLTexture);
  11484. // Unbind channels
  11485. this.unbindAllTextures();
  11486. var index = this._internalTexturesCache.indexOf(texture);
  11487. if (index !== -1) {
  11488. this._internalTexturesCache.splice(index, 1);
  11489. }
  11490. // Integrated fixed lod samplers.
  11491. if (texture._lodTextureHigh) {
  11492. texture._lodTextureHigh.dispose();
  11493. }
  11494. if (texture._lodTextureMid) {
  11495. texture._lodTextureMid.dispose();
  11496. }
  11497. if (texture._lodTextureLow) {
  11498. texture._lodTextureLow.dispose();
  11499. }
  11500. };
  11501. Engine.prototype.setProgram = function (program) {
  11502. if (this._currentProgram !== program) {
  11503. this._gl.useProgram(program);
  11504. this._currentProgram = program;
  11505. }
  11506. };
  11507. Engine.prototype.bindSamplers = function (effect) {
  11508. this.setProgram(effect.getProgram());
  11509. var samplers = effect.getSamplers();
  11510. for (var index = 0; index < samplers.length; index++) {
  11511. var uniform = effect.getUniform(samplers[index]);
  11512. this._gl.uniform1i(uniform, index);
  11513. }
  11514. this._currentEffect = null;
  11515. };
  11516. Engine.prototype.activateTextureChannel = function (textureChannel) {
  11517. if (this._activeTextureChannel !== textureChannel) {
  11518. this._gl.activeTexture(textureChannel);
  11519. this._activeTextureChannel = textureChannel;
  11520. }
  11521. };
  11522. Engine.prototype._bindTextureDirectly = function (target, texture) {
  11523. if (this._boundTexturesCache[this._activeTextureChannel] !== texture) {
  11524. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  11525. this._boundTexturesCache[this._activeTextureChannel] = texture;
  11526. }
  11527. };
  11528. Engine.prototype._bindTexture = function (channel, texture) {
  11529. if (channel < 0) {
  11530. return;
  11531. }
  11532. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11533. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  11534. };
  11535. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  11536. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  11537. };
  11538. Engine.prototype.unbindAllTextures = function () {
  11539. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  11540. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11541. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11542. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11543. if (this.webGLVersion > 1) {
  11544. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11545. }
  11546. }
  11547. };
  11548. Engine.prototype.setTexture = function (channel, uniform, texture) {
  11549. if (channel < 0) {
  11550. return;
  11551. }
  11552. if (this._setTexture(channel, texture)) {
  11553. this._gl.uniform1i(uniform, channel);
  11554. }
  11555. };
  11556. Engine.prototype._setTexture = function (channel, texture) {
  11557. // Not ready?
  11558. if (!texture) {
  11559. if (this._boundTexturesCache[channel] != null) {
  11560. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11561. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11562. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11563. if (this.webGLVersion > 1) {
  11564. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11565. }
  11566. }
  11567. return false;
  11568. }
  11569. // Video
  11570. var alreadyActivated = false;
  11571. if (texture.video) {
  11572. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11573. alreadyActivated = true;
  11574. texture.update();
  11575. }
  11576. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  11577. texture.delayLoad();
  11578. return false;
  11579. }
  11580. var internalTexture;
  11581. if (texture.isReady()) {
  11582. internalTexture = texture.getInternalTexture();
  11583. }
  11584. else if (texture.isCube) {
  11585. internalTexture = this.emptyCubeTexture;
  11586. }
  11587. else if (texture.is3D) {
  11588. internalTexture = this.emptyTexture3D;
  11589. }
  11590. else {
  11591. internalTexture = this.emptyTexture;
  11592. }
  11593. if (!alreadyActivated) {
  11594. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11595. }
  11596. if (this._boundTexturesCache[this._activeTextureChannel] === internalTexture) {
  11597. return false;
  11598. }
  11599. if (internalTexture && internalTexture.is3D) {
  11600. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture);
  11601. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11602. internalTexture._cachedWrapU = texture.wrapU;
  11603. switch (texture.wrapU) {
  11604. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11605. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11606. break;
  11607. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11608. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11609. break;
  11610. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11611. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11612. break;
  11613. }
  11614. }
  11615. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11616. internalTexture._cachedWrapV = texture.wrapV;
  11617. switch (texture.wrapV) {
  11618. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11619. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11620. break;
  11621. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11622. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11623. break;
  11624. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11625. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11626. break;
  11627. }
  11628. }
  11629. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  11630. internalTexture._cachedWrapR = texture.wrapR;
  11631. switch (texture.wrapV) {
  11632. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11633. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  11634. break;
  11635. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11636. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  11637. break;
  11638. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11639. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  11640. break;
  11641. }
  11642. }
  11643. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  11644. }
  11645. else if (internalTexture && internalTexture.isCube) {
  11646. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  11647. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  11648. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  11649. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  11650. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  11651. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  11652. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  11653. }
  11654. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  11655. }
  11656. else {
  11657. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  11658. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11659. internalTexture._cachedWrapU = texture.wrapU;
  11660. switch (texture.wrapU) {
  11661. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11662. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11663. break;
  11664. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11665. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11666. break;
  11667. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11668. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11669. break;
  11670. }
  11671. }
  11672. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11673. internalTexture._cachedWrapV = texture.wrapV;
  11674. switch (texture.wrapV) {
  11675. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11676. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11677. break;
  11678. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11679. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11680. break;
  11681. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11682. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11683. break;
  11684. }
  11685. }
  11686. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  11687. }
  11688. return true;
  11689. };
  11690. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  11691. if (channel < 0 || !uniform) {
  11692. return;
  11693. }
  11694. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  11695. this._textureUnits = new Int32Array(textures.length);
  11696. }
  11697. for (var i = 0; i < textures.length; i++) {
  11698. this._textureUnits[i] = channel + i;
  11699. }
  11700. this._gl.uniform1iv(uniform, this._textureUnits);
  11701. for (var index = 0; index < textures.length; index++) {
  11702. this._setTexture(channel + index, textures[index]);
  11703. }
  11704. };
  11705. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  11706. var internalTexture = texture.getInternalTexture();
  11707. if (!internalTexture) {
  11708. return;
  11709. }
  11710. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  11711. var value = texture.anisotropicFilteringLevel;
  11712. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  11713. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  11714. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  11715. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  11716. }
  11717. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  11718. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  11719. internalTexture._cachedAnisotropicFilteringLevel = value;
  11720. }
  11721. };
  11722. Engine.prototype.readPixels = function (x, y, width, height) {
  11723. var data = new Uint8Array(height * width * 4);
  11724. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  11725. return data;
  11726. };
  11727. /**
  11728. * Add an externaly attached data from its key.
  11729. * This method call will fail and return false, if such key already exists.
  11730. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  11731. * @param key the unique key that identifies the data
  11732. * @param data the data object to associate to the key for this Engine instance
  11733. * @return true if no such key were already present and the data was added successfully, false otherwise
  11734. */
  11735. Engine.prototype.addExternalData = function (key, data) {
  11736. if (!this._externalData) {
  11737. this._externalData = new BABYLON.StringDictionary();
  11738. }
  11739. return this._externalData.add(key, data);
  11740. };
  11741. /**
  11742. * Get an externaly attached data from its key
  11743. * @param key the unique key that identifies the data
  11744. * @return the associated data, if present (can be null), or undefined if not present
  11745. */
  11746. Engine.prototype.getExternalData = function (key) {
  11747. if (!this._externalData) {
  11748. this._externalData = new BABYLON.StringDictionary();
  11749. }
  11750. return this._externalData.get(key);
  11751. };
  11752. /**
  11753. * Get an externaly attached data from its key, create it using a factory if it's not already present
  11754. * @param key the unique key that identifies the data
  11755. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  11756. * @return the associated data, can be null if the factory returned null.
  11757. */
  11758. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  11759. if (!this._externalData) {
  11760. this._externalData = new BABYLON.StringDictionary();
  11761. }
  11762. return this._externalData.getOrAddWithFactory(key, factory);
  11763. };
  11764. /**
  11765. * Remove an externaly attached data from the Engine instance
  11766. * @param key the unique key that identifies the data
  11767. * @return true if the data was successfully removed, false if it doesn't exist
  11768. */
  11769. Engine.prototype.removeExternalData = function (key) {
  11770. if (!this._externalData) {
  11771. this._externalData = new BABYLON.StringDictionary();
  11772. }
  11773. return this._externalData.remove(key);
  11774. };
  11775. Engine.prototype.unbindAllAttributes = function () {
  11776. if (this._mustWipeVertexAttributes) {
  11777. this._mustWipeVertexAttributes = false;
  11778. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11779. this._gl.disableVertexAttribArray(i);
  11780. this._vertexAttribArraysEnabled[i] = false;
  11781. this._currentBufferPointers[i].active = false;
  11782. }
  11783. return;
  11784. }
  11785. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  11786. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  11787. continue;
  11788. }
  11789. this._gl.disableVertexAttribArray(i);
  11790. this._vertexAttribArraysEnabled[i] = false;
  11791. this._currentBufferPointers[i].active = false;
  11792. }
  11793. };
  11794. Engine.prototype.releaseEffects = function () {
  11795. for (var name in this._compiledEffects) {
  11796. this._deleteProgram(this._compiledEffects[name]._program);
  11797. }
  11798. this._compiledEffects = {};
  11799. };
  11800. // Dispose
  11801. Engine.prototype.dispose = function () {
  11802. this.hideLoadingUI();
  11803. this.stopRenderLoop();
  11804. // Release postProcesses
  11805. while (this.postProcesses.length) {
  11806. this.postProcesses[0].dispose();
  11807. }
  11808. // Empty texture
  11809. if (this._emptyTexture) {
  11810. this._releaseTexture(this._emptyTexture);
  11811. this._emptyTexture = null;
  11812. }
  11813. if (this._emptyCubeTexture) {
  11814. this._releaseTexture(this._emptyCubeTexture);
  11815. this._emptyCubeTexture = null;
  11816. }
  11817. // Rescale PP
  11818. if (this._rescalePostProcess) {
  11819. this._rescalePostProcess.dispose();
  11820. }
  11821. // Release scenes
  11822. while (this.scenes.length) {
  11823. this.scenes[0].dispose();
  11824. }
  11825. // Release audio engine
  11826. if (Engine.audioEngine) {
  11827. Engine.audioEngine.dispose();
  11828. }
  11829. // Release effects
  11830. this.releaseEffects();
  11831. // Unbind
  11832. this.unbindAllAttributes();
  11833. if (this._dummyFramebuffer) {
  11834. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  11835. }
  11836. //WebVR
  11837. this.disableVR();
  11838. // Events
  11839. if (BABYLON.Tools.IsWindowObjectExist()) {
  11840. window.removeEventListener("blur", this._onBlur);
  11841. window.removeEventListener("focus", this._onFocus);
  11842. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  11843. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  11844. if (this._renderingCanvas) {
  11845. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  11846. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  11847. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  11848. if (!this._doNotHandleContextLost) {
  11849. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  11850. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  11851. }
  11852. }
  11853. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  11854. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  11855. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  11856. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  11857. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  11858. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  11859. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  11860. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  11861. if (this._onVrDisplayConnect) {
  11862. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11863. if (this._onVrDisplayDisconnect) {
  11864. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11865. }
  11866. if (this._onVrDisplayPresentChange) {
  11867. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11868. }
  11869. this._onVrDisplayConnect = null;
  11870. this._onVrDisplayDisconnect = null;
  11871. }
  11872. }
  11873. // Remove from Instances
  11874. var index = Engine.Instances.indexOf(this);
  11875. if (index >= 0) {
  11876. Engine.Instances.splice(index, 1);
  11877. }
  11878. this._workingCanvas = null;
  11879. this._workingContext = null;
  11880. this._currentBufferPointers = [];
  11881. this._renderingCanvas = null;
  11882. this._currentProgram = null;
  11883. this.onResizeObservable.clear();
  11884. this.onCanvasBlurObservable.clear();
  11885. this.onCanvasFocusObservable.clear();
  11886. this.onCanvasPointerOutObservable.clear();
  11887. this.onBeginFrameObservable.clear();
  11888. this.onEndFrameObservable.clear();
  11889. BABYLON.Effect.ResetCache();
  11890. };
  11891. // Loading screen
  11892. Engine.prototype.displayLoadingUI = function () {
  11893. if (!BABYLON.Tools.IsWindowObjectExist()) {
  11894. return;
  11895. }
  11896. var loadingScreen = this.loadingScreen;
  11897. if (loadingScreen) {
  11898. loadingScreen.displayLoadingUI();
  11899. }
  11900. };
  11901. Engine.prototype.hideLoadingUI = function () {
  11902. if (!BABYLON.Tools.IsWindowObjectExist()) {
  11903. return;
  11904. }
  11905. var loadingScreen = this.loadingScreen;
  11906. if (loadingScreen) {
  11907. loadingScreen.hideLoadingUI();
  11908. }
  11909. };
  11910. Object.defineProperty(Engine.prototype, "loadingScreen", {
  11911. get: function () {
  11912. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  11913. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  11914. return this._loadingScreen;
  11915. },
  11916. set: function (loadingScreen) {
  11917. this._loadingScreen = loadingScreen;
  11918. },
  11919. enumerable: true,
  11920. configurable: true
  11921. });
  11922. Object.defineProperty(Engine.prototype, "loadingUIText", {
  11923. set: function (text) {
  11924. this.loadingScreen.loadingUIText = text;
  11925. },
  11926. enumerable: true,
  11927. configurable: true
  11928. });
  11929. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  11930. set: function (color) {
  11931. this.loadingScreen.loadingUIBackgroundColor = color;
  11932. },
  11933. enumerable: true,
  11934. configurable: true
  11935. });
  11936. Engine.prototype.attachContextLostEvent = function (callback) {
  11937. if (this._renderingCanvas) {
  11938. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  11939. }
  11940. };
  11941. Engine.prototype.attachContextRestoredEvent = function (callback) {
  11942. if (this._renderingCanvas) {
  11943. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  11944. }
  11945. };
  11946. Engine.prototype.getVertexShaderSource = function (program) {
  11947. var shaders = this._gl.getAttachedShaders(program);
  11948. if (!shaders) {
  11949. return null;
  11950. }
  11951. return this._gl.getShaderSource(shaders[0]);
  11952. };
  11953. Engine.prototype.getFragmentShaderSource = function (program) {
  11954. var shaders = this._gl.getAttachedShaders(program);
  11955. if (!shaders) {
  11956. return null;
  11957. }
  11958. return this._gl.getShaderSource(shaders[1]);
  11959. };
  11960. Engine.prototype.getError = function () {
  11961. return this._gl.getError();
  11962. };
  11963. // FPS
  11964. Engine.prototype.getFps = function () {
  11965. return this._fps;
  11966. };
  11967. Engine.prototype.getDeltaTime = function () {
  11968. return this._deltaTime;
  11969. };
  11970. Engine.prototype._measureFps = function () {
  11971. this._performanceMonitor.sampleFrame();
  11972. this._fps = this._performanceMonitor.averageFPS;
  11973. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  11974. };
  11975. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  11976. if (faceIndex === void 0) { faceIndex = -1; }
  11977. var gl = this._gl;
  11978. if (!this._dummyFramebuffer) {
  11979. var dummy = gl.createFramebuffer();
  11980. if (!dummy) {
  11981. throw new Error("Unable to create dummy framebuffer");
  11982. }
  11983. this._dummyFramebuffer = dummy;
  11984. }
  11985. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  11986. if (faceIndex > -1) {
  11987. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11988. }
  11989. else {
  11990. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11991. }
  11992. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  11993. var buffer;
  11994. switch (readType) {
  11995. case gl.UNSIGNED_BYTE:
  11996. buffer = new Uint8Array(4 * width * height);
  11997. readType = gl.UNSIGNED_BYTE;
  11998. break;
  11999. default:
  12000. buffer = new Float32Array(4 * width * height);
  12001. readType = gl.FLOAT;
  12002. break;
  12003. }
  12004. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  12005. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  12006. return buffer;
  12007. };
  12008. Engine.prototype._canRenderToFloatFramebuffer = function () {
  12009. if (this._webGLVersion > 1) {
  12010. return this._caps.colorBufferFloat;
  12011. }
  12012. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  12013. };
  12014. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  12015. if (this._webGLVersion > 1) {
  12016. return this._caps.colorBufferFloat;
  12017. }
  12018. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  12019. };
  12020. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  12021. Engine.prototype._canRenderToFramebuffer = function (type) {
  12022. var gl = this._gl;
  12023. //clear existing errors
  12024. while (gl.getError() !== gl.NO_ERROR) { }
  12025. var successful = true;
  12026. var texture = gl.createTexture();
  12027. gl.bindTexture(gl.TEXTURE_2D, texture);
  12028. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  12029. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12030. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12031. var fb = gl.createFramebuffer();
  12032. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  12033. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  12034. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  12035. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  12036. successful = successful && (gl.getError() === gl.NO_ERROR);
  12037. //try render by clearing frame buffer's color buffer
  12038. if (successful) {
  12039. gl.clear(gl.COLOR_BUFFER_BIT);
  12040. successful = successful && (gl.getError() === gl.NO_ERROR);
  12041. }
  12042. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  12043. if (successful) {
  12044. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  12045. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  12046. var readFormat = gl.RGBA;
  12047. var readType = gl.UNSIGNED_BYTE;
  12048. var buffer = new Uint8Array(4);
  12049. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  12050. successful = successful && (gl.getError() === gl.NO_ERROR);
  12051. }
  12052. //clean up
  12053. gl.deleteTexture(texture);
  12054. gl.deleteFramebuffer(fb);
  12055. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  12056. //clear accumulated errors
  12057. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  12058. return successful;
  12059. };
  12060. Engine.prototype._getWebGLTextureType = function (type) {
  12061. if (type === Engine.TEXTURETYPE_FLOAT) {
  12062. return this._gl.FLOAT;
  12063. }
  12064. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  12065. // Add Half Float Constant.
  12066. return this._gl.HALF_FLOAT_OES;
  12067. }
  12068. return this._gl.UNSIGNED_BYTE;
  12069. };
  12070. ;
  12071. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  12072. if (this._webGLVersion === 1) {
  12073. return this._gl.RGBA;
  12074. }
  12075. if (type === Engine.TEXTURETYPE_FLOAT) {
  12076. return this._gl.RGBA32F;
  12077. }
  12078. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  12079. return this._gl.RGBA16F;
  12080. }
  12081. return this._gl.RGBA;
  12082. };
  12083. ;
  12084. Engine.prototype.createQuery = function () {
  12085. return this._gl.createQuery();
  12086. };
  12087. Engine.prototype.deleteQuery = function (query) {
  12088. this._gl.deleteQuery(query);
  12089. return this;
  12090. };
  12091. Engine.prototype.isQueryResultAvailable = function (query) {
  12092. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  12093. };
  12094. Engine.prototype.getQueryResult = function (query) {
  12095. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  12096. };
  12097. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  12098. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  12099. this._gl.beginQuery(glAlgorithm, query);
  12100. return this;
  12101. };
  12102. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  12103. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  12104. this._gl.endQuery(glAlgorithm);
  12105. return this;
  12106. };
  12107. /* Time queries */
  12108. Engine.prototype._createTimeQuery = function () {
  12109. var timerQuery = this._caps.timerQuery;
  12110. if (timerQuery.createQueryEXT) {
  12111. return timerQuery.createQueryEXT();
  12112. }
  12113. return this.createQuery();
  12114. };
  12115. Engine.prototype._deleteTimeQuery = function (query) {
  12116. var timerQuery = this._caps.timerQuery;
  12117. if (timerQuery.deleteQueryEXT) {
  12118. timerQuery.deleteQueryEXT(query);
  12119. return;
  12120. }
  12121. this.deleteQuery(query);
  12122. };
  12123. Engine.prototype._getTimeQueryResult = function (query) {
  12124. var timerQuery = this._caps.timerQuery;
  12125. if (timerQuery.getQueryObjectEXT) {
  12126. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  12127. }
  12128. return this.getQueryResult(query);
  12129. };
  12130. Engine.prototype._getTimeQueryAvailability = function (query) {
  12131. var timerQuery = this._caps.timerQuery;
  12132. if (timerQuery.getQueryObjectEXT) {
  12133. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  12134. }
  12135. return this.isQueryResultAvailable(query);
  12136. };
  12137. Engine.prototype.startTimeQuery = function () {
  12138. var timerQuery = this._caps.timerQuery;
  12139. if (!timerQuery) {
  12140. return null;
  12141. }
  12142. var token = new BABYLON._TimeToken();
  12143. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  12144. if (this._caps.canUseTimestampForTimerQuery) {
  12145. token._startTimeQuery = this._createTimeQuery();
  12146. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  12147. }
  12148. else {
  12149. if (this._currentNonTimestampToken) {
  12150. return this._currentNonTimestampToken;
  12151. }
  12152. token._timeElapsedQuery = this._createTimeQuery();
  12153. if (timerQuery.beginQueryEXT) {
  12154. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  12155. }
  12156. else {
  12157. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  12158. }
  12159. this._currentNonTimestampToken = token;
  12160. }
  12161. return token;
  12162. };
  12163. Engine.prototype.endTimeQuery = function (token) {
  12164. var timerQuery = this._caps.timerQuery;
  12165. if (!timerQuery || !token) {
  12166. return -1;
  12167. }
  12168. if (this._caps.canUseTimestampForTimerQuery) {
  12169. if (!token._startTimeQuery) {
  12170. return -1;
  12171. }
  12172. if (!token._endTimeQuery) {
  12173. token._endTimeQuery = this._createTimeQuery();
  12174. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  12175. }
  12176. }
  12177. else if (!token._timeElapsedQueryEnded) {
  12178. if (!token._timeElapsedQuery) {
  12179. return -1;
  12180. }
  12181. if (timerQuery.endQueryEXT) {
  12182. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  12183. }
  12184. else {
  12185. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  12186. }
  12187. token._timeElapsedQueryEnded = true;
  12188. }
  12189. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  12190. var available = false;
  12191. if (token._endTimeQuery) {
  12192. available = this._getTimeQueryAvailability(token._endTimeQuery);
  12193. }
  12194. else if (token._timeElapsedQuery) {
  12195. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  12196. }
  12197. if (available && !disjoint) {
  12198. var result = 0;
  12199. if (this._caps.canUseTimestampForTimerQuery) {
  12200. if (!token._startTimeQuery || !token._endTimeQuery) {
  12201. return -1;
  12202. }
  12203. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  12204. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  12205. result = timeEnd - timeStart;
  12206. this._deleteTimeQuery(token._startTimeQuery);
  12207. this._deleteTimeQuery(token._endTimeQuery);
  12208. token._startTimeQuery = null;
  12209. token._endTimeQuery = null;
  12210. }
  12211. else {
  12212. if (!token._timeElapsedQuery) {
  12213. return -1;
  12214. }
  12215. result = this._getTimeQueryResult(token._timeElapsedQuery);
  12216. this._deleteTimeQuery(token._timeElapsedQuery);
  12217. token._timeElapsedQuery = null;
  12218. token._timeElapsedQueryEnded = false;
  12219. this._currentNonTimestampToken = null;
  12220. }
  12221. return result;
  12222. }
  12223. return -1;
  12224. };
  12225. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  12226. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  12227. };
  12228. // Transform feedback
  12229. Engine.prototype.createTransformFeedback = function () {
  12230. return this._gl.createTransformFeedback();
  12231. };
  12232. Engine.prototype.deleteTransformFeedback = function (value) {
  12233. this._gl.deleteTransformFeedback(value);
  12234. };
  12235. Engine.prototype.bindTransformFeedback = function (value) {
  12236. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  12237. };
  12238. Engine.prototype.beginTransformFeedback = function (usePoints) {
  12239. if (usePoints === void 0) { usePoints = true; }
  12240. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  12241. };
  12242. Engine.prototype.endTransformFeedback = function () {
  12243. this._gl.endTransformFeedback();
  12244. };
  12245. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  12246. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  12247. };
  12248. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  12249. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  12250. };
  12251. // Statics
  12252. Engine.isSupported = function () {
  12253. try {
  12254. var tempcanvas = document.createElement("canvas");
  12255. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  12256. return gl != null && !!window.WebGLRenderingContext;
  12257. }
  12258. catch (e) {
  12259. return false;
  12260. }
  12261. };
  12262. Engine.Instances = new Array();
  12263. // Const statics
  12264. Engine._ALPHA_DISABLE = 0;
  12265. Engine._ALPHA_ADD = 1;
  12266. Engine._ALPHA_COMBINE = 2;
  12267. Engine._ALPHA_SUBTRACT = 3;
  12268. Engine._ALPHA_MULTIPLY = 4;
  12269. Engine._ALPHA_MAXIMIZED = 5;
  12270. Engine._ALPHA_ONEONE = 6;
  12271. Engine._ALPHA_PREMULTIPLIED = 7;
  12272. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  12273. Engine._ALPHA_INTERPOLATE = 9;
  12274. Engine._ALPHA_SCREENMODE = 10;
  12275. Engine._DELAYLOADSTATE_NONE = 0;
  12276. Engine._DELAYLOADSTATE_LOADED = 1;
  12277. Engine._DELAYLOADSTATE_LOADING = 2;
  12278. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  12279. Engine._TEXTUREFORMAT_ALPHA = 0;
  12280. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  12281. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  12282. Engine._TEXTUREFORMAT_RGB = 4;
  12283. Engine._TEXTUREFORMAT_RGBA = 5;
  12284. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  12285. Engine._TEXTURETYPE_FLOAT = 1;
  12286. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  12287. // Depht or Stencil test Constants.
  12288. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  12289. 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.
  12290. 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.
  12291. 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.
  12292. 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.
  12293. 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.
  12294. 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.
  12295. 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.
  12296. // Stencil Actions Constants.
  12297. Engine._KEEP = 0x1E00;
  12298. Engine._REPLACE = 0x1E01;
  12299. Engine._INCR = 0x1E02;
  12300. Engine._DECR = 0x1E03;
  12301. Engine._INVERT = 0x150A;
  12302. Engine._INCR_WRAP = 0x8507;
  12303. Engine._DECR_WRAP = 0x8508;
  12304. // Texture rescaling mode
  12305. Engine._SCALEMODE_FLOOR = 1;
  12306. Engine._SCALEMODE_NEAREST = 2;
  12307. Engine._SCALEMODE_CEILING = 3;
  12308. // Updatable statics so stick with vars here
  12309. Engine.CollisionsEpsilon = 0.001;
  12310. Engine.CodeRepository = "src/";
  12311. Engine.ShadersRepository = "src/Shaders/";
  12312. return Engine;
  12313. }());
  12314. BABYLON.Engine = Engine;
  12315. })(BABYLON || (BABYLON = {}));
  12316. //# sourceMappingURL=babylon.engine.js.map
  12317. var BABYLON;
  12318. (function (BABYLON) {
  12319. /**
  12320. * Node is the basic class for all scene objects (Mesh, Light Camera).
  12321. */
  12322. var Node = /** @class */ (function () {
  12323. /**
  12324. * @constructor
  12325. * @param {string} name - the name and id to be given to this node
  12326. * @param {BABYLON.Scene} the scene this node will be added to
  12327. */
  12328. function Node(name, scene) {
  12329. if (scene === void 0) { scene = null; }
  12330. this.state = "";
  12331. this.metadata = null;
  12332. this.doNotSerialize = false;
  12333. this.animations = new Array();
  12334. this._ranges = {};
  12335. this._isEnabled = true;
  12336. this._isReady = true;
  12337. this._currentRenderId = -1;
  12338. this._parentRenderId = -1;
  12339. /**
  12340. * An event triggered when the mesh is disposed.
  12341. * @type {BABYLON.Observable}
  12342. */
  12343. this.onDisposeObservable = new BABYLON.Observable();
  12344. // Behaviors
  12345. this._behaviors = new Array();
  12346. this.name = name;
  12347. this.id = name;
  12348. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  12349. this.uniqueId = this._scene.getUniqueId();
  12350. this._initCache();
  12351. }
  12352. Object.defineProperty(Node.prototype, "parent", {
  12353. get: function () {
  12354. return this._parentNode;
  12355. },
  12356. set: function (parent) {
  12357. if (this._parentNode === parent) {
  12358. return;
  12359. }
  12360. if (this._parentNode) {
  12361. var index = this._parentNode._children.indexOf(this);
  12362. if (index !== -1) {
  12363. this._parentNode._children.splice(index, 1);
  12364. }
  12365. }
  12366. this._parentNode = parent;
  12367. if (this._parentNode) {
  12368. if (!this._parentNode._children) {
  12369. this._parentNode._children = new Array();
  12370. }
  12371. this._parentNode._children.push(this);
  12372. }
  12373. },
  12374. enumerable: true,
  12375. configurable: true
  12376. });
  12377. Node.prototype.getClassName = function () {
  12378. return "Node";
  12379. };
  12380. Object.defineProperty(Node.prototype, "onDispose", {
  12381. set: function (callback) {
  12382. if (this._onDisposeObserver) {
  12383. this.onDisposeObservable.remove(this._onDisposeObserver);
  12384. }
  12385. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  12386. },
  12387. enumerable: true,
  12388. configurable: true
  12389. });
  12390. Node.prototype.getScene = function () {
  12391. return this._scene;
  12392. };
  12393. Node.prototype.getEngine = function () {
  12394. return this._scene.getEngine();
  12395. };
  12396. Node.prototype.addBehavior = function (behavior) {
  12397. var _this = this;
  12398. var index = this._behaviors.indexOf(behavior);
  12399. if (index !== -1) {
  12400. return this;
  12401. }
  12402. behavior.init();
  12403. if (this._scene.isLoading) {
  12404. // We defer the attach when the scene will be loaded
  12405. var observer = this._scene.onDataLoadedObservable.add(function () {
  12406. behavior.attach(_this);
  12407. _this._scene.onDataLoadedObservable.remove(observer);
  12408. });
  12409. }
  12410. else {
  12411. behavior.attach(this);
  12412. }
  12413. this._behaviors.push(behavior);
  12414. return this;
  12415. };
  12416. Node.prototype.removeBehavior = function (behavior) {
  12417. var index = this._behaviors.indexOf(behavior);
  12418. if (index === -1) {
  12419. return this;
  12420. }
  12421. this._behaviors[index].detach();
  12422. this._behaviors.splice(index, 1);
  12423. return this;
  12424. };
  12425. Object.defineProperty(Node.prototype, "behaviors", {
  12426. get: function () {
  12427. return this._behaviors;
  12428. },
  12429. enumerable: true,
  12430. configurable: true
  12431. });
  12432. Node.prototype.getBehaviorByName = function (name) {
  12433. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12434. var behavior = _a[_i];
  12435. if (behavior.name === name) {
  12436. return behavior;
  12437. }
  12438. }
  12439. return null;
  12440. };
  12441. // override it in derived class
  12442. Node.prototype.getWorldMatrix = function () {
  12443. return BABYLON.Matrix.Identity();
  12444. };
  12445. // override it in derived class if you add new variables to the cache
  12446. // and call the parent class method
  12447. Node.prototype._initCache = function () {
  12448. this._cache = {};
  12449. this._cache.parent = undefined;
  12450. };
  12451. Node.prototype.updateCache = function (force) {
  12452. if (!force && this.isSynchronized())
  12453. return;
  12454. this._cache.parent = this.parent;
  12455. this._updateCache();
  12456. };
  12457. // override it in derived class if you add new variables to the cache
  12458. // and call the parent class method if !ignoreParentClass
  12459. Node.prototype._updateCache = function (ignoreParentClass) {
  12460. };
  12461. // override it in derived class if you add new variables to the cache
  12462. Node.prototype._isSynchronized = function () {
  12463. return true;
  12464. };
  12465. Node.prototype._markSyncedWithParent = function () {
  12466. if (this.parent) {
  12467. this._parentRenderId = this.parent._currentRenderId;
  12468. }
  12469. };
  12470. Node.prototype.isSynchronizedWithParent = function () {
  12471. if (!this.parent) {
  12472. return true;
  12473. }
  12474. if (this._parentRenderId !== this.parent._currentRenderId) {
  12475. return false;
  12476. }
  12477. return this.parent.isSynchronized();
  12478. };
  12479. Node.prototype.isSynchronized = function (updateCache) {
  12480. var check = this.hasNewParent();
  12481. check = check || !this.isSynchronizedWithParent();
  12482. check = check || !this._isSynchronized();
  12483. if (updateCache)
  12484. this.updateCache(true);
  12485. return !check;
  12486. };
  12487. Node.prototype.hasNewParent = function (update) {
  12488. if (this._cache.parent === this.parent)
  12489. return false;
  12490. if (update)
  12491. this._cache.parent = this.parent;
  12492. return true;
  12493. };
  12494. /**
  12495. * Is this node ready to be used/rendered
  12496. * @return {boolean} is it ready
  12497. */
  12498. Node.prototype.isReady = function () {
  12499. return this._isReady;
  12500. };
  12501. /**
  12502. * Is this node enabled.
  12503. * If the node has a parent and is enabled, the parent will be inspected as well.
  12504. * @return {boolean} whether this node (and its parent) is enabled.
  12505. * @see setEnabled
  12506. */
  12507. Node.prototype.isEnabled = function () {
  12508. if (!this._isEnabled) {
  12509. return false;
  12510. }
  12511. if (this.parent) {
  12512. return this.parent.isEnabled();
  12513. }
  12514. return true;
  12515. };
  12516. /**
  12517. * Set the enabled state of this node.
  12518. * @param {boolean} value - the new enabled state
  12519. * @see isEnabled
  12520. */
  12521. Node.prototype.setEnabled = function (value) {
  12522. this._isEnabled = value;
  12523. };
  12524. /**
  12525. * Is this node a descendant of the given node.
  12526. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  12527. * @param {BABYLON.Node} ancestor - The parent node to inspect
  12528. * @see parent
  12529. */
  12530. Node.prototype.isDescendantOf = function (ancestor) {
  12531. if (this.parent) {
  12532. if (this.parent === ancestor) {
  12533. return true;
  12534. }
  12535. return this.parent.isDescendantOf(ancestor);
  12536. }
  12537. return false;
  12538. };
  12539. /**
  12540. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  12541. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  12542. * @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.
  12543. * @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.
  12544. */
  12545. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  12546. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  12547. if (!this._children) {
  12548. return;
  12549. }
  12550. for (var index = 0; index < this._children.length; index++) {
  12551. var item = this._children[index];
  12552. if (!predicate || predicate(item)) {
  12553. results.push(item);
  12554. }
  12555. if (!directDescendantsOnly) {
  12556. item._getDescendants(results, false, predicate);
  12557. }
  12558. }
  12559. };
  12560. /**
  12561. * Will return all nodes that have this node as ascendant.
  12562. * @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.
  12563. * @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.
  12564. * @return {BABYLON.Node[]} all children nodes of all types.
  12565. */
  12566. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  12567. var results = new Array();
  12568. this._getDescendants(results, directDescendantsOnly, predicate);
  12569. return results;
  12570. };
  12571. /**
  12572. * Get all child-meshes of this node.
  12573. */
  12574. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  12575. var results = [];
  12576. this._getDescendants(results, directDescendantsOnly, function (node) {
  12577. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  12578. });
  12579. return results;
  12580. };
  12581. /**
  12582. * Get all child-transformNodes of this node.
  12583. */
  12584. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  12585. var results = [];
  12586. this._getDescendants(results, directDescendantsOnly, function (node) {
  12587. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  12588. });
  12589. return results;
  12590. };
  12591. /**
  12592. * Get all direct children of this node.
  12593. */
  12594. Node.prototype.getChildren = function (predicate) {
  12595. return this.getDescendants(true, predicate);
  12596. };
  12597. Node.prototype._setReady = function (state) {
  12598. if (state === this._isReady) {
  12599. return;
  12600. }
  12601. if (!state) {
  12602. this._isReady = false;
  12603. return;
  12604. }
  12605. this._isReady = true;
  12606. if (this.onReady) {
  12607. this.onReady(this);
  12608. }
  12609. };
  12610. Node.prototype.getAnimationByName = function (name) {
  12611. for (var i = 0; i < this.animations.length; i++) {
  12612. var animation = this.animations[i];
  12613. if (animation.name === name) {
  12614. return animation;
  12615. }
  12616. }
  12617. return null;
  12618. };
  12619. Node.prototype.createAnimationRange = function (name, from, to) {
  12620. // check name not already in use
  12621. if (!this._ranges[name]) {
  12622. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  12623. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12624. if (this.animations[i]) {
  12625. this.animations[i].createRange(name, from, to);
  12626. }
  12627. }
  12628. }
  12629. };
  12630. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  12631. if (deleteFrames === void 0) { deleteFrames = true; }
  12632. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12633. if (this.animations[i]) {
  12634. this.animations[i].deleteRange(name, deleteFrames);
  12635. }
  12636. }
  12637. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  12638. };
  12639. Node.prototype.getAnimationRange = function (name) {
  12640. return this._ranges[name];
  12641. };
  12642. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  12643. var range = this.getAnimationRange(name);
  12644. if (!range) {
  12645. return;
  12646. }
  12647. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  12648. };
  12649. Node.prototype.serializeAnimationRanges = function () {
  12650. var serializationRanges = [];
  12651. for (var name in this._ranges) {
  12652. var localRange = this._ranges[name];
  12653. if (!localRange) {
  12654. continue;
  12655. }
  12656. var range = {};
  12657. range.name = name;
  12658. range.from = localRange.from;
  12659. range.to = localRange.to;
  12660. serializationRanges.push(range);
  12661. }
  12662. return serializationRanges;
  12663. };
  12664. // override it in derived class
  12665. Node.prototype.computeWorldMatrix = function (force) {
  12666. return BABYLON.Matrix.Identity();
  12667. };
  12668. Node.prototype.dispose = function () {
  12669. this.parent = null;
  12670. // Callback
  12671. this.onDisposeObservable.notifyObservers(this);
  12672. this.onDisposeObservable.clear();
  12673. // Behaviors
  12674. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12675. var behavior = _a[_i];
  12676. behavior.detach();
  12677. }
  12678. this._behaviors = [];
  12679. };
  12680. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  12681. if (parsedNode.ranges) {
  12682. for (var index = 0; index < parsedNode.ranges.length; index++) {
  12683. var data = parsedNode.ranges[index];
  12684. node.createAnimationRange(data.name, data.from, data.to);
  12685. }
  12686. }
  12687. };
  12688. __decorate([
  12689. BABYLON.serialize()
  12690. ], Node.prototype, "name", void 0);
  12691. __decorate([
  12692. BABYLON.serialize()
  12693. ], Node.prototype, "id", void 0);
  12694. __decorate([
  12695. BABYLON.serialize()
  12696. ], Node.prototype, "uniqueId", void 0);
  12697. __decorate([
  12698. BABYLON.serialize()
  12699. ], Node.prototype, "state", void 0);
  12700. __decorate([
  12701. BABYLON.serialize()
  12702. ], Node.prototype, "metadata", void 0);
  12703. return Node;
  12704. }());
  12705. BABYLON.Node = Node;
  12706. })(BABYLON || (BABYLON = {}));
  12707. //# sourceMappingURL=babylon.node.js.map
  12708. var BABYLON;
  12709. (function (BABYLON) {
  12710. var BoundingSphere = /** @class */ (function () {
  12711. function BoundingSphere(minimum, maximum) {
  12712. this.minimum = minimum;
  12713. this.maximum = maximum;
  12714. this._tempRadiusVector = BABYLON.Vector3.Zero();
  12715. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  12716. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  12717. this.radius = distance * 0.5;
  12718. this.centerWorld = BABYLON.Vector3.Zero();
  12719. this._update(BABYLON.Matrix.Identity());
  12720. }
  12721. // Methods
  12722. BoundingSphere.prototype._update = function (world) {
  12723. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  12724. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  12725. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  12726. };
  12727. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  12728. for (var i = 0; i < 6; i++) {
  12729. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  12730. return false;
  12731. }
  12732. return true;
  12733. };
  12734. BoundingSphere.prototype.intersectsPoint = function (point) {
  12735. var x = this.centerWorld.x - point.x;
  12736. var y = this.centerWorld.y - point.y;
  12737. var z = this.centerWorld.z - point.z;
  12738. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12739. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  12740. return false;
  12741. return true;
  12742. };
  12743. // Statics
  12744. BoundingSphere.Intersects = function (sphere0, sphere1) {
  12745. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  12746. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  12747. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  12748. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12749. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  12750. return false;
  12751. return true;
  12752. };
  12753. return BoundingSphere;
  12754. }());
  12755. BABYLON.BoundingSphere = BoundingSphere;
  12756. })(BABYLON || (BABYLON = {}));
  12757. //# sourceMappingURL=babylon.boundingSphere.js.map
  12758. var BABYLON;
  12759. (function (BABYLON) {
  12760. var BoundingBox = /** @class */ (function () {
  12761. function BoundingBox(minimum, maximum) {
  12762. this.minimum = minimum;
  12763. this.maximum = maximum;
  12764. this.vectors = new Array();
  12765. this.vectorsWorld = new Array();
  12766. // Bounding vectors
  12767. this.vectors.push(this.minimum.clone());
  12768. this.vectors.push(this.maximum.clone());
  12769. this.vectors.push(this.minimum.clone());
  12770. this.vectors[2].x = this.maximum.x;
  12771. this.vectors.push(this.minimum.clone());
  12772. this.vectors[3].y = this.maximum.y;
  12773. this.vectors.push(this.minimum.clone());
  12774. this.vectors[4].z = this.maximum.z;
  12775. this.vectors.push(this.maximum.clone());
  12776. this.vectors[5].z = this.minimum.z;
  12777. this.vectors.push(this.maximum.clone());
  12778. this.vectors[6].x = this.minimum.x;
  12779. this.vectors.push(this.maximum.clone());
  12780. this.vectors[7].y = this.minimum.y;
  12781. // OBB
  12782. this.center = this.maximum.add(this.minimum).scale(0.5);
  12783. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  12784. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  12785. // World
  12786. for (var index = 0; index < this.vectors.length; index++) {
  12787. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  12788. }
  12789. this.minimumWorld = BABYLON.Vector3.Zero();
  12790. this.maximumWorld = BABYLON.Vector3.Zero();
  12791. this.centerWorld = BABYLON.Vector3.Zero();
  12792. this.extendSizeWorld = BABYLON.Vector3.Zero();
  12793. this._update(BABYLON.Matrix.Identity());
  12794. }
  12795. // Methods
  12796. BoundingBox.prototype.getWorldMatrix = function () {
  12797. return this._worldMatrix;
  12798. };
  12799. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  12800. this._worldMatrix.copyFrom(matrix);
  12801. return this;
  12802. };
  12803. BoundingBox.prototype._update = function (world) {
  12804. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  12805. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  12806. for (var index = 0; index < this.vectors.length; index++) {
  12807. var v = this.vectorsWorld[index];
  12808. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  12809. if (v.x < this.minimumWorld.x)
  12810. this.minimumWorld.x = v.x;
  12811. if (v.y < this.minimumWorld.y)
  12812. this.minimumWorld.y = v.y;
  12813. if (v.z < this.minimumWorld.z)
  12814. this.minimumWorld.z = v.z;
  12815. if (v.x > this.maximumWorld.x)
  12816. this.maximumWorld.x = v.x;
  12817. if (v.y > this.maximumWorld.y)
  12818. this.maximumWorld.y = v.y;
  12819. if (v.z > this.maximumWorld.z)
  12820. this.maximumWorld.z = v.z;
  12821. }
  12822. // Extend
  12823. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  12824. this.extendSizeWorld.scaleInPlace(0.5);
  12825. // OBB
  12826. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  12827. this.centerWorld.scaleInPlace(0.5);
  12828. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  12829. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  12830. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  12831. this._worldMatrix = world;
  12832. };
  12833. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  12834. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  12835. };
  12836. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12837. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  12838. };
  12839. BoundingBox.prototype.intersectsPoint = function (point) {
  12840. var delta = -BABYLON.Epsilon;
  12841. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  12842. return false;
  12843. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  12844. return false;
  12845. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  12846. return false;
  12847. return true;
  12848. };
  12849. BoundingBox.prototype.intersectsSphere = function (sphere) {
  12850. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  12851. };
  12852. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  12853. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  12854. return false;
  12855. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  12856. return false;
  12857. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  12858. return false;
  12859. return true;
  12860. };
  12861. // Statics
  12862. BoundingBox.Intersects = function (box0, box1) {
  12863. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  12864. return false;
  12865. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  12866. return false;
  12867. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  12868. return false;
  12869. return true;
  12870. };
  12871. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  12872. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  12873. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  12874. return (num <= (sphereRadius * sphereRadius));
  12875. };
  12876. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  12877. for (var p = 0; p < 6; p++) {
  12878. for (var i = 0; i < 8; i++) {
  12879. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12880. return false;
  12881. }
  12882. }
  12883. }
  12884. return true;
  12885. };
  12886. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  12887. for (var p = 0; p < 6; p++) {
  12888. var inCount = 8;
  12889. for (var i = 0; i < 8; i++) {
  12890. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12891. --inCount;
  12892. }
  12893. else {
  12894. break;
  12895. }
  12896. }
  12897. if (inCount === 0)
  12898. return false;
  12899. }
  12900. return true;
  12901. };
  12902. return BoundingBox;
  12903. }());
  12904. BABYLON.BoundingBox = BoundingBox;
  12905. })(BABYLON || (BABYLON = {}));
  12906. //# sourceMappingURL=babylon.boundingBox.js.map
  12907. var BABYLON;
  12908. (function (BABYLON) {
  12909. var computeBoxExtents = function (axis, box) {
  12910. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  12911. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  12912. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  12913. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  12914. var r = r0 + r1 + r2;
  12915. return {
  12916. min: p - r,
  12917. max: p + r
  12918. };
  12919. };
  12920. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  12921. var axisOverlap = function (axis, box0, box1) {
  12922. var result0 = computeBoxExtents(axis, box0);
  12923. var result1 = computeBoxExtents(axis, box1);
  12924. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  12925. };
  12926. var BoundingInfo = /** @class */ (function () {
  12927. function BoundingInfo(minimum, maximum) {
  12928. this.minimum = minimum;
  12929. this.maximum = maximum;
  12930. this._isLocked = false;
  12931. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  12932. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  12933. }
  12934. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  12935. get: function () {
  12936. return this._isLocked;
  12937. },
  12938. set: function (value) {
  12939. this._isLocked = value;
  12940. },
  12941. enumerable: true,
  12942. configurable: true
  12943. });
  12944. // Methods
  12945. BoundingInfo.prototype.update = function (world) {
  12946. if (this._isLocked) {
  12947. return;
  12948. }
  12949. this.boundingBox._update(world);
  12950. this.boundingSphere._update(world);
  12951. };
  12952. /**
  12953. * Recreate the bounding info to be centered around a specific point given a specific extend.
  12954. * @param center New center of the bounding info
  12955. * @param extend New extend of the bounding info
  12956. */
  12957. BoundingInfo.prototype.centerOn = function (center, extend) {
  12958. this.minimum = center.subtract(extend);
  12959. this.maximum = center.add(extend);
  12960. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  12961. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  12962. return this;
  12963. };
  12964. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  12965. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  12966. return false;
  12967. return this.boundingBox.isInFrustum(frustumPlanes);
  12968. };
  12969. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  12970. /**
  12971. * Gets the world distance between the min and max points of the bounding box
  12972. */
  12973. get: function () {
  12974. var boundingBox = this.boundingBox;
  12975. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  12976. return size.length();
  12977. },
  12978. enumerable: true,
  12979. configurable: true
  12980. });
  12981. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12982. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  12983. };
  12984. BoundingInfo.prototype._checkCollision = function (collider) {
  12985. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  12986. };
  12987. BoundingInfo.prototype.intersectsPoint = function (point) {
  12988. if (!this.boundingSphere.centerWorld) {
  12989. return false;
  12990. }
  12991. if (!this.boundingSphere.intersectsPoint(point)) {
  12992. return false;
  12993. }
  12994. if (!this.boundingBox.intersectsPoint(point)) {
  12995. return false;
  12996. }
  12997. return true;
  12998. };
  12999. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  13000. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  13001. return false;
  13002. }
  13003. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  13004. return false;
  13005. }
  13006. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  13007. return false;
  13008. }
  13009. if (!precise) {
  13010. return true;
  13011. }
  13012. var box0 = this.boundingBox;
  13013. var box1 = boundingInfo.boundingBox;
  13014. if (!axisOverlap(box0.directions[0], box0, box1))
  13015. return false;
  13016. if (!axisOverlap(box0.directions[1], box0, box1))
  13017. return false;
  13018. if (!axisOverlap(box0.directions[2], box0, box1))
  13019. return false;
  13020. if (!axisOverlap(box1.directions[0], box0, box1))
  13021. return false;
  13022. if (!axisOverlap(box1.directions[1], box0, box1))
  13023. return false;
  13024. if (!axisOverlap(box1.directions[2], box0, box1))
  13025. return false;
  13026. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  13027. return false;
  13028. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  13029. return false;
  13030. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  13031. return false;
  13032. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  13033. return false;
  13034. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  13035. return false;
  13036. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  13037. return false;
  13038. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  13039. return false;
  13040. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  13041. return false;
  13042. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  13043. return false;
  13044. return true;
  13045. };
  13046. return BoundingInfo;
  13047. }());
  13048. BABYLON.BoundingInfo = BoundingInfo;
  13049. })(BABYLON || (BABYLON = {}));
  13050. //# sourceMappingURL=babylon.boundingInfo.js.map
  13051. var BABYLON;
  13052. (function (BABYLON) {
  13053. var TransformNode = /** @class */ (function (_super) {
  13054. __extends(TransformNode, _super);
  13055. function TransformNode(name, scene, isPure) {
  13056. if (scene === void 0) { scene = null; }
  13057. if (isPure === void 0) { isPure = true; }
  13058. var _this = _super.call(this, name, scene) || this;
  13059. // Properties
  13060. _this._rotation = BABYLON.Vector3.Zero();
  13061. _this._scaling = BABYLON.Vector3.One();
  13062. _this._isDirty = false;
  13063. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  13064. _this.scalingDeterminant = 1;
  13065. _this.infiniteDistance = false;
  13066. _this.position = BABYLON.Vector3.Zero();
  13067. _this._localWorld = BABYLON.Matrix.Zero();
  13068. _this._worldMatrix = BABYLON.Matrix.Zero();
  13069. _this._absolutePosition = BABYLON.Vector3.Zero();
  13070. _this._pivotMatrix = BABYLON.Matrix.Identity();
  13071. _this._postMultiplyPivotMatrix = false;
  13072. _this._isWorldMatrixFrozen = false;
  13073. /**
  13074. * An event triggered after the world matrix is updated
  13075. * @type {BABYLON.Observable}
  13076. */
  13077. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  13078. _this._nonUniformScaling = false;
  13079. if (isPure) {
  13080. _this.getScene().addTransformNode(_this);
  13081. }
  13082. return _this;
  13083. }
  13084. Object.defineProperty(TransformNode.prototype, "rotation", {
  13085. /**
  13086. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  13087. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  13088. * Default : (0.0, 0.0, 0.0)
  13089. */
  13090. get: function () {
  13091. return this._rotation;
  13092. },
  13093. set: function (newRotation) {
  13094. this._rotation = newRotation;
  13095. },
  13096. enumerable: true,
  13097. configurable: true
  13098. });
  13099. Object.defineProperty(TransformNode.prototype, "scaling", {
  13100. /**
  13101. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  13102. * Default : (1.0, 1.0, 1.0)
  13103. */
  13104. get: function () {
  13105. return this._scaling;
  13106. },
  13107. /**
  13108. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  13109. * Default : (1.0, 1.0, 1.0)
  13110. */
  13111. set: function (newScaling) {
  13112. this._scaling = newScaling;
  13113. },
  13114. enumerable: true,
  13115. configurable: true
  13116. });
  13117. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  13118. /**
  13119. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  13120. * It's null by default.
  13121. * 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)
  13122. */
  13123. get: function () {
  13124. return this._rotationQuaternion;
  13125. },
  13126. set: function (quaternion) {
  13127. this._rotationQuaternion = quaternion;
  13128. //reset the rotation vector.
  13129. if (quaternion && this.rotation.length()) {
  13130. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  13131. }
  13132. },
  13133. enumerable: true,
  13134. configurable: true
  13135. });
  13136. /**
  13137. * Returns the latest update of the World matrix
  13138. * Returns a Matrix.
  13139. */
  13140. TransformNode.prototype.getWorldMatrix = function () {
  13141. if (this._currentRenderId !== this.getScene().getRenderId()) {
  13142. this.computeWorldMatrix();
  13143. }
  13144. return this._worldMatrix;
  13145. };
  13146. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  13147. /**
  13148. * Returns directly the latest state of the mesh World matrix.
  13149. * A Matrix is returned.
  13150. */
  13151. get: function () {
  13152. return this._worldMatrix;
  13153. },
  13154. enumerable: true,
  13155. configurable: true
  13156. });
  13157. /**
  13158. * Copies the paramater passed Matrix into the mesh Pose matrix.
  13159. * Returns the AbstractMesh.
  13160. */
  13161. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  13162. this._poseMatrix.copyFrom(matrix);
  13163. return this;
  13164. };
  13165. /**
  13166. * Returns the mesh Pose matrix.
  13167. * Returned object : Matrix
  13168. */
  13169. TransformNode.prototype.getPoseMatrix = function () {
  13170. return this._poseMatrix;
  13171. };
  13172. TransformNode.prototype._isSynchronized = function () {
  13173. if (this._isDirty) {
  13174. return false;
  13175. }
  13176. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  13177. return false;
  13178. if (this._cache.pivotMatrixUpdated) {
  13179. return false;
  13180. }
  13181. if (this.infiniteDistance) {
  13182. return false;
  13183. }
  13184. if (!this._cache.position.equals(this.position))
  13185. return false;
  13186. if (this.rotationQuaternion) {
  13187. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  13188. return false;
  13189. }
  13190. if (!this._cache.rotation.equals(this.rotation))
  13191. return false;
  13192. if (!this._cache.scaling.equals(this.scaling))
  13193. return false;
  13194. return true;
  13195. };
  13196. TransformNode.prototype._initCache = function () {
  13197. _super.prototype._initCache.call(this);
  13198. this._cache.localMatrixUpdated = false;
  13199. this._cache.position = BABYLON.Vector3.Zero();
  13200. this._cache.scaling = BABYLON.Vector3.Zero();
  13201. this._cache.rotation = BABYLON.Vector3.Zero();
  13202. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  13203. this._cache.billboardMode = -1;
  13204. };
  13205. TransformNode.prototype.markAsDirty = function (property) {
  13206. if (property === "rotation") {
  13207. this.rotationQuaternion = null;
  13208. }
  13209. this._currentRenderId = Number.MAX_VALUE;
  13210. this._isDirty = true;
  13211. return this;
  13212. };
  13213. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  13214. /**
  13215. * Returns the current mesh absolute position.
  13216. * Retuns a Vector3.
  13217. */
  13218. get: function () {
  13219. return this._absolutePosition;
  13220. },
  13221. enumerable: true,
  13222. configurable: true
  13223. });
  13224. /**
  13225. * Sets a new pivot matrix to the mesh.
  13226. * Returns the AbstractMesh.
  13227. */
  13228. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  13229. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  13230. this._pivotMatrix = matrix.clone();
  13231. this._cache.pivotMatrixUpdated = true;
  13232. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  13233. if (this._postMultiplyPivotMatrix) {
  13234. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  13235. }
  13236. return this;
  13237. };
  13238. /**
  13239. * Returns the mesh pivot matrix.
  13240. * Default : Identity.
  13241. * A Matrix is returned.
  13242. */
  13243. TransformNode.prototype.getPivotMatrix = function () {
  13244. return this._pivotMatrix;
  13245. };
  13246. /**
  13247. * Prevents the World matrix to be computed any longer.
  13248. * Returns the AbstractMesh.
  13249. */
  13250. TransformNode.prototype.freezeWorldMatrix = function () {
  13251. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  13252. this.computeWorldMatrix(true);
  13253. this._isWorldMatrixFrozen = true;
  13254. return this;
  13255. };
  13256. /**
  13257. * Allows back the World matrix computation.
  13258. * Returns the AbstractMesh.
  13259. */
  13260. TransformNode.prototype.unfreezeWorldMatrix = function () {
  13261. this._isWorldMatrixFrozen = false;
  13262. this.computeWorldMatrix(true);
  13263. return this;
  13264. };
  13265. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  13266. /**
  13267. * True if the World matrix has been frozen.
  13268. * Returns a boolean.
  13269. */
  13270. get: function () {
  13271. return this._isWorldMatrixFrozen;
  13272. },
  13273. enumerable: true,
  13274. configurable: true
  13275. });
  13276. /**
  13277. * Retuns the mesh absolute position in the World.
  13278. * Returns a Vector3.
  13279. */
  13280. TransformNode.prototype.getAbsolutePosition = function () {
  13281. this.computeWorldMatrix();
  13282. return this._absolutePosition;
  13283. };
  13284. /**
  13285. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  13286. * Returns the AbstractMesh.
  13287. */
  13288. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  13289. if (!absolutePosition) {
  13290. return this;
  13291. }
  13292. var absolutePositionX;
  13293. var absolutePositionY;
  13294. var absolutePositionZ;
  13295. if (absolutePosition.x === undefined) {
  13296. if (arguments.length < 3) {
  13297. return this;
  13298. }
  13299. absolutePositionX = arguments[0];
  13300. absolutePositionY = arguments[1];
  13301. absolutePositionZ = arguments[2];
  13302. }
  13303. else {
  13304. absolutePositionX = absolutePosition.x;
  13305. absolutePositionY = absolutePosition.y;
  13306. absolutePositionZ = absolutePosition.z;
  13307. }
  13308. if (this.parent) {
  13309. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13310. invertParentWorldMatrix.invert();
  13311. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  13312. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  13313. }
  13314. else {
  13315. this.position.x = absolutePositionX;
  13316. this.position.y = absolutePositionY;
  13317. this.position.z = absolutePositionZ;
  13318. }
  13319. return this;
  13320. };
  13321. /**
  13322. * Sets the mesh position in its local space.
  13323. * Returns the AbstractMesh.
  13324. */
  13325. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  13326. this.computeWorldMatrix();
  13327. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  13328. return this;
  13329. };
  13330. /**
  13331. * Returns the mesh position in the local space from the current World matrix values.
  13332. * Returns a new Vector3.
  13333. */
  13334. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  13335. this.computeWorldMatrix();
  13336. var invLocalWorldMatrix = this._localWorld.clone();
  13337. invLocalWorldMatrix.invert();
  13338. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  13339. };
  13340. /**
  13341. * Translates the mesh along the passed Vector3 in its local space.
  13342. * Returns the AbstractMesh.
  13343. */
  13344. TransformNode.prototype.locallyTranslate = function (vector3) {
  13345. this.computeWorldMatrix(true);
  13346. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  13347. return this;
  13348. };
  13349. /**
  13350. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  13351. * @param targetPoint the position (must be in same space as current mesh) to look at
  13352. * @param yawCor optional yaw (y-axis) correction in radians
  13353. * @param pitchCor optional pitch (x-axis) correction in radians
  13354. * @param rollCor optional roll (z-axis) correction in radians
  13355. * @param space the choosen space of the target
  13356. * @returns the TransformNode.
  13357. */
  13358. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  13359. if (yawCor === void 0) { yawCor = 0; }
  13360. if (pitchCor === void 0) { pitchCor = 0; }
  13361. if (rollCor === void 0) { rollCor = 0; }
  13362. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13363. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  13364. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  13365. targetPoint.subtractToRef(pos, dv);
  13366. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  13367. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  13368. var pitch = Math.atan2(dv.y, len);
  13369. if (this.rotationQuaternion) {
  13370. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  13371. }
  13372. else {
  13373. this.rotation.x = pitch + pitchCor;
  13374. this.rotation.y = yaw + yawCor;
  13375. this.rotation.z = rollCor;
  13376. }
  13377. return this;
  13378. };
  13379. /**
  13380. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13381. * This Vector3 is expressed in the World space.
  13382. */
  13383. TransformNode.prototype.getDirection = function (localAxis) {
  13384. var result = BABYLON.Vector3.Zero();
  13385. this.getDirectionToRef(localAxis, result);
  13386. return result;
  13387. };
  13388. /**
  13389. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13390. * localAxis is expressed in the mesh local space.
  13391. * result is computed in the Wordl space from the mesh World matrix.
  13392. * Returns the AbstractMesh.
  13393. */
  13394. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  13395. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13396. return this;
  13397. };
  13398. TransformNode.prototype.setPivotPoint = function (point, space) {
  13399. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13400. if (this.getScene().getRenderId() == 0) {
  13401. this.computeWorldMatrix(true);
  13402. }
  13403. var wm = this.getWorldMatrix();
  13404. if (space == BABYLON.Space.WORLD) {
  13405. var tmat = BABYLON.Tmp.Matrix[0];
  13406. wm.invertToRef(tmat);
  13407. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13408. }
  13409. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13410. this._pivotMatrix.m[12] = -point.x;
  13411. this._pivotMatrix.m[13] = -point.y;
  13412. this._pivotMatrix.m[14] = -point.z;
  13413. this._cache.pivotMatrixUpdated = true;
  13414. return this;
  13415. };
  13416. /**
  13417. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13418. */
  13419. TransformNode.prototype.getPivotPoint = function () {
  13420. var point = BABYLON.Vector3.Zero();
  13421. this.getPivotPointToRef(point);
  13422. return point;
  13423. };
  13424. /**
  13425. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13426. * Returns the AbstractMesh.
  13427. */
  13428. TransformNode.prototype.getPivotPointToRef = function (result) {
  13429. result.x = -this._pivotMatrix.m[12];
  13430. result.y = -this._pivotMatrix.m[13];
  13431. result.z = -this._pivotMatrix.m[14];
  13432. return this;
  13433. };
  13434. /**
  13435. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13436. */
  13437. TransformNode.prototype.getAbsolutePivotPoint = function () {
  13438. var point = BABYLON.Vector3.Zero();
  13439. this.getAbsolutePivotPointToRef(point);
  13440. return point;
  13441. };
  13442. /**
  13443. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13444. * Returns the AbstractMesh.
  13445. */
  13446. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  13447. result.x = this._pivotMatrix.m[12];
  13448. result.y = this._pivotMatrix.m[13];
  13449. result.z = this._pivotMatrix.m[14];
  13450. this.getPivotPointToRef(result);
  13451. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13452. return this;
  13453. };
  13454. /**
  13455. * Defines the passed node as the parent of the current node.
  13456. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  13457. * Returns the TransformNode.
  13458. */
  13459. TransformNode.prototype.setParent = function (node) {
  13460. if (node == null) {
  13461. var rotation = BABYLON.Tmp.Quaternion[0];
  13462. var position = BABYLON.Tmp.Vector3[0];
  13463. var scale = BABYLON.Tmp.Vector3[1];
  13464. if (this.parent && this.parent.computeWorldMatrix) {
  13465. this.parent.computeWorldMatrix(true);
  13466. }
  13467. this.computeWorldMatrix(true);
  13468. this.getWorldMatrix().decompose(scale, rotation, position);
  13469. if (this.rotationQuaternion) {
  13470. this.rotationQuaternion.copyFrom(rotation);
  13471. }
  13472. else {
  13473. rotation.toEulerAnglesToRef(this.rotation);
  13474. }
  13475. this.scaling.x = scale.x;
  13476. this.scaling.y = scale.y;
  13477. this.scaling.z = scale.z;
  13478. this.position.x = position.x;
  13479. this.position.y = position.y;
  13480. this.position.z = position.z;
  13481. }
  13482. else {
  13483. var rotation = BABYLON.Tmp.Quaternion[0];
  13484. var position = BABYLON.Tmp.Vector3[0];
  13485. var scale = BABYLON.Tmp.Vector3[1];
  13486. var diffMatrix = BABYLON.Tmp.Matrix[0];
  13487. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  13488. this.computeWorldMatrix(true);
  13489. node.computeWorldMatrix(true);
  13490. node.getWorldMatrix().invertToRef(invParentMatrix);
  13491. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  13492. diffMatrix.decompose(scale, rotation, position);
  13493. if (this.rotationQuaternion) {
  13494. this.rotationQuaternion.copyFrom(rotation);
  13495. }
  13496. else {
  13497. rotation.toEulerAnglesToRef(this.rotation);
  13498. }
  13499. this.position.x = position.x;
  13500. this.position.y = position.y;
  13501. this.position.z = position.z;
  13502. this.scaling.x = scale.x;
  13503. this.scaling.y = scale.y;
  13504. this.scaling.z = scale.z;
  13505. }
  13506. this.parent = node;
  13507. return this;
  13508. };
  13509. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  13510. get: function () {
  13511. return this._nonUniformScaling;
  13512. },
  13513. enumerable: true,
  13514. configurable: true
  13515. });
  13516. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  13517. if (this._nonUniformScaling === value) {
  13518. return false;
  13519. }
  13520. this._nonUniformScaling = true;
  13521. return true;
  13522. };
  13523. /**
  13524. * Attach the current TransformNode to another TransformNode associated with a bone
  13525. * @param bone Bone affecting the TransformNode
  13526. * @param affectedTransformNode TransformNode associated with the bone
  13527. */
  13528. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  13529. this._transformToBoneReferal = affectedTransformNode;
  13530. this.parent = bone;
  13531. if (bone.getWorldMatrix().determinant() < 0) {
  13532. this.scalingDeterminant *= -1;
  13533. }
  13534. return this;
  13535. };
  13536. TransformNode.prototype.detachFromBone = function () {
  13537. if (!this.parent) {
  13538. return this;
  13539. }
  13540. if (this.parent.getWorldMatrix().determinant() < 0) {
  13541. this.scalingDeterminant *= -1;
  13542. }
  13543. this._transformToBoneReferal = null;
  13544. this.parent = null;
  13545. return this;
  13546. };
  13547. /**
  13548. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  13549. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13550. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13551. * The passed axis is also normalized.
  13552. * Returns the AbstractMesh.
  13553. */
  13554. TransformNode.prototype.rotate = function (axis, amount, space) {
  13555. axis.normalize();
  13556. if (!this.rotationQuaternion) {
  13557. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13558. this.rotation = BABYLON.Vector3.Zero();
  13559. }
  13560. var rotationQuaternion;
  13561. if (!space || space === BABYLON.Space.LOCAL) {
  13562. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  13563. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  13564. }
  13565. else {
  13566. if (this.parent) {
  13567. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13568. invertParentWorldMatrix.invert();
  13569. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  13570. }
  13571. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  13572. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13573. }
  13574. return this;
  13575. };
  13576. /**
  13577. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  13578. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13579. * The passed axis is also normalized.
  13580. * Returns the AbstractMesh.
  13581. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  13582. */
  13583. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  13584. axis.normalize();
  13585. if (!this.rotationQuaternion) {
  13586. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13587. this.rotation.copyFromFloats(0, 0, 0);
  13588. }
  13589. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  13590. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  13591. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  13592. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  13593. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  13594. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  13595. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  13596. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  13597. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13598. return this;
  13599. };
  13600. /**
  13601. * Translates the mesh along the axis vector for the passed distance in the given space.
  13602. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13603. * Returns the AbstractMesh.
  13604. */
  13605. TransformNode.prototype.translate = function (axis, distance, space) {
  13606. var displacementVector = axis.scale(distance);
  13607. if (!space || space === BABYLON.Space.LOCAL) {
  13608. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  13609. this.setPositionWithLocalVector(tempV3);
  13610. }
  13611. else {
  13612. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  13613. }
  13614. return this;
  13615. };
  13616. /**
  13617. * Adds a rotation step to the mesh current rotation.
  13618. * x, y, z are Euler angles expressed in radians.
  13619. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  13620. * This means this rotation is made in the mesh local space only.
  13621. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  13622. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  13623. * ```javascript
  13624. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  13625. * ```
  13626. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  13627. * 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.
  13628. * Returns the AbstractMesh.
  13629. */
  13630. TransformNode.prototype.addRotation = function (x, y, z) {
  13631. var rotationQuaternion;
  13632. if (this.rotationQuaternion) {
  13633. rotationQuaternion = this.rotationQuaternion;
  13634. }
  13635. else {
  13636. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  13637. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  13638. }
  13639. var accumulation = BABYLON.Tmp.Quaternion[0];
  13640. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  13641. rotationQuaternion.multiplyInPlace(accumulation);
  13642. if (!this.rotationQuaternion) {
  13643. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  13644. }
  13645. return this;
  13646. };
  13647. /**
  13648. * Computes the mesh World matrix and returns it.
  13649. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  13650. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  13651. * If the parameter `force`is set to `true`, the actual computation is done.
  13652. * Returns the mesh World Matrix.
  13653. */
  13654. TransformNode.prototype.computeWorldMatrix = function (force) {
  13655. if (this._isWorldMatrixFrozen) {
  13656. return this._worldMatrix;
  13657. }
  13658. if (!force && this.isSynchronized(true)) {
  13659. return this._worldMatrix;
  13660. }
  13661. this._cache.position.copyFrom(this.position);
  13662. this._cache.scaling.copyFrom(this.scaling);
  13663. this._cache.pivotMatrixUpdated = false;
  13664. this._cache.billboardMode = this.billboardMode;
  13665. this._currentRenderId = this.getScene().getRenderId();
  13666. this._isDirty = false;
  13667. // Scaling
  13668. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  13669. // Rotation
  13670. //rotate, if quaternion is set and rotation was used
  13671. if (this.rotationQuaternion) {
  13672. var len = this.rotation.length();
  13673. if (len) {
  13674. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  13675. this.rotation.copyFromFloats(0, 0, 0);
  13676. }
  13677. }
  13678. if (this.rotationQuaternion) {
  13679. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  13680. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13681. }
  13682. else {
  13683. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  13684. this._cache.rotation.copyFrom(this.rotation);
  13685. }
  13686. // Translation
  13687. var camera = this.getScene().activeCamera;
  13688. if (this.infiniteDistance && !this.parent && camera) {
  13689. var cameraWorldMatrix = camera.getWorldMatrix();
  13690. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  13691. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  13692. }
  13693. else {
  13694. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  13695. }
  13696. // Composing transformations
  13697. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  13698. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13699. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  13700. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  13701. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  13702. // Need to decompose each rotation here
  13703. var currentPosition = BABYLON.Tmp.Vector3[3];
  13704. if (this.parent && this.parent.getWorldMatrix) {
  13705. if (this._transformToBoneReferal) {
  13706. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13707. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  13708. }
  13709. else {
  13710. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  13711. }
  13712. }
  13713. else {
  13714. currentPosition.copyFrom(this.position);
  13715. }
  13716. currentPosition.subtractInPlace(camera.globalPosition);
  13717. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  13718. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  13719. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  13720. }
  13721. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  13722. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  13723. }
  13724. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  13725. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  13726. }
  13727. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  13728. }
  13729. else {
  13730. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  13731. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  13732. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  13733. }
  13734. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  13735. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13736. }
  13737. // Local world
  13738. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  13739. // Parent
  13740. if (this.parent && this.parent.getWorldMatrix) {
  13741. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  13742. if (this._transformToBoneReferal) {
  13743. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13744. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  13745. }
  13746. else {
  13747. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  13748. }
  13749. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  13750. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  13751. this._worldMatrix.copyFrom(this._localWorld);
  13752. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  13753. }
  13754. else {
  13755. if (this._transformToBoneReferal) {
  13756. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13757. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  13758. }
  13759. else {
  13760. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  13761. }
  13762. }
  13763. this._markSyncedWithParent();
  13764. }
  13765. else {
  13766. this._worldMatrix.copyFrom(this._localWorld);
  13767. }
  13768. // Post multiply inverse of pivotMatrix
  13769. if (this._postMultiplyPivotMatrix) {
  13770. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  13771. }
  13772. // Normal matrix
  13773. if (this.scaling.isNonUniform) {
  13774. this._updateNonUniformScalingState(true);
  13775. }
  13776. else if (this.parent && this.parent._nonUniformScaling) {
  13777. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  13778. }
  13779. else {
  13780. this._updateNonUniformScalingState(false);
  13781. }
  13782. this._afterComputeWorldMatrix();
  13783. // Absolute position
  13784. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  13785. // Callbacks
  13786. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  13787. if (!this._poseMatrix) {
  13788. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  13789. }
  13790. return this._worldMatrix;
  13791. };
  13792. TransformNode.prototype._afterComputeWorldMatrix = function () {
  13793. };
  13794. /**
  13795. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  13796. * @param func: callback function to add
  13797. *
  13798. * Returns the TransformNode.
  13799. */
  13800. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  13801. this.onAfterWorldMatrixUpdateObservable.add(func);
  13802. return this;
  13803. };
  13804. /**
  13805. * Removes a registered callback function.
  13806. * Returns the TransformNode.
  13807. */
  13808. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  13809. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  13810. return this;
  13811. };
  13812. /**
  13813. * Clone the current transform node
  13814. * Returns the new transform node
  13815. * @param name Name of the new clone
  13816. * @param newParent New parent for the clone
  13817. * @param doNotCloneChildren Do not clone children hierarchy
  13818. */
  13819. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13820. var _this = this;
  13821. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  13822. result.name = name;
  13823. result.id = name;
  13824. if (newParent) {
  13825. result.parent = newParent;
  13826. }
  13827. if (!doNotCloneChildren) {
  13828. // Children
  13829. var directDescendants = this.getDescendants(true);
  13830. for (var index = 0; index < directDescendants.length; index++) {
  13831. var child = directDescendants[index];
  13832. if (child.clone) {
  13833. child.clone(name + "." + child.name, result);
  13834. }
  13835. }
  13836. }
  13837. return result;
  13838. };
  13839. TransformNode.prototype.serialize = function (currentSerializationObject) {
  13840. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  13841. serializationObject.type = this.getClassName();
  13842. // Parent
  13843. if (this.parent) {
  13844. serializationObject.parentId = this.parent.id;
  13845. }
  13846. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  13847. serializationObject.tags = BABYLON.Tags.GetTags(this);
  13848. }
  13849. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  13850. serializationObject.isEnabled = this.isEnabled();
  13851. // Parent
  13852. if (this.parent) {
  13853. serializationObject.parentId = this.parent.id;
  13854. }
  13855. return serializationObject;
  13856. };
  13857. // Statics
  13858. /**
  13859. * Returns a new TransformNode object parsed from the source provided.
  13860. * The parameter `parsedMesh` is the source.
  13861. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  13862. */
  13863. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  13864. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  13865. if (BABYLON.Tags) {
  13866. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  13867. }
  13868. if (parsedTransformNode.localMatrix) {
  13869. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  13870. }
  13871. else if (parsedTransformNode.pivotMatrix) {
  13872. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  13873. }
  13874. transformNode.setEnabled(parsedTransformNode.isEnabled);
  13875. // Parent
  13876. if (parsedTransformNode.parentId) {
  13877. transformNode._waitingParentId = parsedTransformNode.parentId;
  13878. }
  13879. return transformNode;
  13880. };
  13881. /**
  13882. * Disposes the TransformNode.
  13883. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  13884. * Returns nothing.
  13885. */
  13886. TransformNode.prototype.dispose = function (doNotRecurse) {
  13887. // Animations
  13888. this.getScene().stopAnimation(this);
  13889. // Remove from scene
  13890. this.getScene().removeTransformNode(this);
  13891. this._cache = null;
  13892. if (!doNotRecurse) {
  13893. // Children
  13894. var objects = this.getDescendants(true);
  13895. for (var index = 0; index < objects.length; index++) {
  13896. objects[index].dispose();
  13897. }
  13898. }
  13899. else {
  13900. var childMeshes = this.getChildMeshes(true);
  13901. for (index = 0; index < childMeshes.length; index++) {
  13902. var child = childMeshes[index];
  13903. child.parent = null;
  13904. child.computeWorldMatrix(true);
  13905. }
  13906. }
  13907. this.onAfterWorldMatrixUpdateObservable.clear();
  13908. _super.prototype.dispose.call(this);
  13909. };
  13910. // Statics
  13911. TransformNode.BILLBOARDMODE_NONE = 0;
  13912. TransformNode.BILLBOARDMODE_X = 1;
  13913. TransformNode.BILLBOARDMODE_Y = 2;
  13914. TransformNode.BILLBOARDMODE_Z = 4;
  13915. TransformNode.BILLBOARDMODE_ALL = 7;
  13916. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  13917. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  13918. __decorate([
  13919. BABYLON.serializeAsVector3()
  13920. ], TransformNode.prototype, "_rotation", void 0);
  13921. __decorate([
  13922. BABYLON.serializeAsQuaternion()
  13923. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  13924. __decorate([
  13925. BABYLON.serializeAsVector3()
  13926. ], TransformNode.prototype, "_scaling", void 0);
  13927. __decorate([
  13928. BABYLON.serialize()
  13929. ], TransformNode.prototype, "billboardMode", void 0);
  13930. __decorate([
  13931. BABYLON.serialize()
  13932. ], TransformNode.prototype, "scalingDeterminant", void 0);
  13933. __decorate([
  13934. BABYLON.serialize()
  13935. ], TransformNode.prototype, "infiniteDistance", void 0);
  13936. __decorate([
  13937. BABYLON.serializeAsVector3()
  13938. ], TransformNode.prototype, "position", void 0);
  13939. return TransformNode;
  13940. }(BABYLON.Node));
  13941. BABYLON.TransformNode = TransformNode;
  13942. })(BABYLON || (BABYLON = {}));
  13943. //# sourceMappingURL=babylon.transformNode.js.map
  13944. var BABYLON;
  13945. (function (BABYLON) {
  13946. var AbstractMesh = /** @class */ (function (_super) {
  13947. __extends(AbstractMesh, _super);
  13948. // Constructor
  13949. function AbstractMesh(name, scene) {
  13950. if (scene === void 0) { scene = null; }
  13951. var _this = _super.call(this, name, scene, false) || this;
  13952. _this._facetNb = 0; // facet number
  13953. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  13954. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  13955. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  13956. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  13957. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  13958. _this._subDiv = {
  13959. max: 1,
  13960. X: 1,
  13961. Y: 1,
  13962. Z: 1
  13963. };
  13964. _this._facetDepthSort = false; // is the facet depth sort to be computed
  13965. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  13966. // Events
  13967. /**
  13968. * An event triggered when this mesh collides with another one
  13969. * @type {BABYLON.Observable}
  13970. */
  13971. _this.onCollideObservable = new BABYLON.Observable();
  13972. /**
  13973. * An event triggered when the collision's position changes
  13974. * @type {BABYLON.Observable}
  13975. */
  13976. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  13977. /**
  13978. * An event triggered when material is changed
  13979. * @type {BABYLON.Observable}
  13980. */
  13981. _this.onMaterialChangedObservable = new BABYLON.Observable();
  13982. // Properties
  13983. _this.definedFacingForward = true; // orientation for POV movement & rotation
  13984. /**
  13985. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  13986. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  13987. * or
  13988. * 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.
  13989. * for more info check WebGl documentations
  13990. */
  13991. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  13992. /**
  13993. * 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:
  13994. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  13995. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  13996. * 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.
  13997. */
  13998. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  13999. /**
  14000. * 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.
  14001. * The default value is -1 which means don't break the query and wait till the result.
  14002. */
  14003. _this.occlusionRetryCount = -1;
  14004. _this._occlusionInternalRetryCounter = 0;
  14005. _this._isOccluded = false;
  14006. _this._isOcclusionQueryInProgress = false;
  14007. _this.visibility = 1.0;
  14008. _this.alphaIndex = Number.MAX_VALUE;
  14009. _this.isVisible = true;
  14010. _this.isPickable = true;
  14011. _this.showBoundingBox = false;
  14012. _this.showSubMeshesBoundingBox = false;
  14013. _this.isBlocker = false;
  14014. _this.enablePointerMoveEvents = false;
  14015. _this.renderingGroupId = 0;
  14016. _this._receiveShadows = false;
  14017. _this.renderOutline = false;
  14018. _this.outlineColor = BABYLON.Color3.Red();
  14019. _this.outlineWidth = 0.02;
  14020. _this.renderOverlay = false;
  14021. _this.overlayColor = BABYLON.Color3.Red();
  14022. _this.overlayAlpha = 0.5;
  14023. _this._hasVertexAlpha = false;
  14024. _this._useVertexColors = true;
  14025. _this._computeBonesUsingShaders = true;
  14026. _this._numBoneInfluencers = 4;
  14027. _this._applyFog = true;
  14028. _this.useOctreeForRenderingSelection = true;
  14029. _this.useOctreeForPicking = true;
  14030. _this.useOctreeForCollisions = true;
  14031. _this._layerMask = 0x0FFFFFFF;
  14032. /**
  14033. * True if the mesh must be rendered in any case.
  14034. */
  14035. _this.alwaysSelectAsActiveMesh = false;
  14036. // Collisions
  14037. _this._checkCollisions = false;
  14038. _this._collisionMask = -1;
  14039. _this._collisionGroup = -1;
  14040. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  14041. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  14042. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  14043. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  14044. // Edges
  14045. _this.edgesWidth = 1;
  14046. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  14047. // Cache
  14048. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  14049. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  14050. _this._isDisposed = false;
  14051. _this._renderId = 0;
  14052. _this._intersectionsInProgress = new Array();
  14053. _this._unIndexed = false;
  14054. _this._lightSources = new Array();
  14055. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  14056. if (collidedMesh === void 0) { collidedMesh = null; }
  14057. //TODO move this to the collision coordinator!
  14058. if (_this.getScene().workerCollisions)
  14059. newPosition.multiplyInPlace(_this._collider.radius);
  14060. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  14061. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  14062. _this.position.addInPlace(_this._diffPositionForCollisions);
  14063. }
  14064. if (collidedMesh) {
  14065. _this.onCollideObservable.notifyObservers(collidedMesh);
  14066. }
  14067. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  14068. };
  14069. _this.getScene().addMesh(_this);
  14070. _this._resyncLightSources();
  14071. return _this;
  14072. }
  14073. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  14074. get: function () {
  14075. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  14076. },
  14077. enumerable: true,
  14078. configurable: true
  14079. });
  14080. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  14081. get: function () {
  14082. return BABYLON.TransformNode.BILLBOARDMODE_X;
  14083. },
  14084. enumerable: true,
  14085. configurable: true
  14086. });
  14087. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  14088. get: function () {
  14089. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  14090. },
  14091. enumerable: true,
  14092. configurable: true
  14093. });
  14094. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  14095. get: function () {
  14096. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  14097. },
  14098. enumerable: true,
  14099. configurable: true
  14100. });
  14101. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  14102. get: function () {
  14103. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  14104. },
  14105. enumerable: true,
  14106. configurable: true
  14107. });
  14108. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  14109. /**
  14110. * Read-only : the number of facets in the mesh
  14111. */
  14112. get: function () {
  14113. return this._facetNb;
  14114. },
  14115. enumerable: true,
  14116. configurable: true
  14117. });
  14118. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  14119. /**
  14120. * The number (integer) of subdivisions per axis in the partioning space
  14121. */
  14122. get: function () {
  14123. return this._partitioningSubdivisions;
  14124. },
  14125. set: function (nb) {
  14126. this._partitioningSubdivisions = nb;
  14127. },
  14128. enumerable: true,
  14129. configurable: true
  14130. });
  14131. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  14132. /**
  14133. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  14134. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  14135. */
  14136. get: function () {
  14137. return this._partitioningBBoxRatio;
  14138. },
  14139. set: function (ratio) {
  14140. this._partitioningBBoxRatio = ratio;
  14141. },
  14142. enumerable: true,
  14143. configurable: true
  14144. });
  14145. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  14146. /**
  14147. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  14148. * Works only for updatable meshes.
  14149. * Doesn't work with multi-materials.
  14150. */
  14151. get: function () {
  14152. return this._facetDepthSort;
  14153. },
  14154. set: function (sort) {
  14155. this._facetDepthSort = sort;
  14156. },
  14157. enumerable: true,
  14158. configurable: true
  14159. });
  14160. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  14161. /**
  14162. * The location (Vector3) where the facet depth sort must be computed from.
  14163. * By default, the active camera position.
  14164. * Used only when facet depth sort is enabled.
  14165. */
  14166. get: function () {
  14167. return this._facetDepthSortFrom;
  14168. },
  14169. set: function (location) {
  14170. this._facetDepthSortFrom = location;
  14171. },
  14172. enumerable: true,
  14173. configurable: true
  14174. });
  14175. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  14176. /**
  14177. * Read-only boolean : is the feature facetData enabled ?
  14178. */
  14179. get: function () {
  14180. return this._facetDataEnabled;
  14181. },
  14182. enumerable: true,
  14183. configurable: true
  14184. });
  14185. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  14186. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  14187. return false;
  14188. }
  14189. this._markSubMeshesAsMiscDirty();
  14190. return true;
  14191. };
  14192. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  14193. set: function (callback) {
  14194. if (this._onCollideObserver) {
  14195. this.onCollideObservable.remove(this._onCollideObserver);
  14196. }
  14197. this._onCollideObserver = this.onCollideObservable.add(callback);
  14198. },
  14199. enumerable: true,
  14200. configurable: true
  14201. });
  14202. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  14203. set: function (callback) {
  14204. if (this._onCollisionPositionChangeObserver) {
  14205. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  14206. }
  14207. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  14208. },
  14209. enumerable: true,
  14210. configurable: true
  14211. });
  14212. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  14213. /**
  14214. * 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.
  14215. */
  14216. get: function () {
  14217. return this._isOccluded;
  14218. },
  14219. set: function (value) {
  14220. this._isOccluded = value;
  14221. },
  14222. enumerable: true,
  14223. configurable: true
  14224. });
  14225. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  14226. /**
  14227. * Flag to check the progress status of the query
  14228. */
  14229. get: function () {
  14230. return this._isOcclusionQueryInProgress;
  14231. },
  14232. enumerable: true,
  14233. configurable: true
  14234. });
  14235. Object.defineProperty(AbstractMesh.prototype, "material", {
  14236. get: function () {
  14237. return this._material;
  14238. },
  14239. set: function (value) {
  14240. if (this._material === value) {
  14241. return;
  14242. }
  14243. this._material = value;
  14244. if (this.onMaterialChangedObservable.hasObservers) {
  14245. this.onMaterialChangedObservable.notifyObservers(this);
  14246. }
  14247. if (!this.subMeshes) {
  14248. return;
  14249. }
  14250. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14251. var subMesh = _a[_i];
  14252. subMesh.setEffect(null);
  14253. }
  14254. },
  14255. enumerable: true,
  14256. configurable: true
  14257. });
  14258. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  14259. get: function () {
  14260. return this._receiveShadows;
  14261. },
  14262. set: function (value) {
  14263. if (this._receiveShadows === value) {
  14264. return;
  14265. }
  14266. this._receiveShadows = value;
  14267. this._markSubMeshesAsLightDirty();
  14268. },
  14269. enumerable: true,
  14270. configurable: true
  14271. });
  14272. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  14273. get: function () {
  14274. return this._hasVertexAlpha;
  14275. },
  14276. set: function (value) {
  14277. if (this._hasVertexAlpha === value) {
  14278. return;
  14279. }
  14280. this._hasVertexAlpha = value;
  14281. this._markSubMeshesAsAttributesDirty();
  14282. },
  14283. enumerable: true,
  14284. configurable: true
  14285. });
  14286. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  14287. get: function () {
  14288. return this._useVertexColors;
  14289. },
  14290. set: function (value) {
  14291. if (this._useVertexColors === value) {
  14292. return;
  14293. }
  14294. this._useVertexColors = value;
  14295. this._markSubMeshesAsAttributesDirty();
  14296. },
  14297. enumerable: true,
  14298. configurable: true
  14299. });
  14300. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  14301. get: function () {
  14302. return this._computeBonesUsingShaders;
  14303. },
  14304. set: function (value) {
  14305. if (this._computeBonesUsingShaders === value) {
  14306. return;
  14307. }
  14308. this._computeBonesUsingShaders = value;
  14309. this._markSubMeshesAsAttributesDirty();
  14310. },
  14311. enumerable: true,
  14312. configurable: true
  14313. });
  14314. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  14315. get: function () {
  14316. return this._numBoneInfluencers;
  14317. },
  14318. set: function (value) {
  14319. if (this._numBoneInfluencers === value) {
  14320. return;
  14321. }
  14322. this._numBoneInfluencers = value;
  14323. this._markSubMeshesAsAttributesDirty();
  14324. },
  14325. enumerable: true,
  14326. configurable: true
  14327. });
  14328. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  14329. get: function () {
  14330. return this._applyFog;
  14331. },
  14332. set: function (value) {
  14333. if (this._applyFog === value) {
  14334. return;
  14335. }
  14336. this._applyFog = value;
  14337. this._markSubMeshesAsMiscDirty();
  14338. },
  14339. enumerable: true,
  14340. configurable: true
  14341. });
  14342. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  14343. get: function () {
  14344. return this._layerMask;
  14345. },
  14346. set: function (value) {
  14347. if (value === this._layerMask) {
  14348. return;
  14349. }
  14350. this._layerMask = value;
  14351. this._resyncLightSources();
  14352. },
  14353. enumerable: true,
  14354. configurable: true
  14355. });
  14356. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  14357. get: function () {
  14358. return this._collisionMask;
  14359. },
  14360. set: function (mask) {
  14361. this._collisionMask = !isNaN(mask) ? mask : -1;
  14362. },
  14363. enumerable: true,
  14364. configurable: true
  14365. });
  14366. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  14367. get: function () {
  14368. return this._collisionGroup;
  14369. },
  14370. set: function (mask) {
  14371. this._collisionGroup = !isNaN(mask) ? mask : -1;
  14372. },
  14373. enumerable: true,
  14374. configurable: true
  14375. });
  14376. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  14377. get: function () {
  14378. return null;
  14379. },
  14380. enumerable: true,
  14381. configurable: true
  14382. });
  14383. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  14384. get: function () {
  14385. return this._skeleton;
  14386. },
  14387. set: function (value) {
  14388. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  14389. this._skeleton._unregisterMeshWithPoseMatrix(this);
  14390. }
  14391. if (value && value.needInitialSkinMatrix) {
  14392. value._registerMeshWithPoseMatrix(this);
  14393. }
  14394. this._skeleton = value;
  14395. if (!this._skeleton) {
  14396. this._bonesTransformMatrices = null;
  14397. }
  14398. this._markSubMeshesAsAttributesDirty();
  14399. },
  14400. enumerable: true,
  14401. configurable: true
  14402. });
  14403. /**
  14404. * Boolean : true if the mesh has been disposed.
  14405. */
  14406. AbstractMesh.prototype.isDisposed = function () {
  14407. return this._isDisposed;
  14408. };
  14409. /**
  14410. * Returns the string "AbstractMesh"
  14411. */
  14412. AbstractMesh.prototype.getClassName = function () {
  14413. return "AbstractMesh";
  14414. };
  14415. /**
  14416. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14417. */
  14418. AbstractMesh.prototype.toString = function (fullDetails) {
  14419. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  14420. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  14421. if (this._skeleton) {
  14422. ret += ", skeleton: " + this._skeleton.name;
  14423. }
  14424. if (fullDetails) {
  14425. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  14426. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  14427. }
  14428. return ret;
  14429. };
  14430. AbstractMesh.prototype._rebuild = function () {
  14431. if (this._occlusionQuery) {
  14432. this._occlusionQuery = null;
  14433. }
  14434. if (this._edgesRenderer) {
  14435. this._edgesRenderer._rebuild();
  14436. }
  14437. if (!this.subMeshes) {
  14438. return;
  14439. }
  14440. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14441. var subMesh = _a[_i];
  14442. subMesh._rebuild();
  14443. }
  14444. };
  14445. AbstractMesh.prototype._resyncLightSources = function () {
  14446. this._lightSources.length = 0;
  14447. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  14448. var light = _a[_i];
  14449. if (!light.isEnabled()) {
  14450. continue;
  14451. }
  14452. if (light.canAffectMesh(this)) {
  14453. this._lightSources.push(light);
  14454. }
  14455. }
  14456. this._markSubMeshesAsLightDirty();
  14457. };
  14458. AbstractMesh.prototype._resyncLighSource = function (light) {
  14459. var isIn = light.isEnabled() && light.canAffectMesh(this);
  14460. var index = this._lightSources.indexOf(light);
  14461. if (index === -1) {
  14462. if (!isIn) {
  14463. return;
  14464. }
  14465. this._lightSources.push(light);
  14466. }
  14467. else {
  14468. if (isIn) {
  14469. return;
  14470. }
  14471. this._lightSources.splice(index, 1);
  14472. }
  14473. this._markSubMeshesAsLightDirty();
  14474. };
  14475. AbstractMesh.prototype._removeLightSource = function (light) {
  14476. var index = this._lightSources.indexOf(light);
  14477. if (index === -1) {
  14478. return;
  14479. }
  14480. this._lightSources.splice(index, 1);
  14481. };
  14482. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  14483. if (!this.subMeshes) {
  14484. return;
  14485. }
  14486. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14487. var subMesh = _a[_i];
  14488. if (subMesh._materialDefines) {
  14489. func(subMesh._materialDefines);
  14490. }
  14491. }
  14492. };
  14493. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  14494. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  14495. };
  14496. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  14497. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  14498. };
  14499. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  14500. if (!this.subMeshes) {
  14501. return;
  14502. }
  14503. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14504. var subMesh = _a[_i];
  14505. var material = subMesh.getMaterial();
  14506. if (material) {
  14507. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  14508. }
  14509. }
  14510. };
  14511. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  14512. /**
  14513. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14514. * Default : (1.0, 1.0, 1.0)
  14515. */
  14516. get: function () {
  14517. return this._scaling;
  14518. },
  14519. /**
  14520. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14521. * Default : (1.0, 1.0, 1.0)
  14522. */
  14523. set: function (newScaling) {
  14524. this._scaling = newScaling;
  14525. if (this.physicsImpostor) {
  14526. this.physicsImpostor.forceUpdate();
  14527. }
  14528. },
  14529. enumerable: true,
  14530. configurable: true
  14531. });
  14532. // Methods
  14533. /**
  14534. * Disables the mesh edger rendering mode.
  14535. * Returns the AbstractMesh.
  14536. */
  14537. AbstractMesh.prototype.disableEdgesRendering = function () {
  14538. if (this._edgesRenderer) {
  14539. this._edgesRenderer.dispose();
  14540. this._edgesRenderer = null;
  14541. }
  14542. return this;
  14543. };
  14544. /**
  14545. * Enables the edge rendering mode on the mesh.
  14546. * This mode makes the mesh edges visible.
  14547. * Returns the AbstractMesh.
  14548. */
  14549. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  14550. if (epsilon === void 0) { epsilon = 0.95; }
  14551. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  14552. this.disableEdgesRendering();
  14553. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  14554. return this;
  14555. };
  14556. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  14557. /**
  14558. * Returns true if the mesh is blocked. Used by the class Mesh.
  14559. * Returns the boolean `false` by default.
  14560. */
  14561. get: function () {
  14562. return false;
  14563. },
  14564. enumerable: true,
  14565. configurable: true
  14566. });
  14567. /**
  14568. * Returns the mesh itself by default, used by the class Mesh.
  14569. * Returned type : AbstractMesh
  14570. */
  14571. AbstractMesh.prototype.getLOD = function (camera) {
  14572. return this;
  14573. };
  14574. /**
  14575. * Returns 0 by default, used by the class Mesh.
  14576. * Returns an integer.
  14577. */
  14578. AbstractMesh.prototype.getTotalVertices = function () {
  14579. return 0;
  14580. };
  14581. /**
  14582. * Returns null by default, used by the class Mesh.
  14583. * Returned type : integer array
  14584. */
  14585. AbstractMesh.prototype.getIndices = function () {
  14586. return null;
  14587. };
  14588. /**
  14589. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  14590. * Returned type : float array or Float32Array
  14591. */
  14592. AbstractMesh.prototype.getVerticesData = function (kind) {
  14593. return null;
  14594. };
  14595. /**
  14596. * Sets the vertex data of the mesh geometry for the requested `kind`.
  14597. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  14598. * The `data` are either a numeric array either a Float32Array.
  14599. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  14600. * 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).
  14601. * Note that a new underlying VertexBuffer object is created each call.
  14602. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  14603. *
  14604. * Possible `kind` values :
  14605. * - BABYLON.VertexBuffer.PositionKind
  14606. * - BABYLON.VertexBuffer.UVKind
  14607. * - BABYLON.VertexBuffer.UV2Kind
  14608. * - BABYLON.VertexBuffer.UV3Kind
  14609. * - BABYLON.VertexBuffer.UV4Kind
  14610. * - BABYLON.VertexBuffer.UV5Kind
  14611. * - BABYLON.VertexBuffer.UV6Kind
  14612. * - BABYLON.VertexBuffer.ColorKind
  14613. * - BABYLON.VertexBuffer.MatricesIndicesKind
  14614. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  14615. * - BABYLON.VertexBuffer.MatricesWeightsKind
  14616. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  14617. *
  14618. * Returns the Mesh.
  14619. */
  14620. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14621. return this;
  14622. };
  14623. /**
  14624. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  14625. * If the mesh has no geometry, it is simply returned as it is.
  14626. * The `data` are either a numeric array either a Float32Array.
  14627. * No new underlying VertexBuffer object is created.
  14628. * 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.
  14629. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  14630. *
  14631. * Possible `kind` values :
  14632. * - BABYLON.VertexBuffer.PositionKind
  14633. * - BABYLON.VertexBuffer.UVKind
  14634. * - BABYLON.VertexBuffer.UV2Kind
  14635. * - BABYLON.VertexBuffer.UV3Kind
  14636. * - BABYLON.VertexBuffer.UV4Kind
  14637. * - BABYLON.VertexBuffer.UV5Kind
  14638. * - BABYLON.VertexBuffer.UV6Kind
  14639. * - BABYLON.VertexBuffer.ColorKind
  14640. * - BABYLON.VertexBuffer.MatricesIndicesKind
  14641. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  14642. * - BABYLON.VertexBuffer.MatricesWeightsKind
  14643. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  14644. *
  14645. * Returns the Mesh.
  14646. */
  14647. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14648. return this;
  14649. };
  14650. /**
  14651. * Sets the mesh indices.
  14652. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  14653. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  14654. * This method creates a new index buffer each call.
  14655. * Returns the Mesh.
  14656. */
  14657. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  14658. return this;
  14659. };
  14660. /** Returns false by default, used by the class Mesh.
  14661. * Returns a boolean
  14662. */
  14663. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  14664. return false;
  14665. };
  14666. /**
  14667. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  14668. * Returns a BoundingInfo
  14669. */
  14670. AbstractMesh.prototype.getBoundingInfo = function () {
  14671. if (this._masterMesh) {
  14672. return this._masterMesh.getBoundingInfo();
  14673. }
  14674. if (!this._boundingInfo) {
  14675. // this._boundingInfo is being created here
  14676. this._updateBoundingInfo();
  14677. }
  14678. // cannot be null.
  14679. return this._boundingInfo;
  14680. };
  14681. /**
  14682. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  14683. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  14684. */
  14685. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  14686. if (includeDescendants === void 0) { includeDescendants = true; }
  14687. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  14688. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  14689. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  14690. if (maxDimension === 0) {
  14691. return this;
  14692. }
  14693. var scale = 1 / maxDimension;
  14694. this.scaling.scaleInPlace(scale);
  14695. return this;
  14696. };
  14697. /**
  14698. * Sets a mesh new object BoundingInfo.
  14699. * Returns the AbstractMesh.
  14700. */
  14701. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  14702. this._boundingInfo = boundingInfo;
  14703. return this;
  14704. };
  14705. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  14706. get: function () {
  14707. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  14708. },
  14709. enumerable: true,
  14710. configurable: true
  14711. });
  14712. AbstractMesh.prototype._preActivate = function () {
  14713. };
  14714. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  14715. };
  14716. AbstractMesh.prototype._activate = function (renderId) {
  14717. this._renderId = renderId;
  14718. };
  14719. /**
  14720. * Returns the latest update of the World matrix
  14721. * Returns a Matrix.
  14722. */
  14723. AbstractMesh.prototype.getWorldMatrix = function () {
  14724. if (this._masterMesh) {
  14725. return this._masterMesh.getWorldMatrix();
  14726. }
  14727. return _super.prototype.getWorldMatrix.call(this);
  14728. };
  14729. // ================================== Point of View Movement =================================
  14730. /**
  14731. * Perform relative position change from the point of view of behind the front of the mesh.
  14732. * This is performed taking into account the meshes current rotation, so you do not have to care.
  14733. * Supports definition of mesh facing forward or backward.
  14734. * @param {number} amountRight
  14735. * @param {number} amountUp
  14736. * @param {number} amountForward
  14737. *
  14738. * Returns the AbstractMesh.
  14739. */
  14740. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  14741. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  14742. return this;
  14743. };
  14744. /**
  14745. * Calculate relative position change from the point of view of behind the front of the mesh.
  14746. * This is performed taking into account the meshes current rotation, so you do not have to care.
  14747. * Supports definition of mesh facing forward or backward.
  14748. * @param {number} amountRight
  14749. * @param {number} amountUp
  14750. * @param {number} amountForward
  14751. *
  14752. * Returns a new Vector3.
  14753. */
  14754. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  14755. var rotMatrix = new BABYLON.Matrix();
  14756. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  14757. rotQuaternion.toRotationMatrix(rotMatrix);
  14758. var translationDelta = BABYLON.Vector3.Zero();
  14759. var defForwardMult = this.definedFacingForward ? -1 : 1;
  14760. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  14761. return translationDelta;
  14762. };
  14763. // ================================== Point of View Rotation =================================
  14764. /**
  14765. * Perform relative rotation change from the point of view of behind the front of the mesh.
  14766. * Supports definition of mesh facing forward or backward.
  14767. * @param {number} flipBack
  14768. * @param {number} twirlClockwise
  14769. * @param {number} tiltRight
  14770. *
  14771. * Returns the AbstractMesh.
  14772. */
  14773. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  14774. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  14775. return this;
  14776. };
  14777. /**
  14778. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  14779. * Supports definition of mesh facing forward or backward.
  14780. * @param {number} flipBack
  14781. * @param {number} twirlClockwise
  14782. * @param {number} tiltRight
  14783. *
  14784. * Returns a new Vector3.
  14785. */
  14786. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  14787. var defForwardMult = this.definedFacingForward ? 1 : -1;
  14788. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  14789. };
  14790. /**
  14791. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  14792. * @param includeDescendants Include bounding info from descendants as well (true by default).
  14793. */
  14794. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  14795. if (includeDescendants === void 0) { includeDescendants = true; }
  14796. this.computeWorldMatrix(true);
  14797. var min;
  14798. var max;
  14799. var boundingInfo = this.getBoundingInfo();
  14800. if (!this.subMeshes) {
  14801. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14802. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  14803. }
  14804. else {
  14805. min = boundingInfo.boundingBox.minimumWorld;
  14806. max = boundingInfo.boundingBox.maximumWorld;
  14807. }
  14808. if (includeDescendants) {
  14809. var descendants = this.getDescendants(false);
  14810. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  14811. var descendant = descendants_1[_i];
  14812. var childMesh = descendant;
  14813. childMesh.computeWorldMatrix(true);
  14814. var childBoundingInfo = childMesh.getBoundingInfo();
  14815. if (childMesh.getTotalVertices() === 0) {
  14816. continue;
  14817. }
  14818. var boundingBox = childBoundingInfo.boundingBox;
  14819. var minBox = boundingBox.minimumWorld;
  14820. var maxBox = boundingBox.maximumWorld;
  14821. BABYLON.Tools.CheckExtends(minBox, min, max);
  14822. BABYLON.Tools.CheckExtends(maxBox, min, max);
  14823. }
  14824. }
  14825. return {
  14826. min: min,
  14827. max: max
  14828. };
  14829. };
  14830. /**
  14831. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  14832. * Returns the AbstractMesh.
  14833. */
  14834. AbstractMesh.prototype._updateBoundingInfo = function () {
  14835. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  14836. this._boundingInfo.update(this.worldMatrixFromCache);
  14837. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14838. return this;
  14839. };
  14840. /**
  14841. * Update a mesh's children BoundingInfo objects only.
  14842. * Returns the AbstractMesh.
  14843. */
  14844. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  14845. if (!this.subMeshes) {
  14846. return this;
  14847. }
  14848. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  14849. var subMesh = this.subMeshes[subIndex];
  14850. if (!subMesh.IsGlobal) {
  14851. subMesh.updateBoundingInfo(matrix);
  14852. }
  14853. }
  14854. return this;
  14855. };
  14856. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  14857. // Bounding info
  14858. this._updateBoundingInfo();
  14859. };
  14860. /**
  14861. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  14862. * A mesh is in the frustum if its bounding box intersects the frustum.
  14863. * Boolean returned.
  14864. */
  14865. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  14866. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  14867. };
  14868. /**
  14869. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  14870. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  14871. * Boolean returned.
  14872. */
  14873. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14874. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  14875. ;
  14876. };
  14877. /**
  14878. * True if the mesh intersects another mesh or a SolidParticle object.
  14879. * 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)
  14880. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  14881. * Returns a boolean.
  14882. */
  14883. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  14884. if (precise === void 0) { precise = false; }
  14885. if (!this._boundingInfo || !mesh._boundingInfo) {
  14886. return false;
  14887. }
  14888. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  14889. return true;
  14890. }
  14891. if (includeDescendants) {
  14892. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  14893. var child = _a[_i];
  14894. if (child.intersectsMesh(mesh, precise, true)) {
  14895. return true;
  14896. }
  14897. }
  14898. }
  14899. return false;
  14900. };
  14901. /**
  14902. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  14903. * Returns a boolean.
  14904. */
  14905. AbstractMesh.prototype.intersectsPoint = function (point) {
  14906. if (!this._boundingInfo) {
  14907. return false;
  14908. }
  14909. return this._boundingInfo.intersectsPoint(point);
  14910. };
  14911. AbstractMesh.prototype.getPhysicsImpostor = function () {
  14912. return this.physicsImpostor;
  14913. };
  14914. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  14915. if (camera === void 0) { camera = null; }
  14916. if (!camera) {
  14917. camera = this.getScene().activeCamera;
  14918. }
  14919. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  14920. };
  14921. /**
  14922. * Returns the distance from the mesh to the active camera.
  14923. * Returns a float.
  14924. */
  14925. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  14926. if (camera === void 0) { camera = null; }
  14927. if (!camera) {
  14928. camera = this.getScene().activeCamera;
  14929. }
  14930. return this.absolutePosition.subtract(camera.position).length();
  14931. };
  14932. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  14933. if (!this.physicsImpostor) {
  14934. return this;
  14935. }
  14936. this.physicsImpostor.applyImpulse(force, contactPoint);
  14937. return this;
  14938. };
  14939. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  14940. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  14941. return this;
  14942. }
  14943. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  14944. mainPivot: pivot1,
  14945. connectedPivot: pivot2,
  14946. nativeParams: options
  14947. });
  14948. return this;
  14949. };
  14950. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  14951. // Collisions
  14952. /**
  14953. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  14954. * Default `false`.
  14955. */
  14956. get: function () {
  14957. return this._checkCollisions;
  14958. },
  14959. set: function (collisionEnabled) {
  14960. this._checkCollisions = collisionEnabled;
  14961. if (this.getScene().workerCollisions) {
  14962. this.getScene().collisionCoordinator.onMeshUpdated(this);
  14963. }
  14964. },
  14965. enumerable: true,
  14966. configurable: true
  14967. });
  14968. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  14969. var globalPosition = this.getAbsolutePosition();
  14970. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  14971. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  14972. if (!this._collider) {
  14973. this._collider = new BABYLON.Collider();
  14974. }
  14975. this._collider.radius = this.ellipsoid;
  14976. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  14977. return this;
  14978. };
  14979. // Submeshes octree
  14980. /**
  14981. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  14982. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  14983. * Returns an Octree of submeshes.
  14984. */
  14985. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  14986. if (maxCapacity === void 0) { maxCapacity = 64; }
  14987. if (maxDepth === void 0) { maxDepth = 2; }
  14988. if (!this._submeshesOctree) {
  14989. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  14990. }
  14991. this.computeWorldMatrix(true);
  14992. var boundingInfo = this.getBoundingInfo();
  14993. // Update octree
  14994. var bbox = boundingInfo.boundingBox;
  14995. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  14996. return this._submeshesOctree;
  14997. };
  14998. // Collisions
  14999. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  15000. this._generatePointsArray();
  15001. if (!this._positions) {
  15002. return this;
  15003. }
  15004. // Transformation
  15005. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  15006. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  15007. subMesh._lastColliderWorldVertices = [];
  15008. subMesh._trianglePlanes = [];
  15009. var start = subMesh.verticesStart;
  15010. var end = (subMesh.verticesStart + subMesh.verticesCount);
  15011. for (var i = start; i < end; i++) {
  15012. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  15013. }
  15014. }
  15015. // Collide
  15016. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  15017. if (collider.collisionFound) {
  15018. collider.collidedMesh = this;
  15019. }
  15020. return this;
  15021. };
  15022. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  15023. var subMeshes;
  15024. var len;
  15025. // Octrees
  15026. if (this._submeshesOctree && this.useOctreeForCollisions) {
  15027. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  15028. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  15029. len = intersections.length;
  15030. subMeshes = intersections.data;
  15031. }
  15032. else {
  15033. subMeshes = this.subMeshes;
  15034. len = subMeshes.length;
  15035. }
  15036. for (var index = 0; index < len; index++) {
  15037. var subMesh = subMeshes[index];
  15038. // Bounding test
  15039. if (len > 1 && !subMesh._checkCollision(collider))
  15040. continue;
  15041. this._collideForSubMesh(subMesh, transformMatrix, collider);
  15042. }
  15043. return this;
  15044. };
  15045. AbstractMesh.prototype._checkCollision = function (collider) {
  15046. // Bounding box test
  15047. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  15048. return this;
  15049. // Transformation matrix
  15050. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  15051. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  15052. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  15053. return this;
  15054. };
  15055. // Picking
  15056. AbstractMesh.prototype._generatePointsArray = function () {
  15057. return false;
  15058. };
  15059. /**
  15060. * Checks if the passed Ray intersects with the mesh.
  15061. * Returns an object PickingInfo.
  15062. */
  15063. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  15064. var pickingInfo = new BABYLON.PickingInfo();
  15065. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  15066. return pickingInfo;
  15067. }
  15068. if (!this._generatePointsArray()) {
  15069. return pickingInfo;
  15070. }
  15071. var intersectInfo = null;
  15072. // Octrees
  15073. var subMeshes;
  15074. var len;
  15075. if (this._submeshesOctree && this.useOctreeForPicking) {
  15076. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  15077. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  15078. len = intersections.length;
  15079. subMeshes = intersections.data;
  15080. }
  15081. else {
  15082. subMeshes = this.subMeshes;
  15083. len = subMeshes.length;
  15084. }
  15085. for (var index = 0; index < len; index++) {
  15086. var subMesh = subMeshes[index];
  15087. // Bounding test
  15088. if (len > 1 && !subMesh.canIntersects(ray))
  15089. continue;
  15090. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  15091. if (currentIntersectInfo) {
  15092. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  15093. intersectInfo = currentIntersectInfo;
  15094. intersectInfo.subMeshId = index;
  15095. if (fastCheck) {
  15096. break;
  15097. }
  15098. }
  15099. }
  15100. }
  15101. if (intersectInfo) {
  15102. // Get picked point
  15103. var world = this.getWorldMatrix();
  15104. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  15105. var direction = ray.direction.clone();
  15106. direction = direction.scale(intersectInfo.distance);
  15107. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  15108. var pickedPoint = worldOrigin.add(worldDirection);
  15109. // Return result
  15110. pickingInfo.hit = true;
  15111. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  15112. pickingInfo.pickedPoint = pickedPoint;
  15113. pickingInfo.pickedMesh = this;
  15114. pickingInfo.bu = intersectInfo.bu || 0;
  15115. pickingInfo.bv = intersectInfo.bv || 0;
  15116. pickingInfo.faceId = intersectInfo.faceId;
  15117. pickingInfo.subMeshId = intersectInfo.subMeshId;
  15118. return pickingInfo;
  15119. }
  15120. return pickingInfo;
  15121. };
  15122. /**
  15123. * Clones the mesh, used by the class Mesh.
  15124. * Just returns `null` for an AbstractMesh.
  15125. */
  15126. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15127. return null;
  15128. };
  15129. /**
  15130. * Disposes all the mesh submeshes.
  15131. * Returns the AbstractMesh.
  15132. */
  15133. AbstractMesh.prototype.releaseSubMeshes = function () {
  15134. if (this.subMeshes) {
  15135. while (this.subMeshes.length) {
  15136. this.subMeshes[0].dispose();
  15137. }
  15138. }
  15139. else {
  15140. this.subMeshes = new Array();
  15141. }
  15142. return this;
  15143. };
  15144. /**
  15145. * Disposes the AbstractMesh.
  15146. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  15147. * Returns nothing.
  15148. */
  15149. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  15150. var _this = this;
  15151. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  15152. var index;
  15153. // Action manager
  15154. if (this.actionManager) {
  15155. this.actionManager.dispose();
  15156. this.actionManager = null;
  15157. }
  15158. // Skeleton
  15159. this.skeleton = null;
  15160. // Physics
  15161. if (this.physicsImpostor) {
  15162. this.physicsImpostor.dispose();
  15163. }
  15164. // Intersections in progress
  15165. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  15166. var other = this._intersectionsInProgress[index];
  15167. var pos = other._intersectionsInProgress.indexOf(this);
  15168. other._intersectionsInProgress.splice(pos, 1);
  15169. }
  15170. this._intersectionsInProgress = [];
  15171. // Lights
  15172. var lights = this.getScene().lights;
  15173. lights.forEach(function (light) {
  15174. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  15175. if (meshIndex !== -1) {
  15176. light.includedOnlyMeshes.splice(meshIndex, 1);
  15177. }
  15178. meshIndex = light.excludedMeshes.indexOf(_this);
  15179. if (meshIndex !== -1) {
  15180. light.excludedMeshes.splice(meshIndex, 1);
  15181. }
  15182. // Shadow generators
  15183. var generator = light.getShadowGenerator();
  15184. if (generator) {
  15185. var shadowMap = generator.getShadowMap();
  15186. if (shadowMap && shadowMap.renderList) {
  15187. meshIndex = shadowMap.renderList.indexOf(_this);
  15188. if (meshIndex !== -1) {
  15189. shadowMap.renderList.splice(meshIndex, 1);
  15190. }
  15191. }
  15192. }
  15193. });
  15194. // Edges
  15195. if (this._edgesRenderer) {
  15196. this._edgesRenderer.dispose();
  15197. this._edgesRenderer = null;
  15198. }
  15199. // SubMeshes
  15200. if (this.getClassName() !== "InstancedMesh") {
  15201. this.releaseSubMeshes();
  15202. }
  15203. // Octree
  15204. var sceneOctree = this.getScene().selectionOctree;
  15205. if (sceneOctree) {
  15206. var index = sceneOctree.dynamicContent.indexOf(this);
  15207. if (index !== -1) {
  15208. sceneOctree.dynamicContent.splice(index, 1);
  15209. }
  15210. }
  15211. // Query
  15212. var engine = this.getScene().getEngine();
  15213. if (this._occlusionQuery) {
  15214. this._isOcclusionQueryInProgress = false;
  15215. engine.deleteQuery(this._occlusionQuery);
  15216. this._occlusionQuery = null;
  15217. }
  15218. // Engine
  15219. engine.wipeCaches();
  15220. // Remove from scene
  15221. this.getScene().removeMesh(this);
  15222. if (disposeMaterialAndTextures) {
  15223. if (this.material) {
  15224. this.material.dispose(false, true);
  15225. }
  15226. }
  15227. if (!doNotRecurse) {
  15228. // Particles
  15229. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  15230. if (this.getScene().particleSystems[index].emitter === this) {
  15231. this.getScene().particleSystems[index].dispose();
  15232. index--;
  15233. }
  15234. }
  15235. }
  15236. // facet data
  15237. if (this._facetDataEnabled) {
  15238. this.disableFacetData();
  15239. }
  15240. this.onAfterWorldMatrixUpdateObservable.clear();
  15241. this.onCollideObservable.clear();
  15242. this.onCollisionPositionChangeObservable.clear();
  15243. this._isDisposed = true;
  15244. _super.prototype.dispose.call(this, doNotRecurse);
  15245. };
  15246. /**
  15247. * Adds the passed mesh as a child to the current mesh.
  15248. * Returns the AbstractMesh.
  15249. */
  15250. AbstractMesh.prototype.addChild = function (mesh) {
  15251. mesh.setParent(this);
  15252. return this;
  15253. };
  15254. /**
  15255. * Removes the passed mesh from the current mesh children list.
  15256. * Returns the AbstractMesh.
  15257. */
  15258. AbstractMesh.prototype.removeChild = function (mesh) {
  15259. mesh.setParent(null);
  15260. return this;
  15261. };
  15262. // Facet data
  15263. /**
  15264. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  15265. * Returns the AbstractMesh.
  15266. */
  15267. AbstractMesh.prototype._initFacetData = function () {
  15268. if (!this._facetNormals) {
  15269. this._facetNormals = new Array();
  15270. }
  15271. if (!this._facetPositions) {
  15272. this._facetPositions = new Array();
  15273. }
  15274. if (!this._facetPartitioning) {
  15275. this._facetPartitioning = new Array();
  15276. }
  15277. this._facetNb = (this.getIndices().length / 3) | 0;
  15278. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  15279. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  15280. for (var f = 0; f < this._facetNb; f++) {
  15281. this._facetNormals[f] = BABYLON.Vector3.Zero();
  15282. this._facetPositions[f] = BABYLON.Vector3.Zero();
  15283. }
  15284. this._facetDataEnabled = true;
  15285. return this;
  15286. };
  15287. /**
  15288. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  15289. * This method can be called within the render loop.
  15290. * 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.
  15291. * Returns the AbstractMesh.
  15292. */
  15293. AbstractMesh.prototype.updateFacetData = function () {
  15294. if (!this._facetDataEnabled) {
  15295. this._initFacetData();
  15296. }
  15297. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15298. var indices = this.getIndices();
  15299. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15300. var bInfo = this.getBoundingInfo();
  15301. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  15302. // init arrays, matrix and sort function on first call
  15303. this._facetDepthSortEnabled = true;
  15304. if (indices instanceof Uint16Array) {
  15305. this._depthSortedIndices = new Uint16Array(indices);
  15306. }
  15307. else if (indices instanceof Uint32Array) {
  15308. this._depthSortedIndices = new Uint32Array(indices);
  15309. }
  15310. else {
  15311. var needs32bits = false;
  15312. for (var i = 0; i < indices.length; i++) {
  15313. if (indices[i] > 65535) {
  15314. needs32bits = true;
  15315. break;
  15316. }
  15317. }
  15318. if (needs32bits) {
  15319. this._depthSortedIndices = new Uint32Array(indices);
  15320. }
  15321. else {
  15322. this._depthSortedIndices = new Uint16Array(indices);
  15323. }
  15324. }
  15325. this._facetDepthSortFunction = function (f1, f2) {
  15326. return (f2.sqDistance - f1.sqDistance);
  15327. };
  15328. if (!this._facetDepthSortFrom) {
  15329. var camera = this.getScene().activeCamera;
  15330. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  15331. }
  15332. this._depthSortedFacets = [];
  15333. for (var f = 0; f < this._facetNb; f++) {
  15334. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  15335. this._depthSortedFacets.push(depthSortedFacet);
  15336. }
  15337. this._invertedMatrix = BABYLON.Matrix.Identity();
  15338. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  15339. }
  15340. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  15341. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  15342. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  15343. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  15344. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  15345. this._subDiv.max = this._partitioningSubdivisions;
  15346. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  15347. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  15348. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  15349. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  15350. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  15351. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  15352. // set the parameters for ComputeNormals()
  15353. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  15354. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  15355. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  15356. this._facetParameters.bInfo = bInfo;
  15357. this._facetParameters.bbSize = this._bbSize;
  15358. this._facetParameters.subDiv = this._subDiv;
  15359. this._facetParameters.ratio = this.partitioningBBoxRatio;
  15360. this._facetParameters.depthSort = this._facetDepthSort;
  15361. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  15362. this.computeWorldMatrix(true);
  15363. this._worldMatrix.invertToRef(this._invertedMatrix);
  15364. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  15365. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  15366. }
  15367. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  15368. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  15369. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  15370. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  15371. var l = (this._depthSortedIndices.length / 3) | 0;
  15372. for (var f = 0; f < l; f++) {
  15373. var sind = this._depthSortedFacets[f].ind;
  15374. this._depthSortedIndices[f * 3] = indices[sind];
  15375. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  15376. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  15377. }
  15378. this.updateIndices(this._depthSortedIndices);
  15379. }
  15380. return this;
  15381. };
  15382. /**
  15383. * Returns the facetLocalNormals array.
  15384. * The normals are expressed in the mesh local space.
  15385. */
  15386. AbstractMesh.prototype.getFacetLocalNormals = function () {
  15387. if (!this._facetNormals) {
  15388. this.updateFacetData();
  15389. }
  15390. return this._facetNormals;
  15391. };
  15392. /**
  15393. * Returns the facetLocalPositions array.
  15394. * The facet positions are expressed in the mesh local space.
  15395. */
  15396. AbstractMesh.prototype.getFacetLocalPositions = function () {
  15397. if (!this._facetPositions) {
  15398. this.updateFacetData();
  15399. }
  15400. return this._facetPositions;
  15401. };
  15402. /**
  15403. * Returns the facetLocalPartioning array.
  15404. */
  15405. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  15406. if (!this._facetPartitioning) {
  15407. this.updateFacetData();
  15408. }
  15409. return this._facetPartitioning;
  15410. };
  15411. /**
  15412. * Returns the i-th facet position in the world system.
  15413. * This method allocates a new Vector3 per call.
  15414. */
  15415. AbstractMesh.prototype.getFacetPosition = function (i) {
  15416. var pos = BABYLON.Vector3.Zero();
  15417. this.getFacetPositionToRef(i, pos);
  15418. return pos;
  15419. };
  15420. /**
  15421. * Sets the reference Vector3 with the i-th facet position in the world system.
  15422. * Returns the AbstractMesh.
  15423. */
  15424. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  15425. var localPos = (this.getFacetLocalPositions())[i];
  15426. var world = this.getWorldMatrix();
  15427. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  15428. return this;
  15429. };
  15430. /**
  15431. * Returns the i-th facet normal in the world system.
  15432. * This method allocates a new Vector3 per call.
  15433. */
  15434. AbstractMesh.prototype.getFacetNormal = function (i) {
  15435. var norm = BABYLON.Vector3.Zero();
  15436. this.getFacetNormalToRef(i, norm);
  15437. return norm;
  15438. };
  15439. /**
  15440. * Sets the reference Vector3 with the i-th facet normal in the world system.
  15441. * Returns the AbstractMesh.
  15442. */
  15443. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  15444. var localNorm = (this.getFacetLocalNormals())[i];
  15445. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  15446. return this;
  15447. };
  15448. /**
  15449. * 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).
  15450. */
  15451. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  15452. var bInfo = this.getBoundingInfo();
  15453. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  15454. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  15455. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  15456. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  15457. return null;
  15458. }
  15459. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  15460. };
  15461. /**
  15462. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  15463. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  15464. * 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.
  15465. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  15466. * 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.
  15467. */
  15468. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  15469. if (checkFace === void 0) { checkFace = false; }
  15470. if (facing === void 0) { facing = true; }
  15471. var world = this.getWorldMatrix();
  15472. var invMat = BABYLON.Tmp.Matrix[5];
  15473. world.invertToRef(invMat);
  15474. var invVect = BABYLON.Tmp.Vector3[8];
  15475. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  15476. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  15477. if (projected) {
  15478. // tranform the local computed projected vector to world coordinates
  15479. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  15480. }
  15481. return closest;
  15482. };
  15483. /**
  15484. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  15485. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  15486. * 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.
  15487. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  15488. * 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.
  15489. */
  15490. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  15491. if (checkFace === void 0) { checkFace = false; }
  15492. if (facing === void 0) { facing = true; }
  15493. var closest = null;
  15494. var tmpx = 0.0;
  15495. var tmpy = 0.0;
  15496. var tmpz = 0.0;
  15497. var d = 0.0; // tmp dot facet normal * facet position
  15498. var t0 = 0.0;
  15499. var projx = 0.0;
  15500. var projy = 0.0;
  15501. var projz = 0.0;
  15502. // Get all the facets in the same partitioning block than (x, y, z)
  15503. var facetPositions = this.getFacetLocalPositions();
  15504. var facetNormals = this.getFacetLocalNormals();
  15505. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  15506. if (!facetsInBlock) {
  15507. return null;
  15508. }
  15509. // Get the closest facet to (x, y, z)
  15510. var shortest = Number.MAX_VALUE; // init distance vars
  15511. var tmpDistance = shortest;
  15512. var fib; // current facet in the block
  15513. var norm; // current facet normal
  15514. var p0; // current facet barycenter position
  15515. // loop on all the facets in the current partitioning block
  15516. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  15517. fib = facetsInBlock[idx];
  15518. norm = facetNormals[fib];
  15519. p0 = facetPositions[fib];
  15520. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  15521. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  15522. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  15523. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  15524. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  15525. projx = x + norm.x * t0;
  15526. projy = y + norm.y * t0;
  15527. projz = z + norm.z * t0;
  15528. tmpx = projx - x;
  15529. tmpy = projy - y;
  15530. tmpz = projz - z;
  15531. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  15532. if (tmpDistance < shortest) {
  15533. shortest = tmpDistance;
  15534. closest = fib;
  15535. if (projected) {
  15536. projected.x = projx;
  15537. projected.y = projy;
  15538. projected.z = projz;
  15539. }
  15540. }
  15541. }
  15542. }
  15543. return closest;
  15544. };
  15545. /**
  15546. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  15547. */
  15548. AbstractMesh.prototype.getFacetDataParameters = function () {
  15549. return this._facetParameters;
  15550. };
  15551. /**
  15552. * Disables the feature FacetData and frees the related memory.
  15553. * Returns the AbstractMesh.
  15554. */
  15555. AbstractMesh.prototype.disableFacetData = function () {
  15556. if (this._facetDataEnabled) {
  15557. this._facetDataEnabled = false;
  15558. this._facetPositions = new Array();
  15559. this._facetNormals = new Array();
  15560. this._facetPartitioning = new Array();
  15561. this._facetParameters = null;
  15562. this._depthSortedIndices = new Uint32Array(0);
  15563. }
  15564. return this;
  15565. };
  15566. /**
  15567. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  15568. * Returns the mesh.
  15569. */
  15570. AbstractMesh.prototype.updateIndices = function (indices) {
  15571. return this;
  15572. };
  15573. /**
  15574. * The mesh Geometry. Actually used by the Mesh object.
  15575. * Returns a blank geometry object.
  15576. */
  15577. /**
  15578. * Creates new normals data for the mesh.
  15579. * @param updatable.
  15580. */
  15581. AbstractMesh.prototype.createNormals = function (updatable) {
  15582. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15583. var indices = this.getIndices();
  15584. var normals;
  15585. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15586. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15587. }
  15588. else {
  15589. normals = [];
  15590. }
  15591. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  15592. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  15593. };
  15594. /**
  15595. * Align the mesh with a normal.
  15596. * Returns the mesh.
  15597. */
  15598. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  15599. if (!upDirection) {
  15600. upDirection = BABYLON.Axis.Y;
  15601. }
  15602. var axisX = BABYLON.Tmp.Vector3[0];
  15603. var axisZ = BABYLON.Tmp.Vector3[1];
  15604. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  15605. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  15606. if (this.rotationQuaternion) {
  15607. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  15608. }
  15609. else {
  15610. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  15611. }
  15612. return this;
  15613. };
  15614. AbstractMesh.prototype.checkOcclusionQuery = function () {
  15615. var engine = this.getEngine();
  15616. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  15617. this._isOccluded = false;
  15618. return;
  15619. }
  15620. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  15621. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  15622. if (isOcclusionQueryAvailable) {
  15623. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  15624. this._isOcclusionQueryInProgress = false;
  15625. this._occlusionInternalRetryCounter = 0;
  15626. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  15627. }
  15628. else {
  15629. this._occlusionInternalRetryCounter++;
  15630. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  15631. this._isOcclusionQueryInProgress = false;
  15632. this._occlusionInternalRetryCounter = 0;
  15633. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  15634. // if strict continue the last state of the object.
  15635. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  15636. }
  15637. else {
  15638. return;
  15639. }
  15640. }
  15641. }
  15642. var scene = this.getScene();
  15643. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  15644. if (!this._occlusionQuery) {
  15645. this._occlusionQuery = engine.createQuery();
  15646. }
  15647. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  15648. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  15649. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  15650. this._isOcclusionQueryInProgress = true;
  15651. };
  15652. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  15653. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  15654. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  15655. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  15656. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  15657. return AbstractMesh;
  15658. }(BABYLON.TransformNode));
  15659. BABYLON.AbstractMesh = AbstractMesh;
  15660. })(BABYLON || (BABYLON = {}));
  15661. //# sourceMappingURL=babylon.abstractMesh.js.map
  15662. var BABYLON;
  15663. (function (BABYLON) {
  15664. var Light = /** @class */ (function (_super) {
  15665. __extends(Light, _super);
  15666. /**
  15667. * Creates a Light object in the scene.
  15668. * Documentation : http://doc.babylonjs.com/tutorials/lights
  15669. */
  15670. function Light(name, scene) {
  15671. var _this = _super.call(this, name, scene) || this;
  15672. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  15673. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  15674. _this.intensity = 1.0;
  15675. _this.range = Number.MAX_VALUE;
  15676. /**
  15677. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  15678. * of light.
  15679. */
  15680. _this._photometricScale = 1.0;
  15681. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  15682. _this._radius = 0.00001;
  15683. _this.renderPriority = 0;
  15684. /**
  15685. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  15686. * the current shadow generator.
  15687. */
  15688. _this.shadowEnabled = true;
  15689. _this._excludeWithLayerMask = 0;
  15690. _this._includeOnlyWithLayerMask = 0;
  15691. _this._lightmapMode = 0;
  15692. _this._excludedMeshesIds = new Array();
  15693. _this._includedOnlyMeshesIds = new Array();
  15694. _this.getScene().addLight(_this);
  15695. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  15696. _this._buildUniformLayout();
  15697. _this.includedOnlyMeshes = new Array();
  15698. _this.excludedMeshes = new Array();
  15699. _this._resyncMeshes();
  15700. return _this;
  15701. }
  15702. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  15703. /**
  15704. * If every light affecting the material is in this lightmapMode,
  15705. * material.lightmapTexture adds or multiplies
  15706. * (depends on material.useLightmapAsShadowmap)
  15707. * after every other light calculations.
  15708. */
  15709. get: function () {
  15710. return Light._LIGHTMAP_DEFAULT;
  15711. },
  15712. enumerable: true,
  15713. configurable: true
  15714. });
  15715. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  15716. /**
  15717. * material.lightmapTexture as only diffuse lighting from this light
  15718. * adds pnly specular lighting from this light
  15719. * adds dynamic shadows
  15720. */
  15721. get: function () {
  15722. return Light._LIGHTMAP_SPECULAR;
  15723. },
  15724. enumerable: true,
  15725. configurable: true
  15726. });
  15727. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  15728. /**
  15729. * material.lightmapTexture as only lighting
  15730. * no light calculation from this light
  15731. * only adds dynamic shadows from this light
  15732. */
  15733. get: function () {
  15734. return Light._LIGHTMAP_SHADOWSONLY;
  15735. },
  15736. enumerable: true,
  15737. configurable: true
  15738. });
  15739. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  15740. /**
  15741. * Each light type uses the default quantity according to its type:
  15742. * point/spot lights use luminous intensity
  15743. * directional lights use illuminance
  15744. */
  15745. get: function () {
  15746. return Light._INTENSITYMODE_AUTOMATIC;
  15747. },
  15748. enumerable: true,
  15749. configurable: true
  15750. });
  15751. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  15752. /**
  15753. * lumen (lm)
  15754. */
  15755. get: function () {
  15756. return Light._INTENSITYMODE_LUMINOUSPOWER;
  15757. },
  15758. enumerable: true,
  15759. configurable: true
  15760. });
  15761. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  15762. /**
  15763. * candela (lm/sr)
  15764. */
  15765. get: function () {
  15766. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  15767. },
  15768. enumerable: true,
  15769. configurable: true
  15770. });
  15771. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  15772. /**
  15773. * lux (lm/m^2)
  15774. */
  15775. get: function () {
  15776. return Light._INTENSITYMODE_ILLUMINANCE;
  15777. },
  15778. enumerable: true,
  15779. configurable: true
  15780. });
  15781. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  15782. /**
  15783. * nit (cd/m^2)
  15784. */
  15785. get: function () {
  15786. return Light._INTENSITYMODE_LUMINANCE;
  15787. },
  15788. enumerable: true,
  15789. configurable: true
  15790. });
  15791. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  15792. /**
  15793. * Light type const id of the point light.
  15794. */
  15795. get: function () {
  15796. return Light._LIGHTTYPEID_POINTLIGHT;
  15797. },
  15798. enumerable: true,
  15799. configurable: true
  15800. });
  15801. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  15802. /**
  15803. * Light type const id of the directional light.
  15804. */
  15805. get: function () {
  15806. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  15807. },
  15808. enumerable: true,
  15809. configurable: true
  15810. });
  15811. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  15812. /**
  15813. * Light type const id of the spot light.
  15814. */
  15815. get: function () {
  15816. return Light._LIGHTTYPEID_SPOTLIGHT;
  15817. },
  15818. enumerable: true,
  15819. configurable: true
  15820. });
  15821. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  15822. /**
  15823. * Light type const id of the hemispheric light.
  15824. */
  15825. get: function () {
  15826. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  15827. },
  15828. enumerable: true,
  15829. configurable: true
  15830. });
  15831. Object.defineProperty(Light.prototype, "intensityMode", {
  15832. /**
  15833. * Gets the photometric scale used to interpret the intensity.
  15834. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  15835. */
  15836. get: function () {
  15837. return this._intensityMode;
  15838. },
  15839. /**
  15840. * Sets the photometric scale used to interpret the intensity.
  15841. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  15842. */
  15843. set: function (value) {
  15844. this._intensityMode = value;
  15845. this._computePhotometricScale();
  15846. },
  15847. enumerable: true,
  15848. configurable: true
  15849. });
  15850. ;
  15851. ;
  15852. Object.defineProperty(Light.prototype, "radius", {
  15853. /**
  15854. * Gets the light radius used by PBR Materials to simulate soft area lights.
  15855. */
  15856. get: function () {
  15857. return this._radius;
  15858. },
  15859. /**
  15860. * sets the light radius used by PBR Materials to simulate soft area lights.
  15861. */
  15862. set: function (value) {
  15863. this._radius = value;
  15864. this._computePhotometricScale();
  15865. },
  15866. enumerable: true,
  15867. configurable: true
  15868. });
  15869. ;
  15870. ;
  15871. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  15872. get: function () {
  15873. return this._includedOnlyMeshes;
  15874. },
  15875. set: function (value) {
  15876. this._includedOnlyMeshes = value;
  15877. this._hookArrayForIncludedOnly(value);
  15878. },
  15879. enumerable: true,
  15880. configurable: true
  15881. });
  15882. Object.defineProperty(Light.prototype, "excludedMeshes", {
  15883. get: function () {
  15884. return this._excludedMeshes;
  15885. },
  15886. set: function (value) {
  15887. this._excludedMeshes = value;
  15888. this._hookArrayForExcluded(value);
  15889. },
  15890. enumerable: true,
  15891. configurable: true
  15892. });
  15893. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  15894. get: function () {
  15895. return this._excludeWithLayerMask;
  15896. },
  15897. set: function (value) {
  15898. this._excludeWithLayerMask = value;
  15899. this._resyncMeshes();
  15900. },
  15901. enumerable: true,
  15902. configurable: true
  15903. });
  15904. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  15905. get: function () {
  15906. return this._includeOnlyWithLayerMask;
  15907. },
  15908. set: function (value) {
  15909. this._includeOnlyWithLayerMask = value;
  15910. this._resyncMeshes();
  15911. },
  15912. enumerable: true,
  15913. configurable: true
  15914. });
  15915. Object.defineProperty(Light.prototype, "lightmapMode", {
  15916. get: function () {
  15917. return this._lightmapMode;
  15918. },
  15919. set: function (value) {
  15920. if (this._lightmapMode === value) {
  15921. return;
  15922. }
  15923. this._lightmapMode = value;
  15924. this._markMeshesAsLightDirty();
  15925. },
  15926. enumerable: true,
  15927. configurable: true
  15928. });
  15929. Light.prototype._buildUniformLayout = function () {
  15930. // Overridden
  15931. };
  15932. /**
  15933. * Returns the string "Light".
  15934. */
  15935. Light.prototype.getClassName = function () {
  15936. return "Light";
  15937. };
  15938. /**
  15939. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15940. */
  15941. Light.prototype.toString = function (fullDetails) {
  15942. var ret = "Name: " + this.name;
  15943. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  15944. if (this.animations) {
  15945. for (var i = 0; i < this.animations.length; i++) {
  15946. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15947. }
  15948. }
  15949. if (fullDetails) {
  15950. }
  15951. return ret;
  15952. };
  15953. /**
  15954. * Set the enabled state of this node.
  15955. * @param {boolean} value - the new enabled state
  15956. * @see isEnabled
  15957. */
  15958. Light.prototype.setEnabled = function (value) {
  15959. _super.prototype.setEnabled.call(this, value);
  15960. this._resyncMeshes();
  15961. };
  15962. /**
  15963. * Returns the Light associated shadow generator.
  15964. */
  15965. Light.prototype.getShadowGenerator = function () {
  15966. return this._shadowGenerator;
  15967. };
  15968. /**
  15969. * Returns a Vector3, the absolute light position in the World.
  15970. */
  15971. Light.prototype.getAbsolutePosition = function () {
  15972. return BABYLON.Vector3.Zero();
  15973. };
  15974. Light.prototype.transferToEffect = function (effect, lightIndex) {
  15975. };
  15976. Light.prototype._getWorldMatrix = function () {
  15977. return BABYLON.Matrix.Identity();
  15978. };
  15979. /**
  15980. * Boolean : True if the light will affect the passed mesh.
  15981. */
  15982. Light.prototype.canAffectMesh = function (mesh) {
  15983. if (!mesh) {
  15984. return true;
  15985. }
  15986. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  15987. return false;
  15988. }
  15989. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  15990. return false;
  15991. }
  15992. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  15993. return false;
  15994. }
  15995. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  15996. return false;
  15997. }
  15998. return true;
  15999. };
  16000. /**
  16001. * Returns the light World matrix.
  16002. */
  16003. Light.prototype.getWorldMatrix = function () {
  16004. this._currentRenderId = this.getScene().getRenderId();
  16005. var worldMatrix = this._getWorldMatrix();
  16006. if (this.parent && this.parent.getWorldMatrix) {
  16007. if (!this._parentedWorldMatrix) {
  16008. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  16009. }
  16010. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  16011. this._markSyncedWithParent();
  16012. return this._parentedWorldMatrix;
  16013. }
  16014. return worldMatrix;
  16015. };
  16016. /**
  16017. * Sort function to order lights for rendering.
  16018. * @param a First Light object to compare to second.
  16019. * @param b Second Light object to compare first.
  16020. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  16021. */
  16022. Light.compareLightsPriority = function (a, b) {
  16023. //shadow-casting lights have priority over non-shadow-casting lights
  16024. //the renderPrioirty is a secondary sort criterion
  16025. if (a.shadowEnabled !== b.shadowEnabled) {
  16026. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  16027. }
  16028. return b.renderPriority - a.renderPriority;
  16029. };
  16030. /**
  16031. * Disposes the light.
  16032. */
  16033. Light.prototype.dispose = function () {
  16034. if (this._shadowGenerator) {
  16035. this._shadowGenerator.dispose();
  16036. this._shadowGenerator = null;
  16037. }
  16038. // Animations
  16039. this.getScene().stopAnimation(this);
  16040. // Remove from meshes
  16041. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  16042. var mesh = _a[_i];
  16043. mesh._removeLightSource(this);
  16044. }
  16045. this._uniformBuffer.dispose();
  16046. // Remove from scene
  16047. this.getScene().removeLight(this);
  16048. _super.prototype.dispose.call(this);
  16049. };
  16050. /**
  16051. * Returns the light type ID (integer).
  16052. */
  16053. Light.prototype.getTypeID = function () {
  16054. return 0;
  16055. };
  16056. /**
  16057. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  16058. */
  16059. Light.prototype.getScaledIntensity = function () {
  16060. return this._photometricScale * this.intensity;
  16061. };
  16062. /**
  16063. * Returns a new Light object, named "name", from the current one.
  16064. */
  16065. Light.prototype.clone = function (name) {
  16066. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  16067. if (!constructor) {
  16068. return null;
  16069. }
  16070. return BABYLON.SerializationHelper.Clone(constructor, this);
  16071. };
  16072. /**
  16073. * Serializes the current light into a Serialization object.
  16074. * Returns the serialized object.
  16075. */
  16076. Light.prototype.serialize = function () {
  16077. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  16078. // Type
  16079. serializationObject.type = this.getTypeID();
  16080. // Parent
  16081. if (this.parent) {
  16082. serializationObject.parentId = this.parent.id;
  16083. }
  16084. // Inclusion / exclusions
  16085. if (this.excludedMeshes.length > 0) {
  16086. serializationObject.excludedMeshesIds = [];
  16087. this.excludedMeshes.forEach(function (mesh) {
  16088. serializationObject.excludedMeshesIds.push(mesh.id);
  16089. });
  16090. }
  16091. if (this.includedOnlyMeshes.length > 0) {
  16092. serializationObject.includedOnlyMeshesIds = [];
  16093. this.includedOnlyMeshes.forEach(function (mesh) {
  16094. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  16095. });
  16096. }
  16097. // Animations
  16098. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  16099. serializationObject.ranges = this.serializeAnimationRanges();
  16100. return serializationObject;
  16101. };
  16102. /**
  16103. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  16104. * This new light is named "name" and added to the passed scene.
  16105. */
  16106. Light.GetConstructorFromName = function (type, name, scene) {
  16107. switch (type) {
  16108. case 0:
  16109. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  16110. case 1:
  16111. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  16112. case 2:
  16113. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  16114. case 3:
  16115. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  16116. }
  16117. return null;
  16118. };
  16119. /**
  16120. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  16121. */
  16122. Light.Parse = function (parsedLight, scene) {
  16123. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  16124. if (!constructor) {
  16125. return null;
  16126. }
  16127. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  16128. // Inclusion / exclusions
  16129. if (parsedLight.excludedMeshesIds) {
  16130. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  16131. }
  16132. if (parsedLight.includedOnlyMeshesIds) {
  16133. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  16134. }
  16135. // Parent
  16136. if (parsedLight.parentId) {
  16137. light._waitingParentId = parsedLight.parentId;
  16138. }
  16139. // Animations
  16140. if (parsedLight.animations) {
  16141. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  16142. var parsedAnimation = parsedLight.animations[animationIndex];
  16143. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16144. }
  16145. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  16146. }
  16147. if (parsedLight.autoAnimate) {
  16148. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  16149. }
  16150. return light;
  16151. };
  16152. Light.prototype._hookArrayForExcluded = function (array) {
  16153. var _this = this;
  16154. var oldPush = array.push;
  16155. array.push = function () {
  16156. var items = [];
  16157. for (var _i = 0; _i < arguments.length; _i++) {
  16158. items[_i] = arguments[_i];
  16159. }
  16160. var result = oldPush.apply(array, items);
  16161. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  16162. var item = items_1[_a];
  16163. item._resyncLighSource(_this);
  16164. }
  16165. return result;
  16166. };
  16167. var oldSplice = array.splice;
  16168. array.splice = function (index, deleteCount) {
  16169. var deleted = oldSplice.apply(array, [index, deleteCount]);
  16170. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  16171. var item = deleted_1[_i];
  16172. item._resyncLighSource(_this);
  16173. }
  16174. return deleted;
  16175. };
  16176. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  16177. var item = array_1[_i];
  16178. item._resyncLighSource(this);
  16179. }
  16180. };
  16181. Light.prototype._hookArrayForIncludedOnly = function (array) {
  16182. var _this = this;
  16183. var oldPush = array.push;
  16184. array.push = function () {
  16185. var items = [];
  16186. for (var _i = 0; _i < arguments.length; _i++) {
  16187. items[_i] = arguments[_i];
  16188. }
  16189. var result = oldPush.apply(array, items);
  16190. _this._resyncMeshes();
  16191. return result;
  16192. };
  16193. var oldSplice = array.splice;
  16194. array.splice = function (index, deleteCount) {
  16195. var deleted = oldSplice.apply(array, [index, deleteCount]);
  16196. _this._resyncMeshes();
  16197. return deleted;
  16198. };
  16199. this._resyncMeshes();
  16200. };
  16201. Light.prototype._resyncMeshes = function () {
  16202. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  16203. var mesh = _a[_i];
  16204. mesh._resyncLighSource(this);
  16205. }
  16206. };
  16207. Light.prototype._markMeshesAsLightDirty = function () {
  16208. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  16209. var mesh = _a[_i];
  16210. if (mesh._lightSources.indexOf(this) !== -1) {
  16211. mesh._markSubMeshesAsLightDirty();
  16212. }
  16213. }
  16214. };
  16215. /**
  16216. * Recomputes the cached photometric scale if needed.
  16217. */
  16218. Light.prototype._computePhotometricScale = function () {
  16219. this._photometricScale = this._getPhotometricScale();
  16220. this.getScene().resetCachedMaterial();
  16221. };
  16222. /**
  16223. * Returns the Photometric Scale according to the light type and intensity mode.
  16224. */
  16225. Light.prototype._getPhotometricScale = function () {
  16226. var photometricScale = 0.0;
  16227. var lightTypeID = this.getTypeID();
  16228. //get photometric mode
  16229. var photometricMode = this.intensityMode;
  16230. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  16231. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  16232. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  16233. }
  16234. else {
  16235. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  16236. }
  16237. }
  16238. //compute photometric scale
  16239. switch (lightTypeID) {
  16240. case Light.LIGHTTYPEID_POINTLIGHT:
  16241. case Light.LIGHTTYPEID_SPOTLIGHT:
  16242. switch (photometricMode) {
  16243. case Light.INTENSITYMODE_LUMINOUSPOWER:
  16244. photometricScale = 1.0 / (4.0 * Math.PI);
  16245. break;
  16246. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  16247. photometricScale = 1.0;
  16248. break;
  16249. case Light.INTENSITYMODE_LUMINANCE:
  16250. photometricScale = this.radius * this.radius;
  16251. break;
  16252. }
  16253. break;
  16254. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  16255. switch (photometricMode) {
  16256. case Light.INTENSITYMODE_ILLUMINANCE:
  16257. photometricScale = 1.0;
  16258. break;
  16259. case Light.INTENSITYMODE_LUMINANCE:
  16260. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  16261. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  16262. var apexAngleRadians = this.radius;
  16263. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  16264. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  16265. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  16266. photometricScale = solidAngle;
  16267. break;
  16268. }
  16269. break;
  16270. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  16271. // No fall off in hemisperic light.
  16272. photometricScale = 1.0;
  16273. break;
  16274. }
  16275. return photometricScale;
  16276. };
  16277. Light.prototype._reorderLightsInScene = function () {
  16278. var scene = this.getScene();
  16279. if (this._renderPriority != 0) {
  16280. scene.requireLightSorting = true;
  16281. }
  16282. this.getScene().sortLightsByPriority();
  16283. };
  16284. //lightmapMode Consts
  16285. Light._LIGHTMAP_DEFAULT = 0;
  16286. Light._LIGHTMAP_SPECULAR = 1;
  16287. Light._LIGHTMAP_SHADOWSONLY = 2;
  16288. // Intensity Mode Consts
  16289. Light._INTENSITYMODE_AUTOMATIC = 0;
  16290. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  16291. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  16292. Light._INTENSITYMODE_ILLUMINANCE = 3;
  16293. Light._INTENSITYMODE_LUMINANCE = 4;
  16294. // Light types ids const.
  16295. Light._LIGHTTYPEID_POINTLIGHT = 0;
  16296. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  16297. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  16298. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  16299. __decorate([
  16300. BABYLON.serializeAsColor3()
  16301. ], Light.prototype, "diffuse", void 0);
  16302. __decorate([
  16303. BABYLON.serializeAsColor3()
  16304. ], Light.prototype, "specular", void 0);
  16305. __decorate([
  16306. BABYLON.serialize()
  16307. ], Light.prototype, "intensity", void 0);
  16308. __decorate([
  16309. BABYLON.serialize()
  16310. ], Light.prototype, "range", void 0);
  16311. __decorate([
  16312. BABYLON.serialize()
  16313. ], Light.prototype, "intensityMode", null);
  16314. __decorate([
  16315. BABYLON.serialize()
  16316. ], Light.prototype, "radius", null);
  16317. __decorate([
  16318. BABYLON.serialize()
  16319. ], Light.prototype, "_renderPriority", void 0);
  16320. __decorate([
  16321. BABYLON.expandToProperty("_reorderLightsInScene")
  16322. ], Light.prototype, "renderPriority", void 0);
  16323. __decorate([
  16324. BABYLON.serialize()
  16325. ], Light.prototype, "shadowEnabled", void 0);
  16326. __decorate([
  16327. BABYLON.serialize("excludeWithLayerMask")
  16328. ], Light.prototype, "_excludeWithLayerMask", void 0);
  16329. __decorate([
  16330. BABYLON.serialize("includeOnlyWithLayerMask")
  16331. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  16332. __decorate([
  16333. BABYLON.serialize("lightmapMode")
  16334. ], Light.prototype, "_lightmapMode", void 0);
  16335. return Light;
  16336. }(BABYLON.Node));
  16337. BABYLON.Light = Light;
  16338. })(BABYLON || (BABYLON = {}));
  16339. //# sourceMappingURL=babylon.light.js.map
  16340. var BABYLON;
  16341. (function (BABYLON) {
  16342. var Camera = /** @class */ (function (_super) {
  16343. __extends(Camera, _super);
  16344. function Camera(name, position, scene) {
  16345. var _this = _super.call(this, name, scene) || this;
  16346. _this.upVector = BABYLON.Vector3.Up();
  16347. _this.orthoLeft = null;
  16348. _this.orthoRight = null;
  16349. _this.orthoBottom = null;
  16350. _this.orthoTop = null;
  16351. _this.fov = 0.8;
  16352. _this.minZ = 1;
  16353. _this.maxZ = 10000.0;
  16354. _this.inertia = 0.9;
  16355. _this.mode = Camera.PERSPECTIVE_CAMERA;
  16356. _this.isIntermediate = false;
  16357. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  16358. _this.layerMask = 0x0FFFFFFF;
  16359. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  16360. // Camera rig members
  16361. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  16362. _this._rigCameras = new Array();
  16363. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  16364. _this._skipRendering = false;
  16365. _this.customRenderTargets = new Array();
  16366. // Observables
  16367. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  16368. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  16369. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  16370. _this.onRestoreStateObservable = new BABYLON.Observable();
  16371. // Cache
  16372. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  16373. _this._projectionMatrix = new BABYLON.Matrix();
  16374. _this._doNotComputeProjectionMatrix = false;
  16375. _this._postProcesses = new Array();
  16376. _this._transformMatrix = BABYLON.Matrix.Zero();
  16377. _this._activeMeshes = new BABYLON.SmartArray(256);
  16378. _this._globalPosition = BABYLON.Vector3.Zero();
  16379. _this._refreshFrustumPlanes = true;
  16380. _this.getScene().addCamera(_this);
  16381. if (!_this.getScene().activeCamera) {
  16382. _this.getScene().activeCamera = _this;
  16383. }
  16384. _this.position = position;
  16385. return _this;
  16386. }
  16387. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  16388. get: function () {
  16389. return Camera._PERSPECTIVE_CAMERA;
  16390. },
  16391. enumerable: true,
  16392. configurable: true
  16393. });
  16394. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  16395. get: function () {
  16396. return Camera._ORTHOGRAPHIC_CAMERA;
  16397. },
  16398. enumerable: true,
  16399. configurable: true
  16400. });
  16401. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  16402. get: function () {
  16403. return Camera._FOVMODE_VERTICAL_FIXED;
  16404. },
  16405. enumerable: true,
  16406. configurable: true
  16407. });
  16408. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  16409. get: function () {
  16410. return Camera._FOVMODE_HORIZONTAL_FIXED;
  16411. },
  16412. enumerable: true,
  16413. configurable: true
  16414. });
  16415. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  16416. get: function () {
  16417. return Camera._RIG_MODE_NONE;
  16418. },
  16419. enumerable: true,
  16420. configurable: true
  16421. });
  16422. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  16423. get: function () {
  16424. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  16425. },
  16426. enumerable: true,
  16427. configurable: true
  16428. });
  16429. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  16430. get: function () {
  16431. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  16432. },
  16433. enumerable: true,
  16434. configurable: true
  16435. });
  16436. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  16437. get: function () {
  16438. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16439. },
  16440. enumerable: true,
  16441. configurable: true
  16442. });
  16443. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  16444. get: function () {
  16445. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  16446. },
  16447. enumerable: true,
  16448. configurable: true
  16449. });
  16450. Object.defineProperty(Camera, "RIG_MODE_VR", {
  16451. get: function () {
  16452. return Camera._RIG_MODE_VR;
  16453. },
  16454. enumerable: true,
  16455. configurable: true
  16456. });
  16457. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  16458. get: function () {
  16459. return Camera._RIG_MODE_WEBVR;
  16460. },
  16461. enumerable: true,
  16462. configurable: true
  16463. });
  16464. /**
  16465. * Store current camera state (fov, position, etc..)
  16466. */
  16467. Camera.prototype.storeState = function () {
  16468. this._stateStored = true;
  16469. this._storedFov = this.fov;
  16470. return this;
  16471. };
  16472. /**
  16473. * Restores the camera state values if it has been stored. You must call storeState() first
  16474. */
  16475. Camera.prototype._restoreStateValues = function () {
  16476. if (!this._stateStored) {
  16477. return false;
  16478. }
  16479. this.fov = this._storedFov;
  16480. return true;
  16481. };
  16482. /**
  16483. * Restored camera state. You must call storeState() first
  16484. */
  16485. Camera.prototype.restoreState = function () {
  16486. if (this._restoreStateValues()) {
  16487. this.onRestoreStateObservable.notifyObservers(this);
  16488. return true;
  16489. }
  16490. return false;
  16491. };
  16492. Camera.prototype.getClassName = function () {
  16493. return "Camera";
  16494. };
  16495. /**
  16496. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16497. */
  16498. Camera.prototype.toString = function (fullDetails) {
  16499. var ret = "Name: " + this.name;
  16500. ret += ", type: " + this.getClassName();
  16501. if (this.animations) {
  16502. for (var i = 0; i < this.animations.length; i++) {
  16503. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  16504. }
  16505. }
  16506. if (fullDetails) {
  16507. }
  16508. return ret;
  16509. };
  16510. Object.defineProperty(Camera.prototype, "globalPosition", {
  16511. get: function () {
  16512. return this._globalPosition;
  16513. },
  16514. enumerable: true,
  16515. configurable: true
  16516. });
  16517. Camera.prototype.getActiveMeshes = function () {
  16518. return this._activeMeshes;
  16519. };
  16520. Camera.prototype.isActiveMesh = function (mesh) {
  16521. return (this._activeMeshes.indexOf(mesh) !== -1);
  16522. };
  16523. //Cache
  16524. Camera.prototype._initCache = function () {
  16525. _super.prototype._initCache.call(this);
  16526. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16527. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16528. this._cache.mode = undefined;
  16529. this._cache.minZ = undefined;
  16530. this._cache.maxZ = undefined;
  16531. this._cache.fov = undefined;
  16532. this._cache.fovMode = undefined;
  16533. this._cache.aspectRatio = undefined;
  16534. this._cache.orthoLeft = undefined;
  16535. this._cache.orthoRight = undefined;
  16536. this._cache.orthoBottom = undefined;
  16537. this._cache.orthoTop = undefined;
  16538. this._cache.renderWidth = undefined;
  16539. this._cache.renderHeight = undefined;
  16540. };
  16541. Camera.prototype._updateCache = function (ignoreParentClass) {
  16542. if (!ignoreParentClass) {
  16543. _super.prototype._updateCache.call(this);
  16544. }
  16545. this._cache.position.copyFrom(this.position);
  16546. this._cache.upVector.copyFrom(this.upVector);
  16547. };
  16548. // Synchronized
  16549. Camera.prototype._isSynchronized = function () {
  16550. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  16551. };
  16552. Camera.prototype._isSynchronizedViewMatrix = function () {
  16553. if (!_super.prototype._isSynchronized.call(this))
  16554. return false;
  16555. return this._cache.position.equals(this.position)
  16556. && this._cache.upVector.equals(this.upVector)
  16557. && this.isSynchronizedWithParent();
  16558. };
  16559. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  16560. var check = this._cache.mode === this.mode
  16561. && this._cache.minZ === this.minZ
  16562. && this._cache.maxZ === this.maxZ;
  16563. if (!check) {
  16564. return false;
  16565. }
  16566. var engine = this.getEngine();
  16567. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16568. check = this._cache.fov === this.fov
  16569. && this._cache.fovMode === this.fovMode
  16570. && this._cache.aspectRatio === engine.getAspectRatio(this);
  16571. }
  16572. else {
  16573. check = this._cache.orthoLeft === this.orthoLeft
  16574. && this._cache.orthoRight === this.orthoRight
  16575. && this._cache.orthoBottom === this.orthoBottom
  16576. && this._cache.orthoTop === this.orthoTop
  16577. && this._cache.renderWidth === engine.getRenderWidth()
  16578. && this._cache.renderHeight === engine.getRenderHeight();
  16579. }
  16580. return check;
  16581. };
  16582. // Controls
  16583. Camera.prototype.attachControl = function (element, noPreventDefault) {
  16584. };
  16585. Camera.prototype.detachControl = function (element) {
  16586. };
  16587. Camera.prototype.update = function () {
  16588. this._checkInputs();
  16589. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16590. this._updateRigCameras();
  16591. }
  16592. };
  16593. Camera.prototype._checkInputs = function () {
  16594. this.onAfterCheckInputsObservable.notifyObservers(this);
  16595. };
  16596. Object.defineProperty(Camera.prototype, "rigCameras", {
  16597. get: function () {
  16598. return this._rigCameras;
  16599. },
  16600. enumerable: true,
  16601. configurable: true
  16602. });
  16603. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  16604. get: function () {
  16605. return this._rigPostProcess;
  16606. },
  16607. enumerable: true,
  16608. configurable: true
  16609. });
  16610. Camera.prototype._cascadePostProcessesToRigCams = function () {
  16611. // invalidate framebuffer
  16612. if (this._postProcesses.length > 0) {
  16613. this._postProcesses[0].markTextureDirty();
  16614. }
  16615. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  16616. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  16617. var cam = this._rigCameras[i];
  16618. var rigPostProcess = cam._rigPostProcess;
  16619. // for VR rig, there does not have to be a post process
  16620. if (rigPostProcess) {
  16621. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  16622. if (isPass) {
  16623. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  16624. cam.isIntermediate = this._postProcesses.length === 0;
  16625. }
  16626. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  16627. rigPostProcess.markTextureDirty();
  16628. }
  16629. else {
  16630. cam._postProcesses = this._postProcesses.slice(0);
  16631. }
  16632. }
  16633. };
  16634. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  16635. if (insertAt === void 0) { insertAt = null; }
  16636. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  16637. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  16638. return 0;
  16639. }
  16640. if (insertAt == null || insertAt < 0) {
  16641. this._postProcesses.push(postProcess);
  16642. }
  16643. else {
  16644. this._postProcesses.splice(insertAt, 0, postProcess);
  16645. }
  16646. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16647. return this._postProcesses.indexOf(postProcess);
  16648. };
  16649. Camera.prototype.detachPostProcess = function (postProcess) {
  16650. var idx = this._postProcesses.indexOf(postProcess);
  16651. if (idx !== -1) {
  16652. this._postProcesses.splice(idx, 1);
  16653. }
  16654. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16655. };
  16656. Camera.prototype.getWorldMatrix = function () {
  16657. if (!this._worldMatrix) {
  16658. this._worldMatrix = BABYLON.Matrix.Identity();
  16659. }
  16660. var viewMatrix = this.getViewMatrix();
  16661. viewMatrix.invertToRef(this._worldMatrix);
  16662. return this._worldMatrix;
  16663. };
  16664. Camera.prototype._getViewMatrix = function () {
  16665. return BABYLON.Matrix.Identity();
  16666. };
  16667. Camera.prototype.getViewMatrix = function (force) {
  16668. if (!force && this._isSynchronizedViewMatrix()) {
  16669. return this._computedViewMatrix;
  16670. }
  16671. this.updateCache();
  16672. this._computedViewMatrix = this._getViewMatrix();
  16673. this._currentRenderId = this.getScene().getRenderId();
  16674. this._refreshFrustumPlanes = true;
  16675. if (!this.parent || !this.parent.getWorldMatrix) {
  16676. this._globalPosition.copyFrom(this.position);
  16677. }
  16678. else {
  16679. if (!this._worldMatrix) {
  16680. this._worldMatrix = BABYLON.Matrix.Identity();
  16681. }
  16682. this._computedViewMatrix.invertToRef(this._worldMatrix);
  16683. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  16684. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  16685. this._computedViewMatrix.invert();
  16686. this._markSyncedWithParent();
  16687. }
  16688. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  16689. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  16690. }
  16691. this.onViewMatrixChangedObservable.notifyObservers(this);
  16692. return this._computedViewMatrix;
  16693. };
  16694. Camera.prototype.freezeProjectionMatrix = function (projection) {
  16695. this._doNotComputeProjectionMatrix = true;
  16696. if (projection !== undefined) {
  16697. this._projectionMatrix = projection;
  16698. }
  16699. };
  16700. ;
  16701. Camera.prototype.unfreezeProjectionMatrix = function () {
  16702. this._doNotComputeProjectionMatrix = false;
  16703. };
  16704. ;
  16705. Camera.prototype.getProjectionMatrix = function (force) {
  16706. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  16707. return this._projectionMatrix;
  16708. }
  16709. // Cache
  16710. this._cache.mode = this.mode;
  16711. this._cache.minZ = this.minZ;
  16712. this._cache.maxZ = this.maxZ;
  16713. // Matrix
  16714. this._refreshFrustumPlanes = true;
  16715. var engine = this.getEngine();
  16716. var scene = this.getScene();
  16717. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16718. this._cache.fov = this.fov;
  16719. this._cache.fovMode = this.fovMode;
  16720. this._cache.aspectRatio = engine.getAspectRatio(this);
  16721. if (this.minZ <= 0) {
  16722. this.minZ = 0.1;
  16723. }
  16724. if (scene.useRightHandedSystem) {
  16725. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16726. }
  16727. else {
  16728. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16729. }
  16730. }
  16731. else {
  16732. var halfWidth = engine.getRenderWidth() / 2.0;
  16733. var halfHeight = engine.getRenderHeight() / 2.0;
  16734. if (scene.useRightHandedSystem) {
  16735. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16736. }
  16737. else {
  16738. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16739. }
  16740. this._cache.orthoLeft = this.orthoLeft;
  16741. this._cache.orthoRight = this.orthoRight;
  16742. this._cache.orthoBottom = this.orthoBottom;
  16743. this._cache.orthoTop = this.orthoTop;
  16744. this._cache.renderWidth = engine.getRenderWidth();
  16745. this._cache.renderHeight = engine.getRenderHeight();
  16746. }
  16747. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  16748. return this._projectionMatrix;
  16749. };
  16750. Camera.prototype.getTranformationMatrix = function () {
  16751. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16752. return this._transformMatrix;
  16753. };
  16754. Camera.prototype.updateFrustumPlanes = function () {
  16755. if (!this._refreshFrustumPlanes) {
  16756. return;
  16757. }
  16758. this.getTranformationMatrix();
  16759. if (!this._frustumPlanes) {
  16760. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16761. }
  16762. else {
  16763. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16764. }
  16765. this._refreshFrustumPlanes = false;
  16766. };
  16767. Camera.prototype.isInFrustum = function (target) {
  16768. this.updateFrustumPlanes();
  16769. return target.isInFrustum(this._frustumPlanes);
  16770. };
  16771. Camera.prototype.isCompletelyInFrustum = function (target) {
  16772. this.updateFrustumPlanes();
  16773. return target.isCompletelyInFrustum(this._frustumPlanes);
  16774. };
  16775. Camera.prototype.getForwardRay = function (length, transform, origin) {
  16776. if (length === void 0) { length = 100; }
  16777. if (!transform) {
  16778. transform = this.getWorldMatrix();
  16779. }
  16780. if (!origin) {
  16781. origin = this.position;
  16782. }
  16783. var forward = new BABYLON.Vector3(0, 0, 1);
  16784. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  16785. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  16786. return new BABYLON.Ray(origin, direction, length);
  16787. };
  16788. Camera.prototype.dispose = function () {
  16789. // Observables
  16790. this.onViewMatrixChangedObservable.clear();
  16791. this.onProjectionMatrixChangedObservable.clear();
  16792. this.onAfterCheckInputsObservable.clear();
  16793. this.onRestoreStateObservable.clear();
  16794. // Inputs
  16795. if (this.inputs) {
  16796. this.inputs.clear();
  16797. }
  16798. // Animations
  16799. this.getScene().stopAnimation(this);
  16800. // Remove from scene
  16801. this.getScene().removeCamera(this);
  16802. while (this._rigCameras.length > 0) {
  16803. var camera = this._rigCameras.pop();
  16804. if (camera) {
  16805. camera.dispose();
  16806. }
  16807. }
  16808. // Postprocesses
  16809. if (this._rigPostProcess) {
  16810. this._rigPostProcess.dispose(this);
  16811. this._rigPostProcess = null;
  16812. this._postProcesses = [];
  16813. }
  16814. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16815. this._rigPostProcess = null;
  16816. this._postProcesses = [];
  16817. }
  16818. else {
  16819. var i = this._postProcesses.length;
  16820. while (--i >= 0) {
  16821. this._postProcesses[i].dispose(this);
  16822. }
  16823. }
  16824. // Render targets
  16825. var i = this.customRenderTargets.length;
  16826. while (--i >= 0) {
  16827. this.customRenderTargets[i].dispose();
  16828. }
  16829. this.customRenderTargets = [];
  16830. // Active Meshes
  16831. this._activeMeshes.dispose();
  16832. _super.prototype.dispose.call(this);
  16833. };
  16834. Object.defineProperty(Camera.prototype, "leftCamera", {
  16835. // ---- Camera rigs section ----
  16836. get: function () {
  16837. if (this._rigCameras.length < 1) {
  16838. return null;
  16839. }
  16840. return this._rigCameras[0];
  16841. },
  16842. enumerable: true,
  16843. configurable: true
  16844. });
  16845. Object.defineProperty(Camera.prototype, "rightCamera", {
  16846. get: function () {
  16847. if (this._rigCameras.length < 2) {
  16848. return null;
  16849. }
  16850. return this._rigCameras[1];
  16851. },
  16852. enumerable: true,
  16853. configurable: true
  16854. });
  16855. Camera.prototype.getLeftTarget = function () {
  16856. if (this._rigCameras.length < 1) {
  16857. return null;
  16858. }
  16859. return this._rigCameras[0].getTarget();
  16860. };
  16861. Camera.prototype.getRightTarget = function () {
  16862. if (this._rigCameras.length < 2) {
  16863. return null;
  16864. }
  16865. return this._rigCameras[1].getTarget();
  16866. };
  16867. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  16868. if (this.cameraRigMode === mode) {
  16869. return;
  16870. }
  16871. while (this._rigCameras.length > 0) {
  16872. var camera = this._rigCameras.pop();
  16873. if (camera) {
  16874. camera.dispose();
  16875. }
  16876. }
  16877. this.cameraRigMode = mode;
  16878. this._cameraRigParams = {};
  16879. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  16880. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  16881. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  16882. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  16883. // create the rig cameras, unless none
  16884. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16885. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  16886. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  16887. if (leftCamera && rightCamera) {
  16888. this._rigCameras.push(leftCamera);
  16889. this._rigCameras.push(rightCamera);
  16890. }
  16891. }
  16892. switch (this.cameraRigMode) {
  16893. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  16894. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16895. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  16896. break;
  16897. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  16898. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  16899. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  16900. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16901. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16902. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  16903. break;
  16904. case Camera.RIG_MODE_VR:
  16905. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  16906. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  16907. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16908. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16909. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  16910. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  16911. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  16912. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  16913. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16914. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16915. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  16916. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  16917. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  16918. if (metrics.compensateDistortion) {
  16919. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  16920. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  16921. }
  16922. break;
  16923. case Camera.RIG_MODE_WEBVR:
  16924. if (rigParams.vrDisplay) {
  16925. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  16926. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  16927. //Left eye
  16928. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16929. this._rigCameras[0].setCameraRigParameter("left", true);
  16930. //leaving this for future reference
  16931. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  16932. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  16933. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  16934. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16935. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16936. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16937. this._rigCameras[0].parent = this;
  16938. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  16939. //Right eye
  16940. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16941. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  16942. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  16943. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  16944. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16945. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16946. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16947. this._rigCameras[1].parent = this;
  16948. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  16949. if (Camera.UseAlternateWebVRRendering) {
  16950. this._rigCameras[1]._skipRendering = true;
  16951. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  16952. }
  16953. }
  16954. break;
  16955. }
  16956. this._cascadePostProcessesToRigCams();
  16957. this.update();
  16958. };
  16959. Camera.prototype._getVRProjectionMatrix = function () {
  16960. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  16961. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  16962. return this._projectionMatrix;
  16963. };
  16964. Camera.prototype._updateCameraRotationMatrix = function () {
  16965. //Here for WebVR
  16966. };
  16967. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  16968. //Here for WebVR
  16969. };
  16970. /**
  16971. * This function MUST be overwritten by the different WebVR cameras available.
  16972. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16973. */
  16974. Camera.prototype._getWebVRProjectionMatrix = function () {
  16975. return BABYLON.Matrix.Identity();
  16976. };
  16977. /**
  16978. * This function MUST be overwritten by the different WebVR cameras available.
  16979. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16980. */
  16981. Camera.prototype._getWebVRViewMatrix = function () {
  16982. return BABYLON.Matrix.Identity();
  16983. };
  16984. Camera.prototype.setCameraRigParameter = function (name, value) {
  16985. if (!this._cameraRigParams) {
  16986. this._cameraRigParams = {};
  16987. }
  16988. this._cameraRigParams[name] = value;
  16989. //provisionnally:
  16990. if (name === "interaxialDistance") {
  16991. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  16992. }
  16993. };
  16994. /**
  16995. * needs to be overridden by children so sub has required properties to be copied
  16996. */
  16997. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  16998. return null;
  16999. };
  17000. /**
  17001. * May need to be overridden by children
  17002. */
  17003. Camera.prototype._updateRigCameras = function () {
  17004. for (var i = 0; i < this._rigCameras.length; i++) {
  17005. this._rigCameras[i].minZ = this.minZ;
  17006. this._rigCameras[i].maxZ = this.maxZ;
  17007. this._rigCameras[i].fov = this.fov;
  17008. }
  17009. // only update viewport when ANAGLYPH
  17010. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  17011. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  17012. }
  17013. };
  17014. Camera.prototype._setupInputs = function () {
  17015. };
  17016. Camera.prototype.serialize = function () {
  17017. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  17018. // Type
  17019. serializationObject.type = this.getClassName();
  17020. // Parent
  17021. if (this.parent) {
  17022. serializationObject.parentId = this.parent.id;
  17023. }
  17024. if (this.inputs) {
  17025. this.inputs.serialize(serializationObject);
  17026. }
  17027. // Animations
  17028. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17029. serializationObject.ranges = this.serializeAnimationRanges();
  17030. return serializationObject;
  17031. };
  17032. Camera.prototype.clone = function (name) {
  17033. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  17034. };
  17035. Camera.prototype.getDirection = function (localAxis) {
  17036. var result = BABYLON.Vector3.Zero();
  17037. this.getDirectionToRef(localAxis, result);
  17038. return result;
  17039. };
  17040. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  17041. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  17042. };
  17043. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  17044. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  17045. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  17046. switch (type) {
  17047. case "ArcRotateCamera":
  17048. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  17049. case "DeviceOrientationCamera":
  17050. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  17051. case "FollowCamera":
  17052. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  17053. case "ArcFollowCamera":
  17054. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  17055. case "GamepadCamera":
  17056. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  17057. case "TouchCamera":
  17058. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  17059. case "VirtualJoysticksCamera":
  17060. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  17061. case "WebVRFreeCamera":
  17062. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  17063. case "WebVRGamepadCamera":
  17064. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  17065. case "VRDeviceOrientationFreeCamera":
  17066. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  17067. case "VRDeviceOrientationGamepadCamera":
  17068. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  17069. case "AnaglyphArcRotateCamera":
  17070. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  17071. case "AnaglyphFreeCamera":
  17072. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  17073. case "AnaglyphGamepadCamera":
  17074. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  17075. case "AnaglyphUniversalCamera":
  17076. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  17077. case "StereoscopicArcRotateCamera":
  17078. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  17079. case "StereoscopicFreeCamera":
  17080. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  17081. case "StereoscopicGamepadCamera":
  17082. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  17083. case "StereoscopicUniversalCamera":
  17084. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  17085. case "FreeCamera":// Forcing Universal here
  17086. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  17087. default:// Universal Camera is the default value
  17088. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  17089. }
  17090. };
  17091. Camera.prototype.computeWorldMatrix = function () {
  17092. return this.getWorldMatrix();
  17093. };
  17094. Camera.Parse = function (parsedCamera, scene) {
  17095. var type = parsedCamera.type;
  17096. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  17097. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  17098. // Parent
  17099. if (parsedCamera.parentId) {
  17100. camera._waitingParentId = parsedCamera.parentId;
  17101. }
  17102. //If camera has an input manager, let it parse inputs settings
  17103. if (camera.inputs) {
  17104. camera.inputs.parse(parsedCamera);
  17105. camera._setupInputs();
  17106. }
  17107. if (camera.setPosition) {
  17108. camera.position.copyFromFloats(0, 0, 0);
  17109. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  17110. }
  17111. // Target
  17112. if (parsedCamera.target) {
  17113. if (camera.setTarget) {
  17114. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  17115. }
  17116. }
  17117. // Apply 3d rig, when found
  17118. if (parsedCamera.cameraRigMode) {
  17119. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  17120. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  17121. }
  17122. // Animations
  17123. if (parsedCamera.animations) {
  17124. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  17125. var parsedAnimation = parsedCamera.animations[animationIndex];
  17126. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17127. }
  17128. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  17129. }
  17130. if (parsedCamera.autoAnimate) {
  17131. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  17132. }
  17133. return camera;
  17134. };
  17135. // Statics
  17136. Camera._PERSPECTIVE_CAMERA = 0;
  17137. Camera._ORTHOGRAPHIC_CAMERA = 1;
  17138. Camera._FOVMODE_VERTICAL_FIXED = 0;
  17139. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  17140. Camera._RIG_MODE_NONE = 0;
  17141. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  17142. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  17143. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  17144. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  17145. Camera._RIG_MODE_VR = 20;
  17146. Camera._RIG_MODE_WEBVR = 21;
  17147. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  17148. Camera.UseAlternateWebVRRendering = false;
  17149. __decorate([
  17150. BABYLON.serializeAsVector3()
  17151. ], Camera.prototype, "position", void 0);
  17152. __decorate([
  17153. BABYLON.serializeAsVector3()
  17154. ], Camera.prototype, "upVector", void 0);
  17155. __decorate([
  17156. BABYLON.serialize()
  17157. ], Camera.prototype, "orthoLeft", void 0);
  17158. __decorate([
  17159. BABYLON.serialize()
  17160. ], Camera.prototype, "orthoRight", void 0);
  17161. __decorate([
  17162. BABYLON.serialize()
  17163. ], Camera.prototype, "orthoBottom", void 0);
  17164. __decorate([
  17165. BABYLON.serialize()
  17166. ], Camera.prototype, "orthoTop", void 0);
  17167. __decorate([
  17168. BABYLON.serialize()
  17169. ], Camera.prototype, "fov", void 0);
  17170. __decorate([
  17171. BABYLON.serialize()
  17172. ], Camera.prototype, "minZ", void 0);
  17173. __decorate([
  17174. BABYLON.serialize()
  17175. ], Camera.prototype, "maxZ", void 0);
  17176. __decorate([
  17177. BABYLON.serialize()
  17178. ], Camera.prototype, "inertia", void 0);
  17179. __decorate([
  17180. BABYLON.serialize()
  17181. ], Camera.prototype, "mode", void 0);
  17182. __decorate([
  17183. BABYLON.serialize()
  17184. ], Camera.prototype, "layerMask", void 0);
  17185. __decorate([
  17186. BABYLON.serialize()
  17187. ], Camera.prototype, "fovMode", void 0);
  17188. __decorate([
  17189. BABYLON.serialize()
  17190. ], Camera.prototype, "cameraRigMode", void 0);
  17191. __decorate([
  17192. BABYLON.serialize()
  17193. ], Camera.prototype, "interaxialDistance", void 0);
  17194. __decorate([
  17195. BABYLON.serialize()
  17196. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  17197. return Camera;
  17198. }(BABYLON.Node));
  17199. BABYLON.Camera = Camera;
  17200. })(BABYLON || (BABYLON = {}));
  17201. //# sourceMappingURL=babylon.camera.js.map
  17202. var BABYLON;
  17203. (function (BABYLON) {
  17204. var RenderingManager = /** @class */ (function () {
  17205. function RenderingManager(scene) {
  17206. this._renderingGroups = new Array();
  17207. this._autoClearDepthStencil = {};
  17208. this._customOpaqueSortCompareFn = {};
  17209. this._customAlphaTestSortCompareFn = {};
  17210. this._customTransparentSortCompareFn = {};
  17211. this._renderinGroupInfo = null;
  17212. this._scene = scene;
  17213. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  17214. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  17215. }
  17216. }
  17217. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  17218. if (depth === void 0) { depth = true; }
  17219. if (stencil === void 0) { stencil = true; }
  17220. if (this._depthStencilBufferAlreadyCleaned) {
  17221. return;
  17222. }
  17223. this._scene.getEngine().clear(null, false, depth, stencil);
  17224. this._depthStencilBufferAlreadyCleaned = true;
  17225. };
  17226. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  17227. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  17228. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  17229. var info = null;
  17230. if (observable) {
  17231. if (!this._renderinGroupInfo) {
  17232. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  17233. }
  17234. info = this._renderinGroupInfo;
  17235. info.scene = this._scene;
  17236. info.camera = this._scene.activeCamera;
  17237. }
  17238. // Dispatch sprites
  17239. if (renderSprites) {
  17240. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  17241. var manager = this._scene.spriteManagers[index];
  17242. this.dispatchSprites(manager);
  17243. }
  17244. }
  17245. // Render
  17246. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  17247. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  17248. var renderingGroup = this._renderingGroups[index];
  17249. if (!renderingGroup && !observable)
  17250. continue;
  17251. var renderingGroupMask = 0;
  17252. // Fire PRECLEAR stage
  17253. if (observable && info) {
  17254. renderingGroupMask = Math.pow(2, index);
  17255. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  17256. info.renderingGroupId = index;
  17257. observable.notifyObservers(info, renderingGroupMask);
  17258. }
  17259. // Clear depth/stencil if needed
  17260. if (RenderingManager.AUTOCLEAR) {
  17261. var autoClear = this._autoClearDepthStencil[index];
  17262. if (autoClear && autoClear.autoClear) {
  17263. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  17264. }
  17265. }
  17266. if (observable && info) {
  17267. // Fire PREOPAQUE stage
  17268. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  17269. observable.notifyObservers(info, renderingGroupMask);
  17270. // Fire PRETRANSPARENT stage
  17271. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  17272. observable.notifyObservers(info, renderingGroupMask);
  17273. }
  17274. if (renderingGroup)
  17275. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  17276. // Fire POSTTRANSPARENT stage
  17277. if (observable && info) {
  17278. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  17279. observable.notifyObservers(info, renderingGroupMask);
  17280. }
  17281. }
  17282. };
  17283. RenderingManager.prototype.reset = function () {
  17284. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  17285. var renderingGroup = this._renderingGroups[index];
  17286. if (renderingGroup) {
  17287. renderingGroup.prepare();
  17288. }
  17289. }
  17290. };
  17291. RenderingManager.prototype.dispose = function () {
  17292. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  17293. var renderingGroup = this._renderingGroups[index];
  17294. if (renderingGroup) {
  17295. renderingGroup.dispose();
  17296. }
  17297. }
  17298. this._renderingGroups.length = 0;
  17299. };
  17300. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  17301. if (!this._renderingGroups[renderingGroupId]) {
  17302. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  17303. }
  17304. };
  17305. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  17306. var renderingGroupId = spriteManager.renderingGroupId || 0;
  17307. this._prepareRenderingGroup(renderingGroupId);
  17308. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  17309. };
  17310. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  17311. var renderingGroupId = particleSystem.renderingGroupId || 0;
  17312. this._prepareRenderingGroup(renderingGroupId);
  17313. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  17314. };
  17315. RenderingManager.prototype.dispatch = function (subMesh) {
  17316. var mesh = subMesh.getMesh();
  17317. var renderingGroupId = mesh.renderingGroupId || 0;
  17318. this._prepareRenderingGroup(renderingGroupId);
  17319. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  17320. };
  17321. /**
  17322. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  17323. * This allowed control for front to back rendering or reversly depending of the special needs.
  17324. *
  17325. * @param renderingGroupId The rendering group id corresponding to its index
  17326. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  17327. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  17328. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  17329. */
  17330. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  17331. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  17332. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  17333. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  17334. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  17335. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  17336. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  17337. if (this._renderingGroups[renderingGroupId]) {
  17338. var group = this._renderingGroups[renderingGroupId];
  17339. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  17340. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  17341. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  17342. }
  17343. };
  17344. /**
  17345. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  17346. *
  17347. * @param renderingGroupId The rendering group id corresponding to its index
  17348. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  17349. * @param depth Automatically clears depth between groups if true and autoClear is true.
  17350. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  17351. */
  17352. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  17353. if (depth === void 0) { depth = true; }
  17354. if (stencil === void 0) { stencil = true; }
  17355. this._autoClearDepthStencil[renderingGroupId] = {
  17356. autoClear: autoClearDepthStencil,
  17357. depth: depth,
  17358. stencil: stencil
  17359. };
  17360. };
  17361. /**
  17362. * The max id used for rendering groups (not included)
  17363. */
  17364. RenderingManager.MAX_RENDERINGGROUPS = 4;
  17365. /**
  17366. * The min id used for rendering groups (included)
  17367. */
  17368. RenderingManager.MIN_RENDERINGGROUPS = 0;
  17369. /**
  17370. * Used to globally prevent autoclearing scenes.
  17371. */
  17372. RenderingManager.AUTOCLEAR = true;
  17373. return RenderingManager;
  17374. }());
  17375. BABYLON.RenderingManager = RenderingManager;
  17376. })(BABYLON || (BABYLON = {}));
  17377. //# sourceMappingURL=babylon.renderingManager.js.map
  17378. var BABYLON;
  17379. (function (BABYLON) {
  17380. var RenderingGroup = /** @class */ (function () {
  17381. /**
  17382. * Creates a new rendering group.
  17383. * @param index The rendering group index
  17384. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  17385. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  17386. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  17387. */
  17388. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  17389. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  17390. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  17391. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  17392. this.index = index;
  17393. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  17394. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  17395. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  17396. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  17397. this._particleSystems = new BABYLON.SmartArray(256);
  17398. this._spriteManagers = new BABYLON.SmartArray(256);
  17399. this._edgesRenderers = new BABYLON.SmartArray(16);
  17400. this._scene = scene;
  17401. this.opaqueSortCompareFn = opaqueSortCompareFn;
  17402. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  17403. this.transparentSortCompareFn = transparentSortCompareFn;
  17404. }
  17405. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  17406. /**
  17407. * Set the opaque sort comparison function.
  17408. * If null the sub meshes will be render in the order they were created
  17409. */
  17410. set: function (value) {
  17411. this._opaqueSortCompareFn = value;
  17412. if (value) {
  17413. this._renderOpaque = this.renderOpaqueSorted;
  17414. }
  17415. else {
  17416. this._renderOpaque = RenderingGroup.renderUnsorted;
  17417. }
  17418. },
  17419. enumerable: true,
  17420. configurable: true
  17421. });
  17422. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  17423. /**
  17424. * Set the alpha test sort comparison function.
  17425. * If null the sub meshes will be render in the order they were created
  17426. */
  17427. set: function (value) {
  17428. this._alphaTestSortCompareFn = value;
  17429. if (value) {
  17430. this._renderAlphaTest = this.renderAlphaTestSorted;
  17431. }
  17432. else {
  17433. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  17434. }
  17435. },
  17436. enumerable: true,
  17437. configurable: true
  17438. });
  17439. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  17440. /**
  17441. * Set the transparent sort comparison function.
  17442. * If null the sub meshes will be render in the order they were created
  17443. */
  17444. set: function (value) {
  17445. if (value) {
  17446. this._transparentSortCompareFn = value;
  17447. }
  17448. else {
  17449. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  17450. }
  17451. this._renderTransparent = this.renderTransparentSorted;
  17452. },
  17453. enumerable: true,
  17454. configurable: true
  17455. });
  17456. /**
  17457. * Render all the sub meshes contained in the group.
  17458. * @param customRenderFunction Used to override the default render behaviour of the group.
  17459. * @returns true if rendered some submeshes.
  17460. */
  17461. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  17462. if (customRenderFunction) {
  17463. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  17464. return;
  17465. }
  17466. var engine = this._scene.getEngine();
  17467. // Depth only
  17468. if (this._depthOnlySubMeshes.length !== 0) {
  17469. engine.setAlphaTesting(true);
  17470. engine.setColorWrite(false);
  17471. this._renderAlphaTest(this._depthOnlySubMeshes);
  17472. engine.setAlphaTesting(false);
  17473. engine.setColorWrite(true);
  17474. }
  17475. // Opaque
  17476. if (this._opaqueSubMeshes.length !== 0) {
  17477. this._renderOpaque(this._opaqueSubMeshes);
  17478. }
  17479. // Alpha test
  17480. if (this._alphaTestSubMeshes.length !== 0) {
  17481. engine.setAlphaTesting(true);
  17482. this._renderAlphaTest(this._alphaTestSubMeshes);
  17483. engine.setAlphaTesting(false);
  17484. }
  17485. var stencilState = engine.getStencilBuffer();
  17486. engine.setStencilBuffer(false);
  17487. // Sprites
  17488. if (renderSprites) {
  17489. this._renderSprites();
  17490. }
  17491. // Particles
  17492. if (renderParticles) {
  17493. this._renderParticles(activeMeshes);
  17494. }
  17495. if (this.onBeforeTransparentRendering) {
  17496. this.onBeforeTransparentRendering();
  17497. }
  17498. // Transparent
  17499. if (this._transparentSubMeshes.length !== 0) {
  17500. this._renderTransparent(this._transparentSubMeshes);
  17501. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17502. }
  17503. // Set back stencil to false in case it changes before the edge renderer.
  17504. engine.setStencilBuffer(false);
  17505. // Edges
  17506. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  17507. this._edgesRenderers.data[edgesRendererIndex].render();
  17508. }
  17509. // Restore Stencil state.
  17510. engine.setStencilBuffer(stencilState);
  17511. };
  17512. /**
  17513. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  17514. * @param subMeshes The submeshes to render
  17515. */
  17516. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  17517. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  17518. };
  17519. /**
  17520. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  17521. * @param subMeshes The submeshes to render
  17522. */
  17523. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  17524. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  17525. };
  17526. /**
  17527. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  17528. * @param subMeshes The submeshes to render
  17529. */
  17530. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  17531. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  17532. };
  17533. /**
  17534. * Renders the submeshes in a specified order.
  17535. * @param subMeshes The submeshes to sort before render
  17536. * @param sortCompareFn The comparison function use to sort
  17537. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  17538. * @param transparent Specifies to activate blending if true
  17539. */
  17540. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  17541. var subIndex = 0;
  17542. var subMesh;
  17543. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  17544. for (; subIndex < subMeshes.length; subIndex++) {
  17545. subMesh = subMeshes.data[subIndex];
  17546. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  17547. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  17548. }
  17549. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  17550. if (sortCompareFn) {
  17551. sortedArray.sort(sortCompareFn);
  17552. }
  17553. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  17554. subMesh = sortedArray[subIndex];
  17555. if (transparent) {
  17556. var material = subMesh.getMaterial();
  17557. if (material && material.needDepthPrePass) {
  17558. var engine = material.getScene().getEngine();
  17559. engine.setColorWrite(false);
  17560. engine.setAlphaTesting(true);
  17561. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17562. subMesh.render(false);
  17563. engine.setAlphaTesting(false);
  17564. engine.setColorWrite(true);
  17565. }
  17566. }
  17567. subMesh.render(transparent);
  17568. }
  17569. };
  17570. /**
  17571. * Renders the submeshes in the order they were dispatched (no sort applied).
  17572. * @param subMeshes The submeshes to render
  17573. */
  17574. RenderingGroup.renderUnsorted = function (subMeshes) {
  17575. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  17576. var submesh = subMeshes.data[subIndex];
  17577. submesh.render(false);
  17578. }
  17579. };
  17580. /**
  17581. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17582. * are rendered back to front if in the same alpha index.
  17583. *
  17584. * @param a The first submesh
  17585. * @param b The second submesh
  17586. * @returns The result of the comparison
  17587. */
  17588. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  17589. // Alpha index first
  17590. if (a._alphaIndex > b._alphaIndex) {
  17591. return 1;
  17592. }
  17593. if (a._alphaIndex < b._alphaIndex) {
  17594. return -1;
  17595. }
  17596. // Then distance to camera
  17597. return RenderingGroup.backToFrontSortCompare(a, b);
  17598. };
  17599. /**
  17600. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17601. * are rendered back to front.
  17602. *
  17603. * @param a The first submesh
  17604. * @param b The second submesh
  17605. * @returns The result of the comparison
  17606. */
  17607. RenderingGroup.backToFrontSortCompare = function (a, b) {
  17608. // Then distance to camera
  17609. if (a._distanceToCamera < b._distanceToCamera) {
  17610. return 1;
  17611. }
  17612. if (a._distanceToCamera > b._distanceToCamera) {
  17613. return -1;
  17614. }
  17615. return 0;
  17616. };
  17617. /**
  17618. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17619. * are rendered front to back (prevent overdraw).
  17620. *
  17621. * @param a The first submesh
  17622. * @param b The second submesh
  17623. * @returns The result of the comparison
  17624. */
  17625. RenderingGroup.frontToBackSortCompare = function (a, b) {
  17626. // Then distance to camera
  17627. if (a._distanceToCamera < b._distanceToCamera) {
  17628. return -1;
  17629. }
  17630. if (a._distanceToCamera > b._distanceToCamera) {
  17631. return 1;
  17632. }
  17633. return 0;
  17634. };
  17635. /**
  17636. * Resets the different lists of submeshes to prepare a new frame.
  17637. */
  17638. RenderingGroup.prototype.prepare = function () {
  17639. this._opaqueSubMeshes.reset();
  17640. this._transparentSubMeshes.reset();
  17641. this._alphaTestSubMeshes.reset();
  17642. this._depthOnlySubMeshes.reset();
  17643. this._particleSystems.reset();
  17644. this._spriteManagers.reset();
  17645. this._edgesRenderers.reset();
  17646. };
  17647. RenderingGroup.prototype.dispose = function () {
  17648. this._opaqueSubMeshes.dispose();
  17649. this._transparentSubMeshes.dispose();
  17650. this._alphaTestSubMeshes.dispose();
  17651. this._depthOnlySubMeshes.dispose();
  17652. this._particleSystems.dispose();
  17653. this._spriteManagers.dispose();
  17654. this._edgesRenderers.dispose();
  17655. };
  17656. /**
  17657. * Inserts the submesh in its correct queue depending on its material.
  17658. * @param subMesh The submesh to dispatch
  17659. */
  17660. RenderingGroup.prototype.dispatch = function (subMesh) {
  17661. var material = subMesh.getMaterial();
  17662. var mesh = subMesh.getMesh();
  17663. if (!material) {
  17664. return;
  17665. }
  17666. if (material.needAlphaBlendingForMesh(mesh)) {
  17667. this._transparentSubMeshes.push(subMesh);
  17668. }
  17669. else if (material.needAlphaTesting()) {
  17670. if (material.needDepthPrePass) {
  17671. this._depthOnlySubMeshes.push(subMesh);
  17672. }
  17673. this._alphaTestSubMeshes.push(subMesh);
  17674. }
  17675. else {
  17676. if (material.needDepthPrePass) {
  17677. this._depthOnlySubMeshes.push(subMesh);
  17678. }
  17679. this._opaqueSubMeshes.push(subMesh); // Opaque
  17680. }
  17681. if (mesh._edgesRenderer) {
  17682. this._edgesRenderers.push(mesh._edgesRenderer);
  17683. }
  17684. };
  17685. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  17686. this._spriteManagers.push(spriteManager);
  17687. };
  17688. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  17689. this._particleSystems.push(particleSystem);
  17690. };
  17691. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  17692. if (this._particleSystems.length === 0) {
  17693. return;
  17694. }
  17695. // Particles
  17696. var activeCamera = this._scene.activeCamera;
  17697. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  17698. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  17699. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  17700. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  17701. continue;
  17702. }
  17703. var emitter = particleSystem.emitter;
  17704. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  17705. this._scene._activeParticles.addCount(particleSystem.render(), false);
  17706. }
  17707. }
  17708. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  17709. };
  17710. RenderingGroup.prototype._renderSprites = function () {
  17711. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  17712. return;
  17713. }
  17714. // Sprites
  17715. var activeCamera = this._scene.activeCamera;
  17716. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  17717. for (var id = 0; id < this._spriteManagers.length; id++) {
  17718. var spriteManager = this._spriteManagers.data[id];
  17719. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  17720. spriteManager.render();
  17721. }
  17722. }
  17723. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  17724. };
  17725. return RenderingGroup;
  17726. }());
  17727. BABYLON.RenderingGroup = RenderingGroup;
  17728. })(BABYLON || (BABYLON = {}));
  17729. //# sourceMappingURL=babylon.renderingGroup.js.map
  17730. var BABYLON;
  17731. (function (BABYLON) {
  17732. var ClickInfo = /** @class */ (function () {
  17733. function ClickInfo() {
  17734. this._singleClick = false;
  17735. this._doubleClick = false;
  17736. this._hasSwiped = false;
  17737. this._ignore = false;
  17738. }
  17739. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  17740. get: function () {
  17741. return this._singleClick;
  17742. },
  17743. set: function (b) {
  17744. this._singleClick = b;
  17745. },
  17746. enumerable: true,
  17747. configurable: true
  17748. });
  17749. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  17750. get: function () {
  17751. return this._doubleClick;
  17752. },
  17753. set: function (b) {
  17754. this._doubleClick = b;
  17755. },
  17756. enumerable: true,
  17757. configurable: true
  17758. });
  17759. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  17760. get: function () {
  17761. return this._hasSwiped;
  17762. },
  17763. set: function (b) {
  17764. this._hasSwiped = b;
  17765. },
  17766. enumerable: true,
  17767. configurable: true
  17768. });
  17769. Object.defineProperty(ClickInfo.prototype, "ignore", {
  17770. get: function () {
  17771. return this._ignore;
  17772. },
  17773. set: function (b) {
  17774. this._ignore = b;
  17775. },
  17776. enumerable: true,
  17777. configurable: true
  17778. });
  17779. return ClickInfo;
  17780. }());
  17781. /**
  17782. * This class is used by the onRenderingGroupObservable
  17783. */
  17784. var RenderingGroupInfo = /** @class */ (function () {
  17785. function RenderingGroupInfo() {
  17786. }
  17787. /**
  17788. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  17789. * This stage will be fired no matter what
  17790. */
  17791. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  17792. /**
  17793. * Called before opaque object are rendered.
  17794. * This stage will be fired only if there's 3D Opaque content to render
  17795. */
  17796. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  17797. /**
  17798. * Called after the opaque objects are rendered and before the transparent ones
  17799. * This stage will be fired only if there's 3D transparent content to render
  17800. */
  17801. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  17802. /**
  17803. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  17804. * This stage will be fired no matter what
  17805. */
  17806. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  17807. return RenderingGroupInfo;
  17808. }());
  17809. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  17810. /**
  17811. * Represents a scene to be rendered by the engine.
  17812. * @see http://doc.babylonjs.com/page.php?p=21911
  17813. */
  17814. var Scene = /** @class */ (function () {
  17815. /**
  17816. * @constructor
  17817. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  17818. */
  17819. function Scene(engine) {
  17820. // Members
  17821. this.autoClear = true;
  17822. this.autoClearDepthAndStencil = true;
  17823. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  17824. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  17825. this.forceWireframe = false;
  17826. this._forcePointsCloud = false;
  17827. this.forceShowBoundingBoxes = false;
  17828. this.animationsEnabled = true;
  17829. this.useConstantAnimationDeltaTime = false;
  17830. this.constantlyUpdateMeshUnderPointer = false;
  17831. this.hoverCursor = "pointer";
  17832. this.defaultCursor = "";
  17833. /**
  17834. * This is used to call preventDefault() on pointer down
  17835. * in order to block unwanted artifacts like system double clicks
  17836. */
  17837. this.preventDefaultOnPointerDown = true;
  17838. // Metadata
  17839. this.metadata = null;
  17840. /**
  17841. * An event triggered when the scene is disposed.
  17842. * @type {BABYLON.Observable}
  17843. */
  17844. this.onDisposeObservable = new BABYLON.Observable();
  17845. /**
  17846. * An event triggered before rendering the scene (right after animations and physics)
  17847. * @type {BABYLON.Observable}
  17848. */
  17849. this.onBeforeRenderObservable = new BABYLON.Observable();
  17850. /**
  17851. * An event triggered after rendering the scene
  17852. * @type {BABYLON.Observable}
  17853. */
  17854. this.onAfterRenderObservable = new BABYLON.Observable();
  17855. /**
  17856. * An event triggered before animating the scene
  17857. * @type {BABYLON.Observable}
  17858. */
  17859. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  17860. /**
  17861. * An event triggered after animations processing
  17862. * @type {BABYLON.Observable}
  17863. */
  17864. this.onAfterAnimationsObservable = new BABYLON.Observable();
  17865. /**
  17866. * An event triggered before draw calls are ready to be sent
  17867. * @type {BABYLON.Observable}
  17868. */
  17869. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  17870. /**
  17871. * An event triggered after draw calls have been sent
  17872. * @type {BABYLON.Observable}
  17873. */
  17874. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  17875. /**
  17876. * An event triggered when physic simulation is about to be run
  17877. * @type {BABYLON.Observable}
  17878. */
  17879. this.onBeforePhysicsObservable = new BABYLON.Observable();
  17880. /**
  17881. * An event triggered when physic simulation has been done
  17882. * @type {BABYLON.Observable}
  17883. */
  17884. this.onAfterPhysicsObservable = new BABYLON.Observable();
  17885. /**
  17886. * An event triggered when the scene is ready
  17887. * @type {BABYLON.Observable}
  17888. */
  17889. this.onReadyObservable = new BABYLON.Observable();
  17890. /**
  17891. * An event triggered before rendering a camera
  17892. * @type {BABYLON.Observable}
  17893. */
  17894. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  17895. /**
  17896. * An event triggered after rendering a camera
  17897. * @type {BABYLON.Observable}
  17898. */
  17899. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  17900. /**
  17901. * An event triggered when active meshes evaluation is about to start
  17902. * @type {BABYLON.Observable}
  17903. */
  17904. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  17905. /**
  17906. * An event triggered when active meshes evaluation is done
  17907. * @type {BABYLON.Observable}
  17908. */
  17909. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  17910. /**
  17911. * An event triggered when particles rendering is about to start
  17912. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  17913. * @type {BABYLON.Observable}
  17914. */
  17915. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  17916. /**
  17917. * An event triggered when particles rendering is done
  17918. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  17919. * @type {BABYLON.Observable}
  17920. */
  17921. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  17922. /**
  17923. * An event triggered when sprites rendering is about to start
  17924. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  17925. * @type {BABYLON.Observable}
  17926. */
  17927. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  17928. /**
  17929. * An event triggered when sprites rendering is done
  17930. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  17931. * @type {BABYLON.Observable}
  17932. */
  17933. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  17934. /**
  17935. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  17936. * @type {BABYLON.Observable}
  17937. */
  17938. this.onDataLoadedObservable = new BABYLON.Observable();
  17939. /**
  17940. * An event triggered when a camera is created
  17941. * @type {BABYLON.Observable}
  17942. */
  17943. this.onNewCameraAddedObservable = new BABYLON.Observable();
  17944. /**
  17945. * An event triggered when a camera is removed
  17946. * @type {BABYLON.Observable}
  17947. */
  17948. this.onCameraRemovedObservable = new BABYLON.Observable();
  17949. /**
  17950. * An event triggered when a light is created
  17951. * @type {BABYLON.Observable}
  17952. */
  17953. this.onNewLightAddedObservable = new BABYLON.Observable();
  17954. /**
  17955. * An event triggered when a light is removed
  17956. * @type {BABYLON.Observable}
  17957. */
  17958. this.onLightRemovedObservable = new BABYLON.Observable();
  17959. /**
  17960. * An event triggered when a geometry is created
  17961. * @type {BABYLON.Observable}
  17962. */
  17963. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  17964. /**
  17965. * An event triggered when a geometry is removed
  17966. * @type {BABYLON.Observable}
  17967. */
  17968. this.onGeometryRemovedObservable = new BABYLON.Observable();
  17969. /**
  17970. * An event triggered when a transform node is created
  17971. * @type {BABYLON.Observable}
  17972. */
  17973. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  17974. /**
  17975. * An event triggered when a transform node is removed
  17976. * @type {BABYLON.Observable}
  17977. */
  17978. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  17979. /**
  17980. * An event triggered when a mesh is created
  17981. * @type {BABYLON.Observable}
  17982. */
  17983. this.onNewMeshAddedObservable = new BABYLON.Observable();
  17984. /**
  17985. * An event triggered when a mesh is removed
  17986. * @type {BABYLON.Observable}
  17987. */
  17988. this.onMeshRemovedObservable = new BABYLON.Observable();
  17989. /**
  17990. * An event triggered when render targets are about to be rendered
  17991. * Can happen multiple times per frame.
  17992. * @type {BABYLON.Observable}
  17993. */
  17994. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  17995. /**
  17996. * An event triggered when render targets were rendered.
  17997. * Can happen multiple times per frame.
  17998. * @type {BABYLON.Observable}
  17999. */
  18000. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  18001. /**
  18002. * An event triggered before calculating deterministic simulation step
  18003. * @type {BABYLON.Observable}
  18004. */
  18005. this.onBeforeStepObservable = new BABYLON.Observable();
  18006. /**
  18007. * An event triggered after calculating deterministic simulation step
  18008. * @type {BABYLON.Observable}
  18009. */
  18010. this.onAfterStepObservable = new BABYLON.Observable();
  18011. /**
  18012. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  18013. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  18014. * 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)
  18015. */
  18016. this.onRenderingGroupObservable = new BABYLON.Observable();
  18017. // Animations
  18018. this.animations = [];
  18019. /**
  18020. * 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).
  18021. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  18022. */
  18023. this.onPrePointerObservable = new BABYLON.Observable();
  18024. /**
  18025. * Observable event triggered each time an input event is received from the rendering canvas
  18026. */
  18027. this.onPointerObservable = new BABYLON.Observable();
  18028. this._meshPickProceed = false;
  18029. this._currentPickResult = null;
  18030. this._previousPickResult = null;
  18031. this._totalPointersPressed = 0;
  18032. this._doubleClickOccured = false;
  18033. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  18034. this.cameraToUseForPointers = null;
  18035. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  18036. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  18037. this._startingPointerTime = 0;
  18038. this._previousStartingPointerTime = 0;
  18039. // Deterministic lockstep
  18040. this._timeAccumulator = 0;
  18041. this._currentStepId = 0;
  18042. this._currentInternalStep = 0;
  18043. // Keyboard
  18044. /**
  18045. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  18046. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  18047. */
  18048. this.onPreKeyboardObservable = new BABYLON.Observable();
  18049. /**
  18050. * Observable event triggered each time an keyboard event is received from the hosting window
  18051. */
  18052. this.onKeyboardObservable = new BABYLON.Observable();
  18053. // Coordinate system
  18054. /**
  18055. * use right-handed coordinate system on this scene.
  18056. * @type {boolean}
  18057. */
  18058. this._useRightHandedSystem = false;
  18059. // Fog
  18060. this._fogEnabled = true;
  18061. this._fogMode = Scene.FOGMODE_NONE;
  18062. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  18063. this.fogDensity = 0.1;
  18064. this.fogStart = 0;
  18065. this.fogEnd = 1000.0;
  18066. // Lights
  18067. /**
  18068. * is shadow enabled on this scene.
  18069. * @type {boolean}
  18070. */
  18071. this._shadowsEnabled = true;
  18072. /**
  18073. * is light enabled on this scene.
  18074. * @type {boolean}
  18075. */
  18076. this._lightsEnabled = true;
  18077. /**
  18078. * All of the lights added to this scene.
  18079. * @see BABYLON.Light
  18080. * @type {BABYLON.Light[]}
  18081. */
  18082. this.lights = new Array();
  18083. // Cameras
  18084. /** All of the cameras added to this scene. */
  18085. this.cameras = new Array();
  18086. /** All of the active cameras added to this scene. */
  18087. this.activeCameras = new Array();
  18088. // Meshes
  18089. /**
  18090. * All of the tranform nodes added to this scene.
  18091. * @see BABYLON.TransformNode
  18092. * @type {BABYLON.TransformNode[]}
  18093. */
  18094. this.transformNodes = new Array();
  18095. /**
  18096. * All of the (abstract) meshes added to this scene.
  18097. * @see BABYLON.AbstractMesh
  18098. * @type {BABYLON.AbstractMesh[]}
  18099. */
  18100. this.meshes = new Array();
  18101. // Geometries
  18102. this._geometries = new Array();
  18103. this.materials = new Array();
  18104. this.multiMaterials = new Array();
  18105. // Textures
  18106. this._texturesEnabled = true;
  18107. this.textures = new Array();
  18108. // Particles
  18109. this.particlesEnabled = true;
  18110. this.particleSystems = new Array();
  18111. // Sprites
  18112. this.spritesEnabled = true;
  18113. this.spriteManagers = new Array();
  18114. // Layers
  18115. this.layers = new Array();
  18116. this.highlightLayers = new Array();
  18117. // Skeletons
  18118. this._skeletonsEnabled = true;
  18119. this.skeletons = new Array();
  18120. // Morph targets
  18121. this.morphTargetManagers = new Array();
  18122. // Lens flares
  18123. this.lensFlaresEnabled = true;
  18124. this.lensFlareSystems = new Array();
  18125. // Collisions
  18126. this.collisionsEnabled = true;
  18127. /** Defines the gravity applied to this scene */
  18128. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  18129. // Postprocesses
  18130. this.postProcesses = new Array();
  18131. this.postProcessesEnabled = true;
  18132. // Customs render targets
  18133. this.renderTargetsEnabled = true;
  18134. this.dumpNextRenderTargets = false;
  18135. this.customRenderTargets = new Array();
  18136. // Imported meshes
  18137. this.importedMeshesFiles = new Array();
  18138. // Probes
  18139. this.probesEnabled = true;
  18140. this.reflectionProbes = new Array();
  18141. this._actionManagers = new Array();
  18142. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  18143. // Procedural textures
  18144. this.proceduralTexturesEnabled = true;
  18145. this._proceduralTextures = new Array();
  18146. this.soundTracks = new Array();
  18147. this._audioEnabled = true;
  18148. this._headphone = false;
  18149. // Performance counters
  18150. this._totalVertices = new BABYLON.PerfCounter();
  18151. this._activeIndices = new BABYLON.PerfCounter();
  18152. this._activeParticles = new BABYLON.PerfCounter();
  18153. this._activeBones = new BABYLON.PerfCounter();
  18154. this._animationTime = 0;
  18155. this.animationTimeScale = 1;
  18156. this._renderId = 0;
  18157. this._executeWhenReadyTimeoutId = -1;
  18158. this._intermediateRendering = false;
  18159. this._viewUpdateFlag = -1;
  18160. this._projectionUpdateFlag = -1;
  18161. this._alternateViewUpdateFlag = -1;
  18162. this._alternateProjectionUpdateFlag = -1;
  18163. this._toBeDisposed = new BABYLON.SmartArray(256);
  18164. this._pendingData = new Array();
  18165. this._isDisposed = false;
  18166. this._activeMeshes = new BABYLON.SmartArray(256);
  18167. this._processedMaterials = new BABYLON.SmartArray(256);
  18168. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  18169. this._activeParticleSystems = new BABYLON.SmartArray(256);
  18170. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  18171. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  18172. this._activeAnimatables = new Array();
  18173. this._transformMatrix = BABYLON.Matrix.Zero();
  18174. this._useAlternateCameraConfiguration = false;
  18175. this._alternateRendering = false;
  18176. this.requireLightSorting = false;
  18177. this._activeMeshesFrozen = false;
  18178. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  18179. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  18180. this._engine.scenes.push(this);
  18181. this._uid = null;
  18182. this._renderingManager = new BABYLON.RenderingManager(this);
  18183. this.postProcessManager = new BABYLON.PostProcessManager(this);
  18184. if (BABYLON.OutlineRenderer) {
  18185. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  18186. }
  18187. if (BABYLON.Tools.IsWindowObjectExist()) {
  18188. this.attachControl();
  18189. }
  18190. //simplification queue
  18191. if (BABYLON.SimplificationQueue) {
  18192. this.simplificationQueue = new BABYLON.SimplificationQueue();
  18193. }
  18194. //collision coordinator initialization. For now legacy per default.
  18195. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  18196. // Uniform Buffer
  18197. this._createUbo();
  18198. // Default Image processing definition.
  18199. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  18200. }
  18201. Object.defineProperty(Scene, "FOGMODE_NONE", {
  18202. /** The fog is deactivated */
  18203. get: function () {
  18204. return Scene._FOGMODE_NONE;
  18205. },
  18206. enumerable: true,
  18207. configurable: true
  18208. });
  18209. Object.defineProperty(Scene, "FOGMODE_EXP", {
  18210. /** The fog density is following an exponential function */
  18211. get: function () {
  18212. return Scene._FOGMODE_EXP;
  18213. },
  18214. enumerable: true,
  18215. configurable: true
  18216. });
  18217. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  18218. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  18219. get: function () {
  18220. return Scene._FOGMODE_EXP2;
  18221. },
  18222. enumerable: true,
  18223. configurable: true
  18224. });
  18225. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  18226. /** The fog density is following a linear function. */
  18227. get: function () {
  18228. return Scene._FOGMODE_LINEAR;
  18229. },
  18230. enumerable: true,
  18231. configurable: true
  18232. });
  18233. Object.defineProperty(Scene.prototype, "environmentTexture", {
  18234. /**
  18235. * Texture used in all pbr material as the reflection texture.
  18236. * As in the majority of the scene they are the same (exception for multi room and so on),
  18237. * this is easier to reference from here than from all the materials.
  18238. */
  18239. get: function () {
  18240. return this._environmentTexture;
  18241. },
  18242. /**
  18243. * Texture used in all pbr material as the reflection texture.
  18244. * As in the majority of the scene they are the same (exception for multi room and so on),
  18245. * this is easier to set here than in all the materials.
  18246. */
  18247. set: function (value) {
  18248. if (this._environmentTexture === value) {
  18249. return;
  18250. }
  18251. this._environmentTexture = value;
  18252. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18253. },
  18254. enumerable: true,
  18255. configurable: true
  18256. });
  18257. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  18258. /**
  18259. * Default image processing configuration used either in the rendering
  18260. * Forward main pass or through the imageProcessingPostProcess if present.
  18261. * As in the majority of the scene they are the same (exception for multi camera),
  18262. * this is easier to reference from here than from all the materials and post process.
  18263. *
  18264. * No setter as we it is a shared configuration, you can set the values instead.
  18265. */
  18266. get: function () {
  18267. return this._imageProcessingConfiguration;
  18268. },
  18269. enumerable: true,
  18270. configurable: true
  18271. });
  18272. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  18273. get: function () {
  18274. return this._forcePointsCloud;
  18275. },
  18276. set: function (value) {
  18277. if (this._forcePointsCloud === value) {
  18278. return;
  18279. }
  18280. this._forcePointsCloud = value;
  18281. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18282. },
  18283. enumerable: true,
  18284. configurable: true
  18285. });
  18286. Object.defineProperty(Scene.prototype, "onDispose", {
  18287. /** A function to be executed when this scene is disposed. */
  18288. set: function (callback) {
  18289. if (this._onDisposeObserver) {
  18290. this.onDisposeObservable.remove(this._onDisposeObserver);
  18291. }
  18292. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18293. },
  18294. enumerable: true,
  18295. configurable: true
  18296. });
  18297. Object.defineProperty(Scene.prototype, "beforeRender", {
  18298. /** A function to be executed before rendering this scene */
  18299. set: function (callback) {
  18300. if (this._onBeforeRenderObserver) {
  18301. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  18302. }
  18303. if (callback) {
  18304. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  18305. }
  18306. },
  18307. enumerable: true,
  18308. configurable: true
  18309. });
  18310. Object.defineProperty(Scene.prototype, "afterRender", {
  18311. /** A function to be executed after rendering this scene */
  18312. set: function (callback) {
  18313. if (this._onAfterRenderObserver) {
  18314. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  18315. }
  18316. if (callback) {
  18317. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  18318. }
  18319. },
  18320. enumerable: true,
  18321. configurable: true
  18322. });
  18323. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  18324. set: function (callback) {
  18325. if (this._onBeforeCameraRenderObserver) {
  18326. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  18327. }
  18328. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  18329. },
  18330. enumerable: true,
  18331. configurable: true
  18332. });
  18333. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  18334. set: function (callback) {
  18335. if (this._onAfterCameraRenderObserver) {
  18336. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  18337. }
  18338. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  18339. },
  18340. enumerable: true,
  18341. configurable: true
  18342. });
  18343. Object.defineProperty(Scene.prototype, "gamepadManager", {
  18344. get: function () {
  18345. if (!this._gamepadManager) {
  18346. this._gamepadManager = new BABYLON.GamepadManager(this);
  18347. }
  18348. return this._gamepadManager;
  18349. },
  18350. enumerable: true,
  18351. configurable: true
  18352. });
  18353. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  18354. get: function () {
  18355. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  18356. },
  18357. enumerable: true,
  18358. configurable: true
  18359. });
  18360. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  18361. get: function () {
  18362. return this._useRightHandedSystem;
  18363. },
  18364. set: function (value) {
  18365. if (this._useRightHandedSystem === value) {
  18366. return;
  18367. }
  18368. this._useRightHandedSystem = value;
  18369. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18370. },
  18371. enumerable: true,
  18372. configurable: true
  18373. });
  18374. Scene.prototype.setStepId = function (newStepId) {
  18375. this._currentStepId = newStepId;
  18376. };
  18377. ;
  18378. Scene.prototype.getStepId = function () {
  18379. return this._currentStepId;
  18380. };
  18381. ;
  18382. Scene.prototype.getInternalStep = function () {
  18383. return this._currentInternalStep;
  18384. };
  18385. ;
  18386. Object.defineProperty(Scene.prototype, "fogEnabled", {
  18387. get: function () {
  18388. return this._fogEnabled;
  18389. },
  18390. /**
  18391. * is fog enabled on this scene.
  18392. */
  18393. set: function (value) {
  18394. if (this._fogEnabled === value) {
  18395. return;
  18396. }
  18397. this._fogEnabled = value;
  18398. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18399. },
  18400. enumerable: true,
  18401. configurable: true
  18402. });
  18403. Object.defineProperty(Scene.prototype, "fogMode", {
  18404. get: function () {
  18405. return this._fogMode;
  18406. },
  18407. set: function (value) {
  18408. if (this._fogMode === value) {
  18409. return;
  18410. }
  18411. this._fogMode = value;
  18412. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18413. },
  18414. enumerable: true,
  18415. configurable: true
  18416. });
  18417. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  18418. get: function () {
  18419. return this._shadowsEnabled;
  18420. },
  18421. set: function (value) {
  18422. if (this._shadowsEnabled === value) {
  18423. return;
  18424. }
  18425. this._shadowsEnabled = value;
  18426. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  18427. },
  18428. enumerable: true,
  18429. configurable: true
  18430. });
  18431. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  18432. get: function () {
  18433. return this._lightsEnabled;
  18434. },
  18435. set: function (value) {
  18436. if (this._lightsEnabled === value) {
  18437. return;
  18438. }
  18439. this._lightsEnabled = value;
  18440. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  18441. },
  18442. enumerable: true,
  18443. configurable: true
  18444. });
  18445. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  18446. /** The default material used on meshes when no material is affected */
  18447. get: function () {
  18448. if (!this._defaultMaterial) {
  18449. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  18450. }
  18451. return this._defaultMaterial;
  18452. },
  18453. /** The default material used on meshes when no material is affected */
  18454. set: function (value) {
  18455. this._defaultMaterial = value;
  18456. },
  18457. enumerable: true,
  18458. configurable: true
  18459. });
  18460. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  18461. get: function () {
  18462. return this._texturesEnabled;
  18463. },
  18464. set: function (value) {
  18465. if (this._texturesEnabled === value) {
  18466. return;
  18467. }
  18468. this._texturesEnabled = value;
  18469. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18470. },
  18471. enumerable: true,
  18472. configurable: true
  18473. });
  18474. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  18475. get: function () {
  18476. return this._skeletonsEnabled;
  18477. },
  18478. set: function (value) {
  18479. if (this._skeletonsEnabled === value) {
  18480. return;
  18481. }
  18482. this._skeletonsEnabled = value;
  18483. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  18484. },
  18485. enumerable: true,
  18486. configurable: true
  18487. });
  18488. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  18489. get: function () {
  18490. if (!this._postProcessRenderPipelineManager) {
  18491. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  18492. }
  18493. return this._postProcessRenderPipelineManager;
  18494. },
  18495. enumerable: true,
  18496. configurable: true
  18497. });
  18498. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  18499. get: function () {
  18500. if (!this._mainSoundTrack) {
  18501. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  18502. }
  18503. return this._mainSoundTrack;
  18504. },
  18505. enumerable: true,
  18506. configurable: true
  18507. });
  18508. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  18509. get: function () {
  18510. return this._alternateRendering;
  18511. },
  18512. enumerable: true,
  18513. configurable: true
  18514. });
  18515. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  18516. get: function () {
  18517. return this._frustumPlanes;
  18518. },
  18519. enumerable: true,
  18520. configurable: true
  18521. });
  18522. Object.defineProperty(Scene.prototype, "debugLayer", {
  18523. // Properties
  18524. get: function () {
  18525. if (!this._debugLayer) {
  18526. this._debugLayer = new BABYLON.DebugLayer(this);
  18527. }
  18528. return this._debugLayer;
  18529. },
  18530. enumerable: true,
  18531. configurable: true
  18532. });
  18533. Object.defineProperty(Scene.prototype, "workerCollisions", {
  18534. get: function () {
  18535. return this._workerCollisions;
  18536. },
  18537. set: function (enabled) {
  18538. if (!BABYLON.CollisionCoordinatorLegacy) {
  18539. return;
  18540. }
  18541. enabled = (enabled && !!Worker);
  18542. this._workerCollisions = enabled;
  18543. if (this.collisionCoordinator) {
  18544. this.collisionCoordinator.destroy();
  18545. }
  18546. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  18547. this.collisionCoordinator.init(this);
  18548. },
  18549. enumerable: true,
  18550. configurable: true
  18551. });
  18552. Object.defineProperty(Scene.prototype, "selectionOctree", {
  18553. get: function () {
  18554. return this._selectionOctree;
  18555. },
  18556. enumerable: true,
  18557. configurable: true
  18558. });
  18559. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  18560. /**
  18561. * The mesh that is currently under the pointer.
  18562. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  18563. */
  18564. get: function () {
  18565. return this._pointerOverMesh;
  18566. },
  18567. enumerable: true,
  18568. configurable: true
  18569. });
  18570. Object.defineProperty(Scene.prototype, "pointerX", {
  18571. /**
  18572. * Current on-screen X position of the pointer
  18573. * @return {number} X position of the pointer
  18574. */
  18575. get: function () {
  18576. return this._pointerX;
  18577. },
  18578. enumerable: true,
  18579. configurable: true
  18580. });
  18581. Object.defineProperty(Scene.prototype, "pointerY", {
  18582. /**
  18583. * Current on-screen Y position of the pointer
  18584. * @return {number} Y position of the pointer
  18585. */
  18586. get: function () {
  18587. return this._pointerY;
  18588. },
  18589. enumerable: true,
  18590. configurable: true
  18591. });
  18592. Scene.prototype.getCachedMaterial = function () {
  18593. return this._cachedMaterial;
  18594. };
  18595. Scene.prototype.getCachedEffect = function () {
  18596. return this._cachedEffect;
  18597. };
  18598. Scene.prototype.getCachedVisibility = function () {
  18599. return this._cachedVisibility;
  18600. };
  18601. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  18602. if (visibility === void 0) { visibility = 1; }
  18603. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  18604. };
  18605. Scene.prototype.getBoundingBoxRenderer = function () {
  18606. if (!this._boundingBoxRenderer) {
  18607. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  18608. }
  18609. return this._boundingBoxRenderer;
  18610. };
  18611. Scene.prototype.getOutlineRenderer = function () {
  18612. return this._outlineRenderer;
  18613. };
  18614. Scene.prototype.getEngine = function () {
  18615. return this._engine;
  18616. };
  18617. Scene.prototype.getTotalVertices = function () {
  18618. return this._totalVertices.current;
  18619. };
  18620. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  18621. get: function () {
  18622. return this._totalVertices;
  18623. },
  18624. enumerable: true,
  18625. configurable: true
  18626. });
  18627. Scene.prototype.getActiveIndices = function () {
  18628. return this._activeIndices.current;
  18629. };
  18630. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  18631. get: function () {
  18632. return this._activeIndices;
  18633. },
  18634. enumerable: true,
  18635. configurable: true
  18636. });
  18637. Scene.prototype.getActiveParticles = function () {
  18638. return this._activeParticles.current;
  18639. };
  18640. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  18641. get: function () {
  18642. return this._activeParticles;
  18643. },
  18644. enumerable: true,
  18645. configurable: true
  18646. });
  18647. Scene.prototype.getActiveBones = function () {
  18648. return this._activeBones.current;
  18649. };
  18650. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  18651. get: function () {
  18652. return this._activeBones;
  18653. },
  18654. enumerable: true,
  18655. configurable: true
  18656. });
  18657. // Stats
  18658. Scene.prototype.getInterFramePerfCounter = function () {
  18659. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18660. return 0;
  18661. };
  18662. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  18663. get: function () {
  18664. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18665. return null;
  18666. },
  18667. enumerable: true,
  18668. configurable: true
  18669. });
  18670. Scene.prototype.getLastFrameDuration = function () {
  18671. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  18672. return 0;
  18673. };
  18674. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  18675. get: function () {
  18676. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18677. return null;
  18678. },
  18679. enumerable: true,
  18680. configurable: true
  18681. });
  18682. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  18683. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  18684. return 0;
  18685. };
  18686. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  18687. get: function () {
  18688. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18689. return null;
  18690. },
  18691. enumerable: true,
  18692. configurable: true
  18693. });
  18694. Scene.prototype.getActiveMeshes = function () {
  18695. return this._activeMeshes;
  18696. };
  18697. Scene.prototype.getRenderTargetsDuration = function () {
  18698. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  18699. return 0;
  18700. };
  18701. Scene.prototype.getRenderDuration = function () {
  18702. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  18703. return 0;
  18704. };
  18705. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  18706. get: function () {
  18707. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18708. return null;
  18709. },
  18710. enumerable: true,
  18711. configurable: true
  18712. });
  18713. Scene.prototype.getParticlesDuration = function () {
  18714. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  18715. return 0;
  18716. };
  18717. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  18718. get: function () {
  18719. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18720. return null;
  18721. },
  18722. enumerable: true,
  18723. configurable: true
  18724. });
  18725. Scene.prototype.getSpritesDuration = function () {
  18726. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  18727. return 0;
  18728. };
  18729. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  18730. get: function () {
  18731. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  18732. return null;
  18733. },
  18734. enumerable: true,
  18735. configurable: true
  18736. });
  18737. Scene.prototype.getAnimationRatio = function () {
  18738. return this._animationRatio;
  18739. };
  18740. Scene.prototype.getRenderId = function () {
  18741. return this._renderId;
  18742. };
  18743. Scene.prototype.incrementRenderId = function () {
  18744. this._renderId++;
  18745. };
  18746. Scene.prototype._updatePointerPosition = function (evt) {
  18747. var canvasRect = this._engine.getRenderingCanvasClientRect();
  18748. if (!canvasRect) {
  18749. return;
  18750. }
  18751. this._pointerX = evt.clientX - canvasRect.left;
  18752. this._pointerY = evt.clientY - canvasRect.top;
  18753. this._unTranslatedPointerX = this._pointerX;
  18754. this._unTranslatedPointerY = this._pointerY;
  18755. };
  18756. Scene.prototype._createUbo = function () {
  18757. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  18758. this._sceneUbo.addUniform("viewProjection", 16);
  18759. this._sceneUbo.addUniform("view", 16);
  18760. };
  18761. Scene.prototype._createAlternateUbo = function () {
  18762. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  18763. this._alternateSceneUbo.addUniform("viewProjection", 16);
  18764. this._alternateSceneUbo.addUniform("view", 16);
  18765. };
  18766. // Pointers handling
  18767. /**
  18768. * Use this method to simulate a pointer move on a mesh
  18769. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18770. */
  18771. Scene.prototype.simulatePointerMove = function (pickResult) {
  18772. var evt = new PointerEvent("pointermove");
  18773. return this._processPointerMove(pickResult, evt);
  18774. };
  18775. Scene.prototype._processPointerMove = function (pickResult, evt) {
  18776. var canvas = this._engine.getRenderingCanvas();
  18777. if (!canvas) {
  18778. return this;
  18779. }
  18780. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  18781. this.setPointerOverSprite(null);
  18782. this.setPointerOverMesh(pickResult.pickedMesh);
  18783. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  18784. if (this._pointerOverMesh.actionManager.hoverCursor) {
  18785. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  18786. }
  18787. else {
  18788. canvas.style.cursor = this.hoverCursor;
  18789. }
  18790. }
  18791. else {
  18792. canvas.style.cursor = this.defaultCursor;
  18793. }
  18794. }
  18795. else {
  18796. this.setPointerOverMesh(null);
  18797. // Sprites
  18798. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  18799. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  18800. this.setPointerOverSprite(pickResult.pickedSprite);
  18801. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  18802. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  18803. }
  18804. else {
  18805. canvas.style.cursor = this.hoverCursor;
  18806. }
  18807. }
  18808. else {
  18809. this.setPointerOverSprite(null);
  18810. // Restore pointer
  18811. canvas.style.cursor = this.defaultCursor;
  18812. }
  18813. }
  18814. if (pickResult) {
  18815. if (this.onPointerMove) {
  18816. this.onPointerMove(evt, pickResult);
  18817. }
  18818. if (this.onPointerObservable.hasObservers()) {
  18819. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  18820. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18821. this.onPointerObservable.notifyObservers(pi, type);
  18822. }
  18823. }
  18824. return this;
  18825. };
  18826. /**
  18827. * Use this method to simulate a pointer down on a mesh
  18828. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18829. */
  18830. Scene.prototype.simulatePointerDown = function (pickResult) {
  18831. var evt = new PointerEvent("pointerdown");
  18832. return this._processPointerDown(pickResult, evt);
  18833. };
  18834. Scene.prototype._processPointerDown = function (pickResult, evt) {
  18835. var _this = this;
  18836. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  18837. this._pickedDownMesh = pickResult.pickedMesh;
  18838. var actionManager = pickResult.pickedMesh.actionManager;
  18839. if (actionManager) {
  18840. if (actionManager.hasPickTriggers) {
  18841. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18842. switch (evt.button) {
  18843. case 0:
  18844. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18845. break;
  18846. case 1:
  18847. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18848. break;
  18849. case 2:
  18850. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18851. break;
  18852. }
  18853. }
  18854. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  18855. window.setTimeout(function () {
  18856. 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);
  18857. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  18858. if (_this._totalPointersPressed !== 0 &&
  18859. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  18860. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  18861. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  18862. _this._startingPointerTime = 0;
  18863. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18864. }
  18865. }
  18866. }, Scene.LongPressDelay);
  18867. }
  18868. }
  18869. }
  18870. if (pickResult) {
  18871. if (this.onPointerDown) {
  18872. this.onPointerDown(evt, pickResult);
  18873. }
  18874. if (this.onPointerObservable.hasObservers()) {
  18875. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  18876. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18877. this.onPointerObservable.notifyObservers(pi, type);
  18878. }
  18879. }
  18880. return this;
  18881. };
  18882. /**
  18883. * Use this method to simulate a pointer up on a mesh
  18884. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18885. */
  18886. Scene.prototype.simulatePointerUp = function (pickResult) {
  18887. var evt = new PointerEvent("pointerup");
  18888. var clickInfo = new ClickInfo();
  18889. clickInfo.singleClick = true;
  18890. clickInfo.ignore = true;
  18891. return this._processPointerUp(pickResult, evt, clickInfo);
  18892. };
  18893. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  18894. if (pickResult && pickResult && pickResult.pickedMesh) {
  18895. this._pickedUpMesh = pickResult.pickedMesh;
  18896. if (this._pickedDownMesh === this._pickedUpMesh) {
  18897. if (this.onPointerPick) {
  18898. this.onPointerPick(evt, pickResult);
  18899. }
  18900. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  18901. var type = BABYLON.PointerEventTypes.POINTERPICK;
  18902. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18903. this.onPointerObservable.notifyObservers(pi, type);
  18904. }
  18905. }
  18906. if (pickResult.pickedMesh.actionManager) {
  18907. if (clickInfo.ignore) {
  18908. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18909. }
  18910. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  18911. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18912. }
  18913. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18914. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18915. }
  18916. }
  18917. }
  18918. if (this._pickedDownMesh &&
  18919. this._pickedDownMesh.actionManager &&
  18920. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  18921. this._pickedDownMesh !== this._pickedUpMesh) {
  18922. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  18923. }
  18924. if (this.onPointerUp) {
  18925. this.onPointerUp(evt, pickResult);
  18926. }
  18927. if (this.onPointerObservable.hasObservers()) {
  18928. if (!clickInfo.ignore) {
  18929. if (!clickInfo.hasSwiped) {
  18930. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  18931. var type = BABYLON.PointerEventTypes.POINTERTAP;
  18932. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18933. this.onPointerObservable.notifyObservers(pi, type);
  18934. }
  18935. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  18936. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  18937. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18938. this.onPointerObservable.notifyObservers(pi, type);
  18939. }
  18940. }
  18941. }
  18942. else {
  18943. var type = BABYLON.PointerEventTypes.POINTERUP;
  18944. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18945. this.onPointerObservable.notifyObservers(pi, type);
  18946. }
  18947. }
  18948. return this;
  18949. };
  18950. /**
  18951. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  18952. * @param attachUp defines if you want to attach events to pointerup
  18953. * @param attachDown defines if you want to attach events to pointerdown
  18954. * @param attachMove defines if you want to attach events to pointermove
  18955. */
  18956. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  18957. var _this = this;
  18958. if (attachUp === void 0) { attachUp = true; }
  18959. if (attachDown === void 0) { attachDown = true; }
  18960. if (attachMove === void 0) { attachMove = true; }
  18961. this._initActionManager = function (act, clickInfo) {
  18962. if (!_this._meshPickProceed) {
  18963. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  18964. _this._currentPickResult = pickResult;
  18965. if (pickResult) {
  18966. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  18967. }
  18968. _this._meshPickProceed = true;
  18969. }
  18970. return act;
  18971. };
  18972. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  18973. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  18974. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  18975. btn !== _this._previousButtonPressed) {
  18976. _this._doubleClickOccured = false;
  18977. clickInfo.singleClick = true;
  18978. clickInfo.ignore = false;
  18979. cb(clickInfo, _this._currentPickResult);
  18980. }
  18981. };
  18982. this._initClickEvent = function (obs1, obs2, evt, cb) {
  18983. var clickInfo = new ClickInfo();
  18984. _this._currentPickResult = null;
  18985. var act = null;
  18986. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  18987. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  18988. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18989. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  18990. act = _this._initActionManager(act, clickInfo);
  18991. if (act)
  18992. checkPicking = act.hasPickTriggers;
  18993. }
  18994. if (checkPicking) {
  18995. var btn = evt.button;
  18996. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  18997. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  18998. if (!clickInfo.hasSwiped) {
  18999. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  19000. if (!checkSingleClickImmediately) {
  19001. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  19002. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  19003. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  19004. act = _this._initActionManager(act, clickInfo);
  19005. if (act)
  19006. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  19007. }
  19008. }
  19009. if (checkSingleClickImmediately) {
  19010. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  19011. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  19012. btn !== _this._previousButtonPressed) {
  19013. clickInfo.singleClick = true;
  19014. cb(clickInfo, _this._currentPickResult);
  19015. }
  19016. }
  19017. else {
  19018. // wait that no double click has been raised during the double click delay
  19019. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  19020. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  19021. }
  19022. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  19023. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  19024. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  19025. act = _this._initActionManager(act, clickInfo);
  19026. if (act)
  19027. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  19028. }
  19029. if (checkDoubleClick) {
  19030. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  19031. if (btn === _this._previousButtonPressed &&
  19032. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  19033. !_this._doubleClickOccured) {
  19034. // pointer has not moved for 2 clicks, it's a double click
  19035. if (!clickInfo.hasSwiped &&
  19036. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  19037. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  19038. _this._previousStartingPointerTime = 0;
  19039. _this._doubleClickOccured = true;
  19040. clickInfo.doubleClick = true;
  19041. clickInfo.ignore = false;
  19042. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  19043. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  19044. }
  19045. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  19046. cb(clickInfo, _this._currentPickResult);
  19047. }
  19048. else {
  19049. _this._doubleClickOccured = false;
  19050. _this._previousStartingPointerTime = _this._startingPointerTime;
  19051. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  19052. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  19053. _this._previousButtonPressed = btn;
  19054. if (Scene.ExclusiveDoubleClickMode) {
  19055. if (_this._previousDelayedSimpleClickTimeout) {
  19056. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  19057. }
  19058. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  19059. cb(clickInfo, _this._previousPickResult);
  19060. }
  19061. else {
  19062. cb(clickInfo, _this._currentPickResult);
  19063. }
  19064. }
  19065. }
  19066. else {
  19067. _this._doubleClickOccured = false;
  19068. _this._previousStartingPointerTime = _this._startingPointerTime;
  19069. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  19070. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  19071. _this._previousButtonPressed = btn;
  19072. }
  19073. }
  19074. }
  19075. }
  19076. clickInfo.ignore = true;
  19077. cb(clickInfo, _this._currentPickResult);
  19078. };
  19079. this._spritePredicate = function (sprite) {
  19080. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  19081. };
  19082. this._onPointerMove = function (evt) {
  19083. _this._updatePointerPosition(evt);
  19084. // PreObservable support
  19085. if (_this.onPrePointerObservable.hasObservers()) {
  19086. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  19087. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19088. _this.onPrePointerObservable.notifyObservers(pi, type);
  19089. if (pi.skipOnPointerObservable) {
  19090. return;
  19091. }
  19092. }
  19093. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19094. return;
  19095. }
  19096. if (!_this.pointerMovePredicate) {
  19097. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  19098. }
  19099. // Meshes
  19100. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  19101. _this._processPointerMove(pickResult, evt);
  19102. };
  19103. this._onPointerDown = function (evt) {
  19104. _this._totalPointersPressed++;
  19105. _this._pickedDownMesh = null;
  19106. _this._meshPickProceed = false;
  19107. _this._updatePointerPosition(evt);
  19108. if (_this.preventDefaultOnPointerDown && canvas) {
  19109. evt.preventDefault();
  19110. canvas.focus();
  19111. }
  19112. // PreObservable support
  19113. if (_this.onPrePointerObservable.hasObservers()) {
  19114. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  19115. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19116. _this.onPrePointerObservable.notifyObservers(pi, type);
  19117. if (pi.skipOnPointerObservable) {
  19118. return;
  19119. }
  19120. }
  19121. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19122. return;
  19123. }
  19124. _this._startingPointerPosition.x = _this._pointerX;
  19125. _this._startingPointerPosition.y = _this._pointerY;
  19126. _this._startingPointerTime = new Date().getTime();
  19127. if (!_this.pointerDownPredicate) {
  19128. _this.pointerDownPredicate = function (mesh) {
  19129. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  19130. };
  19131. }
  19132. // Meshes
  19133. _this._pickedDownMesh = null;
  19134. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  19135. _this._processPointerDown(pickResult, evt);
  19136. // Sprites
  19137. _this._pickedDownSprite = null;
  19138. if (_this.spriteManagers.length > 0) {
  19139. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  19140. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  19141. if (pickResult.pickedSprite.actionManager) {
  19142. _this._pickedDownSprite = pickResult.pickedSprite;
  19143. switch (evt.button) {
  19144. case 0:
  19145. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19146. break;
  19147. case 1:
  19148. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19149. break;
  19150. case 2:
  19151. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19152. break;
  19153. }
  19154. if (pickResult.pickedSprite.actionManager) {
  19155. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19156. }
  19157. }
  19158. }
  19159. }
  19160. };
  19161. this._onPointerUp = function (evt) {
  19162. if (_this._totalPointersPressed === 0) {
  19163. return; // So we need to test it the pointer down was pressed before.
  19164. }
  19165. _this._totalPointersPressed--;
  19166. _this._pickedUpMesh = null;
  19167. _this._meshPickProceed = false;
  19168. _this._updatePointerPosition(evt);
  19169. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  19170. // PreObservable support
  19171. if (_this.onPrePointerObservable.hasObservers()) {
  19172. if (!clickInfo.ignore) {
  19173. if (!clickInfo.hasSwiped) {
  19174. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  19175. var type = BABYLON.PointerEventTypes.POINTERTAP;
  19176. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19177. _this.onPrePointerObservable.notifyObservers(pi, type);
  19178. if (pi.skipOnPointerObservable) {
  19179. return;
  19180. }
  19181. }
  19182. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  19183. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  19184. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19185. _this.onPrePointerObservable.notifyObservers(pi, type);
  19186. if (pi.skipOnPointerObservable) {
  19187. return;
  19188. }
  19189. }
  19190. }
  19191. }
  19192. else {
  19193. var type = BABYLON.PointerEventTypes.POINTERUP;
  19194. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19195. _this.onPrePointerObservable.notifyObservers(pi, type);
  19196. if (pi.skipOnPointerObservable) {
  19197. return;
  19198. }
  19199. }
  19200. }
  19201. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19202. return;
  19203. }
  19204. if (!_this.pointerUpPredicate) {
  19205. _this.pointerUpPredicate = function (mesh) {
  19206. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  19207. };
  19208. }
  19209. // Meshes
  19210. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  19211. _this._initActionManager(null, clickInfo);
  19212. }
  19213. if (!pickResult) {
  19214. pickResult = _this._currentPickResult;
  19215. }
  19216. _this._processPointerUp(pickResult, evt, clickInfo);
  19217. // Sprites
  19218. if (_this.spriteManagers.length > 0) {
  19219. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  19220. if (spritePickResult) {
  19221. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  19222. if (spritePickResult.pickedSprite.actionManager) {
  19223. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  19224. if (spritePickResult.pickedSprite.actionManager) {
  19225. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  19226. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  19227. }
  19228. }
  19229. }
  19230. }
  19231. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  19232. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  19233. }
  19234. }
  19235. }
  19236. _this._previousPickResult = _this._currentPickResult;
  19237. });
  19238. };
  19239. this._onKeyDown = function (evt) {
  19240. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  19241. if (_this.onPreKeyboardObservable.hasObservers()) {
  19242. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  19243. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  19244. if (pi.skipOnPointerObservable) {
  19245. return;
  19246. }
  19247. }
  19248. if (_this.onKeyboardObservable.hasObservers()) {
  19249. var pi = new BABYLON.KeyboardInfo(type, evt);
  19250. _this.onKeyboardObservable.notifyObservers(pi, type);
  19251. }
  19252. if (_this.actionManager) {
  19253. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  19254. }
  19255. };
  19256. this._onKeyUp = function (evt) {
  19257. var type = BABYLON.KeyboardEventTypes.KEYUP;
  19258. if (_this.onPreKeyboardObservable.hasObservers()) {
  19259. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  19260. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  19261. if (pi.skipOnPointerObservable) {
  19262. return;
  19263. }
  19264. }
  19265. if (_this.onKeyboardObservable.hasObservers()) {
  19266. var pi = new BABYLON.KeyboardInfo(type, evt);
  19267. _this.onKeyboardObservable.notifyObservers(pi, type);
  19268. }
  19269. if (_this.actionManager) {
  19270. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  19271. }
  19272. };
  19273. var engine = this.getEngine();
  19274. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  19275. if (!canvas) {
  19276. return;
  19277. }
  19278. canvas.addEventListener("keydown", _this._onKeyDown, false);
  19279. canvas.addEventListener("keyup", _this._onKeyUp, false);
  19280. });
  19281. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  19282. if (!canvas) {
  19283. return;
  19284. }
  19285. canvas.removeEventListener("keydown", _this._onKeyDown);
  19286. canvas.removeEventListener("keyup", _this._onKeyUp);
  19287. });
  19288. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  19289. var canvas = this._engine.getRenderingCanvas();
  19290. if (!canvas) {
  19291. return;
  19292. }
  19293. if (attachMove) {
  19294. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  19295. // Wheel
  19296. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  19297. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  19298. }
  19299. if (attachDown) {
  19300. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  19301. }
  19302. if (attachUp) {
  19303. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  19304. }
  19305. canvas.tabIndex = 1;
  19306. };
  19307. Scene.prototype.detachControl = function () {
  19308. var engine = this.getEngine();
  19309. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  19310. var canvas = engine.getRenderingCanvas();
  19311. if (!canvas) {
  19312. return;
  19313. }
  19314. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  19315. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  19316. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  19317. if (this._onCanvasBlurObserver) {
  19318. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  19319. }
  19320. if (this._onCanvasFocusObserver) {
  19321. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  19322. }
  19323. // Wheel
  19324. canvas.removeEventListener('mousewheel', this._onPointerMove);
  19325. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  19326. // Keyboard
  19327. canvas.removeEventListener("keydown", this._onKeyDown);
  19328. canvas.removeEventListener("keyup", this._onKeyUp);
  19329. // Observables
  19330. this.onKeyboardObservable.clear();
  19331. this.onPreKeyboardObservable.clear();
  19332. this.onPointerObservable.clear();
  19333. this.onPrePointerObservable.clear();
  19334. };
  19335. // Ready
  19336. Scene.prototype.isReady = function () {
  19337. if (this._isDisposed) {
  19338. return false;
  19339. }
  19340. if (this._pendingData.length > 0) {
  19341. return false;
  19342. }
  19343. var index;
  19344. // Geometries
  19345. for (index = 0; index < this._geometries.length; index++) {
  19346. var geometry = this._geometries[index];
  19347. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19348. return false;
  19349. }
  19350. }
  19351. // Meshes
  19352. for (index = 0; index < this.meshes.length; index++) {
  19353. var mesh = this.meshes[index];
  19354. if (!mesh.isEnabled()) {
  19355. continue;
  19356. }
  19357. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  19358. continue;
  19359. }
  19360. if (!mesh.isReady()) {
  19361. return false;
  19362. }
  19363. var mat = mesh.material;
  19364. if (mat) {
  19365. if (!mat.isReady(mesh)) {
  19366. return false;
  19367. }
  19368. }
  19369. }
  19370. return true;
  19371. };
  19372. Scene.prototype.resetCachedMaterial = function () {
  19373. this._cachedMaterial = null;
  19374. this._cachedEffect = null;
  19375. this._cachedVisibility = null;
  19376. };
  19377. Scene.prototype.registerBeforeRender = function (func) {
  19378. this.onBeforeRenderObservable.add(func);
  19379. };
  19380. Scene.prototype.unregisterBeforeRender = function (func) {
  19381. this.onBeforeRenderObservable.removeCallback(func);
  19382. };
  19383. Scene.prototype.registerAfterRender = function (func) {
  19384. this.onAfterRenderObservable.add(func);
  19385. };
  19386. Scene.prototype.unregisterAfterRender = function (func) {
  19387. this.onAfterRenderObservable.removeCallback(func);
  19388. };
  19389. Scene.prototype._addPendingData = function (data) {
  19390. this._pendingData.push(data);
  19391. };
  19392. Scene.prototype._removePendingData = function (data) {
  19393. var wasLoading = this.isLoading;
  19394. var index = this._pendingData.indexOf(data);
  19395. if (index !== -1) {
  19396. this._pendingData.splice(index, 1);
  19397. }
  19398. if (wasLoading && !this.isLoading) {
  19399. this.onDataLoadedObservable.notifyObservers(this);
  19400. }
  19401. };
  19402. Scene.prototype.getWaitingItemsCount = function () {
  19403. return this._pendingData.length;
  19404. };
  19405. Object.defineProperty(Scene.prototype, "isLoading", {
  19406. get: function () {
  19407. return this._pendingData.length > 0;
  19408. },
  19409. enumerable: true,
  19410. configurable: true
  19411. });
  19412. /**
  19413. * Registers a function to be executed when the scene is ready.
  19414. * @param {Function} func - the function to be executed.
  19415. */
  19416. Scene.prototype.executeWhenReady = function (func) {
  19417. var _this = this;
  19418. this.onReadyObservable.add(func);
  19419. if (this._executeWhenReadyTimeoutId !== -1) {
  19420. return;
  19421. }
  19422. this._executeWhenReadyTimeoutId = setTimeout(function () {
  19423. _this._checkIsReady();
  19424. }, 150);
  19425. };
  19426. Scene.prototype._checkIsReady = function () {
  19427. var _this = this;
  19428. if (this.isReady()) {
  19429. this.onReadyObservable.notifyObservers(this);
  19430. this.onReadyObservable.clear();
  19431. this._executeWhenReadyTimeoutId = -1;
  19432. return;
  19433. }
  19434. this._executeWhenReadyTimeoutId = setTimeout(function () {
  19435. _this._checkIsReady();
  19436. }, 150);
  19437. };
  19438. // Animations
  19439. /**
  19440. * Will start the animation sequence of a given target
  19441. * @param target - the target
  19442. * @param {number} from - from which frame should animation start
  19443. * @param {number} to - till which frame should animation run.
  19444. * @param {boolean} [loop] - should the animation loop
  19445. * @param {number} [speedRatio] - the speed in which to run the animation
  19446. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  19447. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  19448. * Returns {BABYLON.Animatable} the animatable object created for this animation
  19449. * See BABYLON.Animatable
  19450. */
  19451. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  19452. if (speedRatio === void 0) { speedRatio = 1.0; }
  19453. if (from > to && speedRatio > 0) {
  19454. speedRatio *= -1;
  19455. }
  19456. this.stopAnimation(target);
  19457. if (!animatable) {
  19458. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  19459. }
  19460. // Local animations
  19461. if (target.animations) {
  19462. animatable.appendAnimations(target, target.animations);
  19463. }
  19464. // Children animations
  19465. if (target.getAnimatables) {
  19466. var animatables = target.getAnimatables();
  19467. for (var index = 0; index < animatables.length; index++) {
  19468. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  19469. }
  19470. }
  19471. animatable.reset();
  19472. return animatable;
  19473. };
  19474. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  19475. if (speedRatio === undefined) {
  19476. speedRatio = 1.0;
  19477. }
  19478. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  19479. return animatable;
  19480. };
  19481. Scene.prototype.getAnimatableByTarget = function (target) {
  19482. for (var index = 0; index < this._activeAnimatables.length; index++) {
  19483. if (this._activeAnimatables[index].target === target) {
  19484. return this._activeAnimatables[index];
  19485. }
  19486. }
  19487. return null;
  19488. };
  19489. Object.defineProperty(Scene.prototype, "Animatables", {
  19490. get: function () {
  19491. return this._activeAnimatables;
  19492. },
  19493. enumerable: true,
  19494. configurable: true
  19495. });
  19496. /**
  19497. * Will stop the animation of the given target
  19498. * @param target - the target
  19499. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  19500. * @see beginAnimation
  19501. */
  19502. Scene.prototype.stopAnimation = function (target, animationName) {
  19503. var animatable = this.getAnimatableByTarget(target);
  19504. if (animatable) {
  19505. animatable.stop(animationName);
  19506. }
  19507. };
  19508. /**
  19509. * Stops and removes all animations that have been applied to the scene
  19510. */
  19511. Scene.prototype.stopAllAnimations = function () {
  19512. if (this._activeAnimatables) {
  19513. for (var i = 0; i < this._activeAnimatables.length; i++) {
  19514. this._activeAnimatables[i].stop();
  19515. }
  19516. this._activeAnimatables = [];
  19517. }
  19518. };
  19519. Scene.prototype._animate = function () {
  19520. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  19521. return;
  19522. }
  19523. // Getting time
  19524. var now = BABYLON.Tools.Now;
  19525. if (!this._animationTimeLast) {
  19526. if (this._pendingData.length > 0) {
  19527. return;
  19528. }
  19529. this._animationTimeLast = now;
  19530. }
  19531. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  19532. this._animationTime += deltaTime;
  19533. this._animationTimeLast = now;
  19534. for (var index = 0; index < this._activeAnimatables.length; index++) {
  19535. this._activeAnimatables[index]._animate(this._animationTime);
  19536. }
  19537. };
  19538. // Matrix
  19539. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  19540. this._useAlternateCameraConfiguration = active;
  19541. };
  19542. Scene.prototype.getViewMatrix = function () {
  19543. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  19544. };
  19545. Scene.prototype.getProjectionMatrix = function () {
  19546. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  19547. };
  19548. Scene.prototype.getTransformMatrix = function () {
  19549. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  19550. };
  19551. Scene.prototype.setTransformMatrix = function (view, projection) {
  19552. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  19553. return;
  19554. }
  19555. this._viewUpdateFlag = view.updateFlag;
  19556. this._projectionUpdateFlag = projection.updateFlag;
  19557. this._viewMatrix = view;
  19558. this._projectionMatrix = projection;
  19559. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  19560. // Update frustum
  19561. if (!this._frustumPlanes) {
  19562. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  19563. }
  19564. else {
  19565. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  19566. }
  19567. if (this.activeCamera && this.activeCamera._alternateCamera) {
  19568. var otherCamera = this.activeCamera._alternateCamera;
  19569. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  19570. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  19571. }
  19572. if (this._sceneUbo.useUbo) {
  19573. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  19574. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  19575. this._sceneUbo.update();
  19576. }
  19577. };
  19578. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  19579. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  19580. return;
  19581. }
  19582. this._alternateViewUpdateFlag = view.updateFlag;
  19583. this._alternateProjectionUpdateFlag = projection.updateFlag;
  19584. this._alternateViewMatrix = view;
  19585. this._alternateProjectionMatrix = projection;
  19586. if (!this._alternateTransformMatrix) {
  19587. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  19588. }
  19589. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  19590. if (!this._alternateSceneUbo) {
  19591. this._createAlternateUbo();
  19592. }
  19593. if (this._alternateSceneUbo.useUbo) {
  19594. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  19595. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  19596. this._alternateSceneUbo.update();
  19597. }
  19598. };
  19599. Scene.prototype.getSceneUniformBuffer = function () {
  19600. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  19601. };
  19602. // Methods
  19603. Scene.prototype.getUniqueId = function () {
  19604. var result = Scene._uniqueIdCounter;
  19605. Scene._uniqueIdCounter++;
  19606. return result;
  19607. };
  19608. Scene.prototype.addMesh = function (newMesh) {
  19609. this.meshes.push(newMesh);
  19610. //notify the collision coordinator
  19611. if (this.collisionCoordinator) {
  19612. this.collisionCoordinator.onMeshAdded(newMesh);
  19613. }
  19614. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  19615. };
  19616. Scene.prototype.removeMesh = function (toRemove) {
  19617. var index = this.meshes.indexOf(toRemove);
  19618. if (index !== -1) {
  19619. // Remove from the scene if mesh found
  19620. this.meshes.splice(index, 1);
  19621. }
  19622. this.onMeshRemovedObservable.notifyObservers(toRemove);
  19623. return index;
  19624. };
  19625. Scene.prototype.addTransformNode = function (newTransformNode) {
  19626. this.transformNodes.push(newTransformNode);
  19627. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  19628. };
  19629. Scene.prototype.removeTransformNode = function (toRemove) {
  19630. var index = this.transformNodes.indexOf(toRemove);
  19631. if (index !== -1) {
  19632. // Remove from the scene if found
  19633. this.transformNodes.splice(index, 1);
  19634. }
  19635. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  19636. return index;
  19637. };
  19638. Scene.prototype.removeSkeleton = function (toRemove) {
  19639. var index = this.skeletons.indexOf(toRemove);
  19640. if (index !== -1) {
  19641. // Remove from the scene if found
  19642. this.skeletons.splice(index, 1);
  19643. }
  19644. return index;
  19645. };
  19646. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  19647. var index = this.morphTargetManagers.indexOf(toRemove);
  19648. if (index !== -1) {
  19649. // Remove from the scene if found
  19650. this.morphTargetManagers.splice(index, 1);
  19651. }
  19652. return index;
  19653. };
  19654. Scene.prototype.removeLight = function (toRemove) {
  19655. var index = this.lights.indexOf(toRemove);
  19656. if (index !== -1) {
  19657. // Remove from the scene if mesh found
  19658. this.lights.splice(index, 1);
  19659. this.sortLightsByPriority();
  19660. }
  19661. this.onLightRemovedObservable.notifyObservers(toRemove);
  19662. return index;
  19663. };
  19664. Scene.prototype.removeCamera = function (toRemove) {
  19665. var index = this.cameras.indexOf(toRemove);
  19666. if (index !== -1) {
  19667. // Remove from the scene if mesh found
  19668. this.cameras.splice(index, 1);
  19669. }
  19670. // Remove from activeCameras
  19671. var index2 = this.activeCameras.indexOf(toRemove);
  19672. if (index2 !== -1) {
  19673. // Remove from the scene if mesh found
  19674. this.activeCameras.splice(index2, 1);
  19675. }
  19676. // Reset the activeCamera
  19677. if (this.activeCamera === toRemove) {
  19678. if (this.cameras.length > 0) {
  19679. this.activeCamera = this.cameras[0];
  19680. }
  19681. else {
  19682. this.activeCamera = null;
  19683. }
  19684. }
  19685. this.onCameraRemovedObservable.notifyObservers(toRemove);
  19686. return index;
  19687. };
  19688. Scene.prototype.addLight = function (newLight) {
  19689. this.lights.push(newLight);
  19690. this.sortLightsByPriority();
  19691. this.onNewLightAddedObservable.notifyObservers(newLight);
  19692. };
  19693. Scene.prototype.sortLightsByPriority = function () {
  19694. if (this.requireLightSorting) {
  19695. this.lights.sort(BABYLON.Light.compareLightsPriority);
  19696. }
  19697. };
  19698. Scene.prototype.addCamera = function (newCamera) {
  19699. this.cameras.push(newCamera);
  19700. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  19701. };
  19702. /**
  19703. * Switch active camera
  19704. * @param {Camera} newCamera - new active camera
  19705. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  19706. */
  19707. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  19708. if (attachControl === void 0) { attachControl = true; }
  19709. var canvas = this._engine.getRenderingCanvas();
  19710. if (!canvas) {
  19711. return;
  19712. }
  19713. if (this.activeCamera) {
  19714. this.activeCamera.detachControl(canvas);
  19715. }
  19716. this.activeCamera = newCamera;
  19717. if (attachControl) {
  19718. newCamera.attachControl(canvas);
  19719. }
  19720. };
  19721. /**
  19722. * sets the active camera of the scene using its ID
  19723. * @param {string} id - the camera's ID
  19724. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  19725. * @see activeCamera
  19726. */
  19727. Scene.prototype.setActiveCameraByID = function (id) {
  19728. var camera = this.getCameraByID(id);
  19729. if (camera) {
  19730. this.activeCamera = camera;
  19731. return camera;
  19732. }
  19733. return null;
  19734. };
  19735. /**
  19736. * sets the active camera of the scene using its name
  19737. * @param {string} name - the camera's name
  19738. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  19739. * @see activeCamera
  19740. */
  19741. Scene.prototype.setActiveCameraByName = function (name) {
  19742. var camera = this.getCameraByName(name);
  19743. if (camera) {
  19744. this.activeCamera = camera;
  19745. return camera;
  19746. }
  19747. return null;
  19748. };
  19749. /**
  19750. * get a material using its id
  19751. * @param {string} the material's ID
  19752. * @return {BABYLON.Material|null} the material or null if none found.
  19753. */
  19754. Scene.prototype.getMaterialByID = function (id) {
  19755. for (var index = 0; index < this.materials.length; index++) {
  19756. if (this.materials[index].id === id) {
  19757. return this.materials[index];
  19758. }
  19759. }
  19760. return null;
  19761. };
  19762. /**
  19763. * get a material using its name
  19764. * @param {string} the material's name
  19765. * @return {BABYLON.Material|null} the material or null if none found.
  19766. */
  19767. Scene.prototype.getMaterialByName = function (name) {
  19768. for (var index = 0; index < this.materials.length; index++) {
  19769. if (this.materials[index].name === name) {
  19770. return this.materials[index];
  19771. }
  19772. }
  19773. return null;
  19774. };
  19775. Scene.prototype.getLensFlareSystemByName = function (name) {
  19776. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  19777. if (this.lensFlareSystems[index].name === name) {
  19778. return this.lensFlareSystems[index];
  19779. }
  19780. }
  19781. return null;
  19782. };
  19783. Scene.prototype.getLensFlareSystemByID = function (id) {
  19784. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  19785. if (this.lensFlareSystems[index].id === id) {
  19786. return this.lensFlareSystems[index];
  19787. }
  19788. }
  19789. return null;
  19790. };
  19791. Scene.prototype.getCameraByID = function (id) {
  19792. for (var index = 0; index < this.cameras.length; index++) {
  19793. if (this.cameras[index].id === id) {
  19794. return this.cameras[index];
  19795. }
  19796. }
  19797. return null;
  19798. };
  19799. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  19800. for (var index = 0; index < this.cameras.length; index++) {
  19801. if (this.cameras[index].uniqueId === uniqueId) {
  19802. return this.cameras[index];
  19803. }
  19804. }
  19805. return null;
  19806. };
  19807. /**
  19808. * get a camera using its name
  19809. * @param {string} the camera's name
  19810. * @return {BABYLON.Camera|null} the camera or null if none found.
  19811. */
  19812. Scene.prototype.getCameraByName = function (name) {
  19813. for (var index = 0; index < this.cameras.length; index++) {
  19814. if (this.cameras[index].name === name) {
  19815. return this.cameras[index];
  19816. }
  19817. }
  19818. return null;
  19819. };
  19820. /**
  19821. * get a bone using its id
  19822. * @param {string} the bone's id
  19823. * @return {BABYLON.Bone|null} the bone or null if not found
  19824. */
  19825. Scene.prototype.getBoneByID = function (id) {
  19826. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  19827. var skeleton = this.skeletons[skeletonIndex];
  19828. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  19829. if (skeleton.bones[boneIndex].id === id) {
  19830. return skeleton.bones[boneIndex];
  19831. }
  19832. }
  19833. }
  19834. return null;
  19835. };
  19836. /**
  19837. * get a bone using its id
  19838. * @param {string} the bone's name
  19839. * @return {BABYLON.Bone|null} the bone or null if not found
  19840. */
  19841. Scene.prototype.getBoneByName = function (name) {
  19842. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  19843. var skeleton = this.skeletons[skeletonIndex];
  19844. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  19845. if (skeleton.bones[boneIndex].name === name) {
  19846. return skeleton.bones[boneIndex];
  19847. }
  19848. }
  19849. }
  19850. return null;
  19851. };
  19852. /**
  19853. * get a light node using its name
  19854. * @param {string} the light's name
  19855. * @return {BABYLON.Light|null} the light or null if none found.
  19856. */
  19857. Scene.prototype.getLightByName = function (name) {
  19858. for (var index = 0; index < this.lights.length; index++) {
  19859. if (this.lights[index].name === name) {
  19860. return this.lights[index];
  19861. }
  19862. }
  19863. return null;
  19864. };
  19865. /**
  19866. * get a light node using its ID
  19867. * @param {string} the light's id
  19868. * @return {BABYLON.Light|null} the light or null if none found.
  19869. */
  19870. Scene.prototype.getLightByID = function (id) {
  19871. for (var index = 0; index < this.lights.length; index++) {
  19872. if (this.lights[index].id === id) {
  19873. return this.lights[index];
  19874. }
  19875. }
  19876. return null;
  19877. };
  19878. /**
  19879. * get a light node using its scene-generated unique ID
  19880. * @param {number} the light's unique id
  19881. * @return {BABYLON.Light|null} the light or null if none found.
  19882. */
  19883. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  19884. for (var index = 0; index < this.lights.length; index++) {
  19885. if (this.lights[index].uniqueId === uniqueId) {
  19886. return this.lights[index];
  19887. }
  19888. }
  19889. return null;
  19890. };
  19891. /**
  19892. * get a particle system by id
  19893. * @param id {number} the particle system id
  19894. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  19895. */
  19896. Scene.prototype.getParticleSystemByID = function (id) {
  19897. for (var index = 0; index < this.particleSystems.length; index++) {
  19898. if (this.particleSystems[index].id === id) {
  19899. return this.particleSystems[index];
  19900. }
  19901. }
  19902. return null;
  19903. };
  19904. /**
  19905. * get a geometry using its ID
  19906. * @param {string} the geometry's id
  19907. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  19908. */
  19909. Scene.prototype.getGeometryByID = function (id) {
  19910. for (var index = 0; index < this._geometries.length; index++) {
  19911. if (this._geometries[index].id === id) {
  19912. return this._geometries[index];
  19913. }
  19914. }
  19915. return null;
  19916. };
  19917. /**
  19918. * add a new geometry to this scene.
  19919. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  19920. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  19921. * @return {boolean} was the geometry added or not
  19922. */
  19923. Scene.prototype.pushGeometry = function (geometry, force) {
  19924. if (!force && this.getGeometryByID(geometry.id)) {
  19925. return false;
  19926. }
  19927. this._geometries.push(geometry);
  19928. //notify the collision coordinator
  19929. if (this.collisionCoordinator) {
  19930. this.collisionCoordinator.onGeometryAdded(geometry);
  19931. }
  19932. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  19933. return true;
  19934. };
  19935. /**
  19936. * Removes an existing geometry
  19937. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  19938. * @return {boolean} was the geometry removed or not
  19939. */
  19940. Scene.prototype.removeGeometry = function (geometry) {
  19941. var index = this._geometries.indexOf(geometry);
  19942. if (index > -1) {
  19943. this._geometries.splice(index, 1);
  19944. //notify the collision coordinator
  19945. if (this.collisionCoordinator) {
  19946. this.collisionCoordinator.onGeometryDeleted(geometry);
  19947. }
  19948. this.onGeometryRemovedObservable.notifyObservers(geometry);
  19949. return true;
  19950. }
  19951. return false;
  19952. };
  19953. Scene.prototype.getGeometries = function () {
  19954. return this._geometries;
  19955. };
  19956. /**
  19957. * Get the first added mesh found of a given ID
  19958. * @param {string} id - the id to search for
  19959. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19960. */
  19961. Scene.prototype.getMeshByID = function (id) {
  19962. for (var index = 0; index < this.meshes.length; index++) {
  19963. if (this.meshes[index].id === id) {
  19964. return this.meshes[index];
  19965. }
  19966. }
  19967. return null;
  19968. };
  19969. Scene.prototype.getMeshesByID = function (id) {
  19970. return this.meshes.filter(function (m) {
  19971. return m.id === id;
  19972. });
  19973. };
  19974. /**
  19975. * Get the first added transform node found of a given ID
  19976. * @param {string} id - the id to search for
  19977. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  19978. */
  19979. Scene.prototype.getTransformNodeByID = function (id) {
  19980. for (var index = 0; index < this.transformNodes.length; index++) {
  19981. if (this.transformNodes[index].id === id) {
  19982. return this.transformNodes[index];
  19983. }
  19984. }
  19985. return null;
  19986. };
  19987. Scene.prototype.getTransformNodesByID = function (id) {
  19988. return this.transformNodes.filter(function (m) {
  19989. return m.id === id;
  19990. });
  19991. };
  19992. /**
  19993. * Get a mesh with its auto-generated unique id
  19994. * @param {number} uniqueId - the unique id to search for
  19995. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19996. */
  19997. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  19998. for (var index = 0; index < this.meshes.length; index++) {
  19999. if (this.meshes[index].uniqueId === uniqueId) {
  20000. return this.meshes[index];
  20001. }
  20002. }
  20003. return null;
  20004. };
  20005. /**
  20006. * Get a the last added mesh found of a given ID
  20007. * @param {string} id - the id to search for
  20008. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  20009. */
  20010. Scene.prototype.getLastMeshByID = function (id) {
  20011. for (var index = this.meshes.length - 1; index >= 0; index--) {
  20012. if (this.meshes[index].id === id) {
  20013. return this.meshes[index];
  20014. }
  20015. }
  20016. return null;
  20017. };
  20018. /**
  20019. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  20020. * @param {string} id - the id to search for
  20021. * @return {BABYLON.Node|null} the node found or null if not found at all.
  20022. */
  20023. Scene.prototype.getLastEntryByID = function (id) {
  20024. var index;
  20025. for (index = this.meshes.length - 1; index >= 0; index--) {
  20026. if (this.meshes[index].id === id) {
  20027. return this.meshes[index];
  20028. }
  20029. }
  20030. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  20031. if (this.transformNodes[index].id === id) {
  20032. return this.transformNodes[index];
  20033. }
  20034. }
  20035. for (index = this.cameras.length - 1; index >= 0; index--) {
  20036. if (this.cameras[index].id === id) {
  20037. return this.cameras[index];
  20038. }
  20039. }
  20040. for (index = this.lights.length - 1; index >= 0; index--) {
  20041. if (this.lights[index].id === id) {
  20042. return this.lights[index];
  20043. }
  20044. }
  20045. return null;
  20046. };
  20047. Scene.prototype.getNodeByID = function (id) {
  20048. var mesh = this.getMeshByID(id);
  20049. if (mesh) {
  20050. return mesh;
  20051. }
  20052. var light = this.getLightByID(id);
  20053. if (light) {
  20054. return light;
  20055. }
  20056. var camera = this.getCameraByID(id);
  20057. if (camera) {
  20058. return camera;
  20059. }
  20060. var bone = this.getBoneByID(id);
  20061. return bone;
  20062. };
  20063. Scene.prototype.getNodeByName = function (name) {
  20064. var mesh = this.getMeshByName(name);
  20065. if (mesh) {
  20066. return mesh;
  20067. }
  20068. var light = this.getLightByName(name);
  20069. if (light) {
  20070. return light;
  20071. }
  20072. var camera = this.getCameraByName(name);
  20073. if (camera) {
  20074. return camera;
  20075. }
  20076. var bone = this.getBoneByName(name);
  20077. return bone;
  20078. };
  20079. Scene.prototype.getMeshByName = function (name) {
  20080. for (var index = 0; index < this.meshes.length; index++) {
  20081. if (this.meshes[index].name === name) {
  20082. return this.meshes[index];
  20083. }
  20084. }
  20085. return null;
  20086. };
  20087. Scene.prototype.getTransformNodeByName = function (name) {
  20088. for (var index = 0; index < this.transformNodes.length; index++) {
  20089. if (this.transformNodes[index].name === name) {
  20090. return this.transformNodes[index];
  20091. }
  20092. }
  20093. return null;
  20094. };
  20095. Scene.prototype.getSoundByName = function (name) {
  20096. var index;
  20097. if (BABYLON.AudioEngine) {
  20098. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  20099. if (this.mainSoundTrack.soundCollection[index].name === name) {
  20100. return this.mainSoundTrack.soundCollection[index];
  20101. }
  20102. }
  20103. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  20104. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  20105. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  20106. return this.soundTracks[sdIndex].soundCollection[index];
  20107. }
  20108. }
  20109. }
  20110. }
  20111. return null;
  20112. };
  20113. Scene.prototype.getLastSkeletonByID = function (id) {
  20114. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  20115. if (this.skeletons[index].id === id) {
  20116. return this.skeletons[index];
  20117. }
  20118. }
  20119. return null;
  20120. };
  20121. Scene.prototype.getSkeletonById = function (id) {
  20122. for (var index = 0; index < this.skeletons.length; index++) {
  20123. if (this.skeletons[index].id === id) {
  20124. return this.skeletons[index];
  20125. }
  20126. }
  20127. return null;
  20128. };
  20129. Scene.prototype.getSkeletonByName = function (name) {
  20130. for (var index = 0; index < this.skeletons.length; index++) {
  20131. if (this.skeletons[index].name === name) {
  20132. return this.skeletons[index];
  20133. }
  20134. }
  20135. return null;
  20136. };
  20137. Scene.prototype.getMorphTargetManagerById = function (id) {
  20138. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  20139. if (this.morphTargetManagers[index].uniqueId === id) {
  20140. return this.morphTargetManagers[index];
  20141. }
  20142. }
  20143. return null;
  20144. };
  20145. Scene.prototype.isActiveMesh = function (mesh) {
  20146. return (this._activeMeshes.indexOf(mesh) !== -1);
  20147. };
  20148. /**
  20149. * Return a the first highlight layer of the scene with a given name.
  20150. * @param name The name of the highlight layer to look for.
  20151. * @return The highlight layer if found otherwise null.
  20152. */
  20153. Scene.prototype.getHighlightLayerByName = function (name) {
  20154. for (var index = 0; index < this.highlightLayers.length; index++) {
  20155. if (this.highlightLayers[index].name === name) {
  20156. return this.highlightLayers[index];
  20157. }
  20158. }
  20159. return null;
  20160. };
  20161. Object.defineProperty(Scene.prototype, "uid", {
  20162. /**
  20163. * Return a unique id as a string which can serve as an identifier for the scene
  20164. */
  20165. get: function () {
  20166. if (!this._uid) {
  20167. this._uid = BABYLON.Tools.RandomId();
  20168. }
  20169. return this._uid;
  20170. },
  20171. enumerable: true,
  20172. configurable: true
  20173. });
  20174. /**
  20175. * Add an externaly attached data from its key.
  20176. * This method call will fail and return false, if such key already exists.
  20177. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  20178. * @param key the unique key that identifies the data
  20179. * @param data the data object to associate to the key for this Engine instance
  20180. * @return true if no such key were already present and the data was added successfully, false otherwise
  20181. */
  20182. Scene.prototype.addExternalData = function (key, data) {
  20183. if (!this._externalData) {
  20184. this._externalData = new BABYLON.StringDictionary();
  20185. }
  20186. return this._externalData.add(key, data);
  20187. };
  20188. /**
  20189. * Get an externaly attached data from its key
  20190. * @param key the unique key that identifies the data
  20191. * @return the associated data, if present (can be null), or undefined if not present
  20192. */
  20193. Scene.prototype.getExternalData = function (key) {
  20194. if (!this._externalData) {
  20195. return null;
  20196. }
  20197. return this._externalData.get(key);
  20198. };
  20199. /**
  20200. * Get an externaly attached data from its key, create it using a factory if it's not already present
  20201. * @param key the unique key that identifies the data
  20202. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  20203. * @return the associated data, can be null if the factory returned null.
  20204. */
  20205. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  20206. if (!this._externalData) {
  20207. this._externalData = new BABYLON.StringDictionary();
  20208. }
  20209. return this._externalData.getOrAddWithFactory(key, factory);
  20210. };
  20211. /**
  20212. * Remove an externaly attached data from the Engine instance
  20213. * @param key the unique key that identifies the data
  20214. * @return true if the data was successfully removed, false if it doesn't exist
  20215. */
  20216. Scene.prototype.removeExternalData = function (key) {
  20217. return this._externalData.remove(key);
  20218. };
  20219. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  20220. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  20221. var material = subMesh.getMaterial();
  20222. if (mesh.showSubMeshesBoundingBox) {
  20223. var boundingInfo = subMesh.getBoundingInfo();
  20224. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  20225. }
  20226. if (material) {
  20227. // Render targets
  20228. if (material.getRenderTargetTextures) {
  20229. if (this._processedMaterials.indexOf(material) === -1) {
  20230. this._processedMaterials.push(material);
  20231. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  20232. }
  20233. }
  20234. // Dispatch
  20235. this._activeIndices.addCount(subMesh.indexCount, false);
  20236. this._renderingManager.dispatch(subMesh);
  20237. }
  20238. }
  20239. };
  20240. Scene.prototype._isInIntermediateRendering = function () {
  20241. return this._intermediateRendering;
  20242. };
  20243. /**
  20244. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  20245. */
  20246. Scene.prototype.freezeActiveMeshes = function () {
  20247. this._evaluateActiveMeshes();
  20248. this._activeMeshesFrozen = true;
  20249. return this;
  20250. };
  20251. /**
  20252. * Use this function to restart evaluating active meshes on every frame
  20253. */
  20254. Scene.prototype.unfreezeActiveMeshes = function () {
  20255. this._activeMeshesFrozen = false;
  20256. return this;
  20257. };
  20258. Scene.prototype._evaluateActiveMeshes = function () {
  20259. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  20260. return;
  20261. }
  20262. if (!this.activeCamera) {
  20263. return;
  20264. }
  20265. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  20266. this.activeCamera._activeMeshes.reset();
  20267. this._activeMeshes.reset();
  20268. this._renderingManager.reset();
  20269. this._processedMaterials.reset();
  20270. this._activeParticleSystems.reset();
  20271. this._activeSkeletons.reset();
  20272. this._softwareSkinnedMeshes.reset();
  20273. if (this._boundingBoxRenderer) {
  20274. this._boundingBoxRenderer.reset();
  20275. }
  20276. // Meshes
  20277. var meshes;
  20278. var len;
  20279. if (this._selectionOctree) {
  20280. var selection = this._selectionOctree.select(this._frustumPlanes);
  20281. meshes = selection.data;
  20282. len = selection.length;
  20283. }
  20284. else {
  20285. len = this.meshes.length;
  20286. meshes = this.meshes;
  20287. }
  20288. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  20289. var mesh = meshes[meshIndex];
  20290. if (mesh.isBlocked) {
  20291. continue;
  20292. }
  20293. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  20294. if (!mesh.isReady() || !mesh.isEnabled()) {
  20295. continue;
  20296. }
  20297. mesh.computeWorldMatrix();
  20298. // Intersections
  20299. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  20300. this._meshesForIntersections.pushNoDuplicate(mesh);
  20301. }
  20302. // Switch to current LOD
  20303. var meshLOD = mesh.getLOD(this.activeCamera);
  20304. if (!meshLOD) {
  20305. continue;
  20306. }
  20307. mesh._preActivate();
  20308. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  20309. this._activeMeshes.push(mesh);
  20310. this.activeCamera._activeMeshes.push(mesh);
  20311. mesh._activate(this._renderId);
  20312. if (meshLOD !== mesh) {
  20313. meshLOD._activate(this._renderId);
  20314. }
  20315. this._activeMesh(mesh, meshLOD);
  20316. }
  20317. }
  20318. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  20319. // Particle systems
  20320. if (this.particlesEnabled) {
  20321. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  20322. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  20323. var particleSystem = this.particleSystems[particleIndex];
  20324. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  20325. continue;
  20326. }
  20327. var emitter = particleSystem.emitter;
  20328. if (!emitter.position || emitter.isEnabled()) {
  20329. this._activeParticleSystems.push(particleSystem);
  20330. particleSystem.animate();
  20331. this._renderingManager.dispatchParticles(particleSystem);
  20332. }
  20333. }
  20334. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  20335. }
  20336. };
  20337. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  20338. if (mesh.skeleton && this.skeletonsEnabled) {
  20339. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  20340. mesh.skeleton.prepare();
  20341. }
  20342. if (!mesh.computeBonesUsingShaders) {
  20343. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  20344. }
  20345. }
  20346. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  20347. var boundingInfo = sourceMesh.getBoundingInfo();
  20348. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  20349. }
  20350. if (mesh && mesh.subMeshes) {
  20351. // Submeshes Octrees
  20352. var len;
  20353. var subMeshes;
  20354. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  20355. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  20356. len = intersections.length;
  20357. subMeshes = intersections.data;
  20358. }
  20359. else {
  20360. subMeshes = mesh.subMeshes;
  20361. len = subMeshes.length;
  20362. }
  20363. for (var subIndex = 0; subIndex < len; subIndex++) {
  20364. var subMesh = subMeshes[subIndex];
  20365. this._evaluateSubMesh(subMesh, mesh);
  20366. }
  20367. }
  20368. };
  20369. Scene.prototype.updateTransformMatrix = function (force) {
  20370. if (!this.activeCamera) {
  20371. return;
  20372. }
  20373. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  20374. };
  20375. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  20376. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  20377. };
  20378. Scene.prototype._renderForCamera = function (camera) {
  20379. if (camera && camera._skipRendering) {
  20380. return;
  20381. }
  20382. var engine = this._engine;
  20383. this.activeCamera = camera;
  20384. if (!this.activeCamera)
  20385. throw new Error("Active camera not set");
  20386. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  20387. // Viewport
  20388. engine.setViewport(this.activeCamera.viewport);
  20389. // Camera
  20390. this.resetCachedMaterial();
  20391. this._renderId++;
  20392. this.activeCamera.update();
  20393. this.updateTransformMatrix();
  20394. if (camera._alternateCamera) {
  20395. this.updateAlternateTransformMatrix(camera._alternateCamera);
  20396. this._alternateRendering = true;
  20397. }
  20398. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  20399. // Meshes
  20400. this._evaluateActiveMeshes();
  20401. // Software skinning
  20402. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  20403. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  20404. mesh.applySkeleton(mesh.skeleton);
  20405. }
  20406. // Render targets
  20407. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  20408. var needsRestoreFrameBuffer = false;
  20409. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  20410. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  20411. }
  20412. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  20413. this._intermediateRendering = true;
  20414. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  20415. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  20416. var renderTarget = this._renderTargets.data[renderIndex];
  20417. if (renderTarget._shouldRender()) {
  20418. this._renderId++;
  20419. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  20420. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  20421. }
  20422. }
  20423. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  20424. this._intermediateRendering = false;
  20425. this._renderId++;
  20426. needsRestoreFrameBuffer = true; // Restore back buffer
  20427. }
  20428. // Render HighlightLayer Texture
  20429. var stencilState = this._engine.getStencilBuffer();
  20430. var renderhighlights = false;
  20431. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  20432. this._intermediateRendering = true;
  20433. for (var i = 0; i < this.highlightLayers.length; i++) {
  20434. var highlightLayer = this.highlightLayers[i];
  20435. if (highlightLayer.shouldRender() &&
  20436. (!highlightLayer.camera ||
  20437. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  20438. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  20439. renderhighlights = true;
  20440. var renderTarget = highlightLayer._mainTexture;
  20441. if (renderTarget._shouldRender()) {
  20442. this._renderId++;
  20443. renderTarget.render(false, false);
  20444. needsRestoreFrameBuffer = true;
  20445. }
  20446. }
  20447. }
  20448. this._intermediateRendering = false;
  20449. this._renderId++;
  20450. }
  20451. if (needsRestoreFrameBuffer) {
  20452. engine.restoreDefaultFramebuffer(); // Restore back buffer
  20453. }
  20454. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  20455. // Prepare Frame
  20456. this.postProcessManager._prepareFrame();
  20457. // Backgrounds
  20458. var layerIndex;
  20459. var layer;
  20460. if (this.layers.length) {
  20461. engine.setDepthBuffer(false);
  20462. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  20463. layer = this.layers[layerIndex];
  20464. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  20465. layer.render();
  20466. }
  20467. }
  20468. engine.setDepthBuffer(true);
  20469. }
  20470. // Activate HighlightLayer stencil
  20471. if (renderhighlights) {
  20472. this._engine.setStencilBuffer(true);
  20473. }
  20474. // Render
  20475. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  20476. this._renderingManager.render(null, null, true, true);
  20477. this.onAfterDrawPhaseObservable.notifyObservers(this);
  20478. // Restore HighlightLayer stencil
  20479. if (renderhighlights) {
  20480. this._engine.setStencilBuffer(stencilState);
  20481. }
  20482. // Bounding boxes
  20483. if (this._boundingBoxRenderer) {
  20484. this._boundingBoxRenderer.render();
  20485. }
  20486. // Lens flares
  20487. if (this.lensFlaresEnabled) {
  20488. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  20489. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  20490. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  20491. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  20492. lensFlareSystem.render();
  20493. }
  20494. }
  20495. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  20496. }
  20497. // Foregrounds
  20498. if (this.layers.length) {
  20499. engine.setDepthBuffer(false);
  20500. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  20501. layer = this.layers[layerIndex];
  20502. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  20503. layer.render();
  20504. }
  20505. }
  20506. engine.setDepthBuffer(true);
  20507. }
  20508. // Highlight Layer
  20509. if (renderhighlights) {
  20510. engine.setDepthBuffer(false);
  20511. for (var i = 0; i < this.highlightLayers.length; i++) {
  20512. if (this.highlightLayers[i].shouldRender()) {
  20513. this.highlightLayers[i].render();
  20514. }
  20515. }
  20516. engine.setDepthBuffer(true);
  20517. }
  20518. // Finalize frame
  20519. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  20520. // Reset some special arrays
  20521. this._renderTargets.reset();
  20522. this._alternateRendering = false;
  20523. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  20524. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  20525. };
  20526. Scene.prototype._processSubCameras = function (camera) {
  20527. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  20528. this._renderForCamera(camera);
  20529. return;
  20530. }
  20531. // Update camera
  20532. if (this.activeCamera) {
  20533. this.activeCamera.update();
  20534. }
  20535. // rig cameras
  20536. for (var index = 0; index < camera._rigCameras.length; index++) {
  20537. this._renderForCamera(camera._rigCameras[index]);
  20538. }
  20539. this.activeCamera = camera;
  20540. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  20541. };
  20542. Scene.prototype._checkIntersections = function () {
  20543. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  20544. var sourceMesh = this._meshesForIntersections.data[index];
  20545. if (!sourceMesh.actionManager) {
  20546. continue;
  20547. }
  20548. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  20549. var action = sourceMesh.actionManager.actions[actionIndex];
  20550. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20551. var parameters = action.getTriggerParameter();
  20552. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  20553. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  20554. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  20555. if (areIntersecting && currentIntersectionInProgress === -1) {
  20556. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  20557. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  20558. sourceMesh._intersectionsInProgress.push(otherMesh);
  20559. }
  20560. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20561. sourceMesh._intersectionsInProgress.push(otherMesh);
  20562. }
  20563. }
  20564. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  20565. //They intersected, and now they don't.
  20566. //is this trigger an exit trigger? execute an event.
  20567. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20568. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  20569. }
  20570. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  20571. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20572. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  20573. }
  20574. }
  20575. }
  20576. }
  20577. }
  20578. };
  20579. Scene.prototype.render = function () {
  20580. if (this.isDisposed) {
  20581. return;
  20582. }
  20583. this._activeParticles.fetchNewFrame();
  20584. this._totalVertices.fetchNewFrame();
  20585. this._activeIndices.fetchNewFrame();
  20586. this._activeBones.fetchNewFrame();
  20587. this._meshesForIntersections.reset();
  20588. this.resetCachedMaterial();
  20589. this.onBeforeAnimationsObservable.notifyObservers(this);
  20590. // Actions
  20591. if (this.actionManager) {
  20592. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  20593. }
  20594. //Simplification Queue
  20595. if (this.simplificationQueue && !this.simplificationQueue.running) {
  20596. this.simplificationQueue.executeNext();
  20597. }
  20598. if (this._engine.isDeterministicLockStep()) {
  20599. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  20600. var defaultFPS = (60.0 / 1000.0);
  20601. var defaultFrameTime = 1000 / 60; // frame time in MS
  20602. if (this._physicsEngine) {
  20603. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  20604. }
  20605. var stepsTaken = 0;
  20606. var maxSubSteps = this._engine.getLockstepMaxSteps();
  20607. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  20608. internalSteps = Math.min(internalSteps, maxSubSteps);
  20609. do {
  20610. this.onBeforeStepObservable.notifyObservers(this);
  20611. // Animations
  20612. this._animationRatio = defaultFrameTime * defaultFPS;
  20613. this._animate();
  20614. this.onAfterAnimationsObservable.notifyObservers(this);
  20615. // Physics
  20616. if (this._physicsEngine) {
  20617. this.onBeforePhysicsObservable.notifyObservers(this);
  20618. this._physicsEngine._step(defaultFrameTime / 1000);
  20619. this.onAfterPhysicsObservable.notifyObservers(this);
  20620. }
  20621. this.onAfterStepObservable.notifyObservers(this);
  20622. this._currentStepId++;
  20623. stepsTaken++;
  20624. deltaTime -= defaultFrameTime;
  20625. } while (deltaTime > 0 && stepsTaken < internalSteps);
  20626. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  20627. }
  20628. else {
  20629. // Animations
  20630. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  20631. this._animationRatio = deltaTime * (60.0 / 1000.0);
  20632. this._animate();
  20633. this.onAfterAnimationsObservable.notifyObservers(this);
  20634. // Physics
  20635. if (this._physicsEngine) {
  20636. this.onBeforePhysicsObservable.notifyObservers(this);
  20637. this._physicsEngine._step(deltaTime / 1000.0);
  20638. this.onAfterPhysicsObservable.notifyObservers(this);
  20639. }
  20640. }
  20641. // update gamepad manager
  20642. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  20643. this._gamepadManager._checkGamepadsStatus();
  20644. }
  20645. // Before render
  20646. this.onBeforeRenderObservable.notifyObservers(this);
  20647. // Customs render targets
  20648. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  20649. var engine = this.getEngine();
  20650. var currentActiveCamera = this.activeCamera;
  20651. if (this.renderTargetsEnabled) {
  20652. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  20653. this._intermediateRendering = true;
  20654. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  20655. var renderTarget = this.customRenderTargets[customIndex];
  20656. if (renderTarget._shouldRender()) {
  20657. this._renderId++;
  20658. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  20659. if (!this.activeCamera)
  20660. throw new Error("Active camera not set");
  20661. // Viewport
  20662. engine.setViewport(this.activeCamera.viewport);
  20663. // Camera
  20664. this.updateTransformMatrix();
  20665. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  20666. }
  20667. }
  20668. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  20669. this._intermediateRendering = false;
  20670. this._renderId++;
  20671. }
  20672. // Restore back buffer
  20673. if (this.customRenderTargets.length > 0) {
  20674. engine.restoreDefaultFramebuffer();
  20675. }
  20676. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  20677. this.activeCamera = currentActiveCamera;
  20678. // Procedural textures
  20679. if (this.proceduralTexturesEnabled) {
  20680. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  20681. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  20682. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  20683. if (proceduralTexture._shouldRender()) {
  20684. proceduralTexture.render();
  20685. }
  20686. }
  20687. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  20688. }
  20689. // Clear
  20690. if (this.autoClearDepthAndStencil || this.autoClear) {
  20691. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  20692. }
  20693. // Shadows
  20694. if (this.shadowsEnabled) {
  20695. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  20696. var light = this.lights[lightIndex];
  20697. var shadowGenerator = light.getShadowGenerator();
  20698. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  20699. var shadowMap = (shadowGenerator.getShadowMap());
  20700. if (this.textures.indexOf(shadowMap) !== -1) {
  20701. this._renderTargets.push(shadowMap);
  20702. }
  20703. }
  20704. }
  20705. }
  20706. // Depth renderer
  20707. if (this._depthRenderer) {
  20708. this._renderTargets.push(this._depthRenderer.getDepthMap());
  20709. }
  20710. // Geometry renderer
  20711. if (this._geometryBufferRenderer) {
  20712. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  20713. }
  20714. // RenderPipeline
  20715. if (this._postProcessRenderPipelineManager) {
  20716. this._postProcessRenderPipelineManager.update();
  20717. }
  20718. // Multi-cameras?
  20719. if (this.activeCameras.length > 0) {
  20720. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  20721. if (cameraIndex > 0) {
  20722. this._engine.clear(null, false, true, true);
  20723. }
  20724. this._processSubCameras(this.activeCameras[cameraIndex]);
  20725. }
  20726. }
  20727. else {
  20728. if (!this.activeCamera) {
  20729. throw new Error("No camera defined");
  20730. }
  20731. this._processSubCameras(this.activeCamera);
  20732. }
  20733. // Intersection checks
  20734. this._checkIntersections();
  20735. // Update the audio listener attached to the camera
  20736. if (BABYLON.AudioEngine) {
  20737. this._updateAudioParameters();
  20738. }
  20739. // After render
  20740. if (this.afterRender) {
  20741. this.afterRender();
  20742. }
  20743. this.onAfterRenderObservable.notifyObservers(this);
  20744. // Cleaning
  20745. for (var index = 0; index < this._toBeDisposed.length; index++) {
  20746. var data = this._toBeDisposed.data[index];
  20747. if (data) {
  20748. data.dispose();
  20749. }
  20750. this._toBeDisposed[index] = null;
  20751. }
  20752. this._toBeDisposed.reset();
  20753. if (this.dumpNextRenderTargets) {
  20754. this.dumpNextRenderTargets = false;
  20755. }
  20756. this._activeBones.addCount(0, true);
  20757. this._activeIndices.addCount(0, true);
  20758. this._activeParticles.addCount(0, true);
  20759. };
  20760. Scene.prototype._updateAudioParameters = function () {
  20761. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  20762. return;
  20763. }
  20764. var listeningCamera;
  20765. var audioEngine = BABYLON.Engine.audioEngine;
  20766. if (this.activeCameras.length > 0) {
  20767. listeningCamera = this.activeCameras[0];
  20768. }
  20769. else {
  20770. listeningCamera = this.activeCamera;
  20771. }
  20772. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  20773. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  20774. // for VR cameras
  20775. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  20776. listeningCamera = listeningCamera.rigCameras[0];
  20777. }
  20778. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  20779. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  20780. cameraDirection.normalize();
  20781. // To avoid some errors on GearVR
  20782. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  20783. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  20784. }
  20785. var i;
  20786. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20787. var sound = this.mainSoundTrack.soundCollection[i];
  20788. if (sound.useCustomAttenuation) {
  20789. sound.updateDistanceFromListener();
  20790. }
  20791. }
  20792. for (i = 0; i < this.soundTracks.length; i++) {
  20793. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20794. sound = this.soundTracks[i].soundCollection[j];
  20795. if (sound.useCustomAttenuation) {
  20796. sound.updateDistanceFromListener();
  20797. }
  20798. }
  20799. }
  20800. }
  20801. };
  20802. Object.defineProperty(Scene.prototype, "audioEnabled", {
  20803. // Audio
  20804. get: function () {
  20805. return this._audioEnabled;
  20806. },
  20807. set: function (value) {
  20808. this._audioEnabled = value;
  20809. if (BABYLON.AudioEngine) {
  20810. if (this._audioEnabled) {
  20811. this._enableAudio();
  20812. }
  20813. else {
  20814. this._disableAudio();
  20815. }
  20816. }
  20817. },
  20818. enumerable: true,
  20819. configurable: true
  20820. });
  20821. Scene.prototype._disableAudio = function () {
  20822. var i;
  20823. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20824. this.mainSoundTrack.soundCollection[i].pause();
  20825. }
  20826. for (i = 0; i < this.soundTracks.length; i++) {
  20827. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20828. this.soundTracks[i].soundCollection[j].pause();
  20829. }
  20830. }
  20831. };
  20832. Scene.prototype._enableAudio = function () {
  20833. var i;
  20834. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20835. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  20836. this.mainSoundTrack.soundCollection[i].play();
  20837. }
  20838. }
  20839. for (i = 0; i < this.soundTracks.length; i++) {
  20840. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20841. if (this.soundTracks[i].soundCollection[j].isPaused) {
  20842. this.soundTracks[i].soundCollection[j].play();
  20843. }
  20844. }
  20845. }
  20846. };
  20847. Object.defineProperty(Scene.prototype, "headphone", {
  20848. get: function () {
  20849. return this._headphone;
  20850. },
  20851. set: function (value) {
  20852. this._headphone = value;
  20853. if (BABYLON.AudioEngine) {
  20854. if (this._headphone) {
  20855. this._switchAudioModeForHeadphones();
  20856. }
  20857. else {
  20858. this._switchAudioModeForNormalSpeakers();
  20859. }
  20860. }
  20861. },
  20862. enumerable: true,
  20863. configurable: true
  20864. });
  20865. Scene.prototype._switchAudioModeForHeadphones = function () {
  20866. this.mainSoundTrack.switchPanningModelToHRTF();
  20867. for (var i = 0; i < this.soundTracks.length; i++) {
  20868. this.soundTracks[i].switchPanningModelToHRTF();
  20869. }
  20870. };
  20871. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  20872. this.mainSoundTrack.switchPanningModelToEqualPower();
  20873. for (var i = 0; i < this.soundTracks.length; i++) {
  20874. this.soundTracks[i].switchPanningModelToEqualPower();
  20875. }
  20876. };
  20877. Scene.prototype.enableDepthRenderer = function () {
  20878. if (this._depthRenderer) {
  20879. return this._depthRenderer;
  20880. }
  20881. this._depthRenderer = new BABYLON.DepthRenderer(this);
  20882. return this._depthRenderer;
  20883. };
  20884. Scene.prototype.disableDepthRenderer = function () {
  20885. if (!this._depthRenderer) {
  20886. return;
  20887. }
  20888. this._depthRenderer.dispose();
  20889. this._depthRenderer = null;
  20890. };
  20891. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  20892. if (ratio === void 0) { ratio = 1; }
  20893. if (this._geometryBufferRenderer) {
  20894. return this._geometryBufferRenderer;
  20895. }
  20896. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  20897. if (!this._geometryBufferRenderer.isSupported) {
  20898. this._geometryBufferRenderer = null;
  20899. }
  20900. return this._geometryBufferRenderer;
  20901. };
  20902. Scene.prototype.disableGeometryBufferRenderer = function () {
  20903. if (!this._geometryBufferRenderer) {
  20904. return;
  20905. }
  20906. this._geometryBufferRenderer.dispose();
  20907. this._geometryBufferRenderer = null;
  20908. };
  20909. Scene.prototype.freezeMaterials = function () {
  20910. for (var i = 0; i < this.materials.length; i++) {
  20911. this.materials[i].freeze();
  20912. }
  20913. };
  20914. Scene.prototype.unfreezeMaterials = function () {
  20915. for (var i = 0; i < this.materials.length; i++) {
  20916. this.materials[i].unfreeze();
  20917. }
  20918. };
  20919. Scene.prototype.dispose = function () {
  20920. this.beforeRender = null;
  20921. this.afterRender = null;
  20922. this.skeletons = [];
  20923. this.morphTargetManagers = [];
  20924. this.importedMeshesFiles = new Array();
  20925. this.stopAllAnimations();
  20926. this.resetCachedMaterial();
  20927. if (this._depthRenderer) {
  20928. this._depthRenderer.dispose();
  20929. }
  20930. if (this._gamepadManager) {
  20931. this._gamepadManager.dispose();
  20932. this._gamepadManager = null;
  20933. }
  20934. // Smart arrays
  20935. if (this.activeCamera) {
  20936. this.activeCamera._activeMeshes.dispose();
  20937. this.activeCamera = null;
  20938. }
  20939. this._activeMeshes.dispose();
  20940. this._renderingManager.dispose();
  20941. this._processedMaterials.dispose();
  20942. this._activeParticleSystems.dispose();
  20943. this._activeSkeletons.dispose();
  20944. this._softwareSkinnedMeshes.dispose();
  20945. this._renderTargets.dispose();
  20946. if (this._boundingBoxRenderer) {
  20947. this._boundingBoxRenderer.dispose();
  20948. }
  20949. this._meshesForIntersections.dispose();
  20950. this._toBeDisposed.dispose();
  20951. // Debug layer
  20952. if (this._debugLayer) {
  20953. this._debugLayer.hide();
  20954. }
  20955. // Events
  20956. this.onDisposeObservable.notifyObservers(this);
  20957. this.onDisposeObservable.clear();
  20958. this.onBeforeRenderObservable.clear();
  20959. this.onAfterRenderObservable.clear();
  20960. this.OnBeforeRenderTargetsRenderObservable.clear();
  20961. this.OnAfterRenderTargetsRenderObservable.clear();
  20962. this.onAfterStepObservable.clear();
  20963. this.onBeforeStepObservable.clear();
  20964. this.onBeforeActiveMeshesEvaluationObservable.clear();
  20965. this.onAfterActiveMeshesEvaluationObservable.clear();
  20966. this.onBeforeParticlesRenderingObservable.clear();
  20967. this.onAfterParticlesRenderingObservable.clear();
  20968. this.onBeforeSpritesRenderingObservable.clear();
  20969. this.onAfterSpritesRenderingObservable.clear();
  20970. this.onBeforeDrawPhaseObservable.clear();
  20971. this.onAfterDrawPhaseObservable.clear();
  20972. this.onBeforePhysicsObservable.clear();
  20973. this.onAfterPhysicsObservable.clear();
  20974. this.onBeforeAnimationsObservable.clear();
  20975. this.onAfterAnimationsObservable.clear();
  20976. this.onDataLoadedObservable.clear();
  20977. this.detachControl();
  20978. // Release sounds & sounds tracks
  20979. if (BABYLON.AudioEngine) {
  20980. this.disposeSounds();
  20981. }
  20982. // VR Helper
  20983. if (this.VRHelper) {
  20984. this.VRHelper.dispose();
  20985. }
  20986. // Detach cameras
  20987. var canvas = this._engine.getRenderingCanvas();
  20988. if (canvas) {
  20989. var index;
  20990. for (index = 0; index < this.cameras.length; index++) {
  20991. this.cameras[index].detachControl(canvas);
  20992. }
  20993. }
  20994. // Release lights
  20995. while (this.lights.length) {
  20996. this.lights[0].dispose();
  20997. }
  20998. // Release meshes
  20999. while (this.meshes.length) {
  21000. this.meshes[0].dispose(true);
  21001. }
  21002. while (this.transformNodes.length) {
  21003. this.removeTransformNode(this.transformNodes[0]);
  21004. }
  21005. // Release cameras
  21006. while (this.cameras.length) {
  21007. this.cameras[0].dispose();
  21008. }
  21009. // Release materials
  21010. if (this.defaultMaterial) {
  21011. this.defaultMaterial.dispose();
  21012. }
  21013. while (this.multiMaterials.length) {
  21014. this.multiMaterials[0].dispose();
  21015. }
  21016. while (this.materials.length) {
  21017. this.materials[0].dispose();
  21018. }
  21019. // Release particles
  21020. while (this.particleSystems.length) {
  21021. this.particleSystems[0].dispose();
  21022. }
  21023. // Release sprites
  21024. while (this.spriteManagers.length) {
  21025. this.spriteManagers[0].dispose();
  21026. }
  21027. // Release postProcesses
  21028. while (this.postProcesses.length) {
  21029. this.postProcesses[0].dispose();
  21030. }
  21031. // Release layers
  21032. while (this.layers.length) {
  21033. this.layers[0].dispose();
  21034. }
  21035. while (this.highlightLayers.length) {
  21036. this.highlightLayers[0].dispose();
  21037. }
  21038. // Release textures
  21039. while (this.textures.length) {
  21040. this.textures[0].dispose();
  21041. }
  21042. // Release UBO
  21043. this._sceneUbo.dispose();
  21044. if (this._alternateSceneUbo) {
  21045. this._alternateSceneUbo.dispose();
  21046. }
  21047. // Post-processes
  21048. this.postProcessManager.dispose();
  21049. if (this._postProcessRenderPipelineManager) {
  21050. this._postProcessRenderPipelineManager.dispose();
  21051. }
  21052. // Physics
  21053. if (this._physicsEngine) {
  21054. this.disablePhysicsEngine();
  21055. }
  21056. // Remove from engine
  21057. index = this._engine.scenes.indexOf(this);
  21058. if (index > -1) {
  21059. this._engine.scenes.splice(index, 1);
  21060. }
  21061. this._engine.wipeCaches();
  21062. this._isDisposed = true;
  21063. };
  21064. Object.defineProperty(Scene.prototype, "isDisposed", {
  21065. get: function () {
  21066. return this._isDisposed;
  21067. },
  21068. enumerable: true,
  21069. configurable: true
  21070. });
  21071. // Release sounds & sounds tracks
  21072. Scene.prototype.disposeSounds = function () {
  21073. if (!this._mainSoundTrack) {
  21074. return;
  21075. }
  21076. this.mainSoundTrack.dispose();
  21077. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  21078. this.soundTracks[scIndex].dispose();
  21079. }
  21080. };
  21081. // Octrees
  21082. Scene.prototype.getWorldExtends = function () {
  21083. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21084. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  21085. for (var index = 0; index < this.meshes.length; index++) {
  21086. var mesh = this.meshes[index];
  21087. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  21088. continue;
  21089. }
  21090. mesh.computeWorldMatrix(true);
  21091. var boundingInfo = mesh.getBoundingInfo();
  21092. var minBox = boundingInfo.boundingBox.minimumWorld;
  21093. var maxBox = boundingInfo.boundingBox.maximumWorld;
  21094. BABYLON.Tools.CheckExtends(minBox, min, max);
  21095. BABYLON.Tools.CheckExtends(maxBox, min, max);
  21096. }
  21097. return {
  21098. min: min,
  21099. max: max
  21100. };
  21101. };
  21102. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  21103. if (maxCapacity === void 0) { maxCapacity = 64; }
  21104. if (maxDepth === void 0) { maxDepth = 2; }
  21105. if (!this._selectionOctree) {
  21106. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  21107. }
  21108. var worldExtends = this.getWorldExtends();
  21109. // Update octree
  21110. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  21111. return this._selectionOctree;
  21112. };
  21113. // Picking
  21114. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  21115. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  21116. var result = BABYLON.Ray.Zero();
  21117. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  21118. return result;
  21119. };
  21120. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  21121. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  21122. var engine = this._engine;
  21123. if (!camera) {
  21124. if (!this.activeCamera)
  21125. throw new Error("Active camera not set");
  21126. camera = this.activeCamera;
  21127. }
  21128. var cameraViewport = camera.viewport;
  21129. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  21130. // Moving coordinates to local viewport world
  21131. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  21132. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  21133. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  21134. return this;
  21135. };
  21136. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  21137. var result = BABYLON.Ray.Zero();
  21138. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  21139. return result;
  21140. };
  21141. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  21142. if (!BABYLON.PickingInfo) {
  21143. return this;
  21144. }
  21145. var engine = this._engine;
  21146. if (!camera) {
  21147. if (!this.activeCamera)
  21148. throw new Error("Active camera not set");
  21149. camera = this.activeCamera;
  21150. }
  21151. var cameraViewport = camera.viewport;
  21152. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  21153. var identity = BABYLON.Matrix.Identity();
  21154. // Moving coordinates to local viewport world
  21155. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  21156. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  21157. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  21158. return this;
  21159. };
  21160. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  21161. if (!BABYLON.PickingInfo) {
  21162. return null;
  21163. }
  21164. var pickingInfo = null;
  21165. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  21166. var mesh = this.meshes[meshIndex];
  21167. if (predicate) {
  21168. if (!predicate(mesh)) {
  21169. continue;
  21170. }
  21171. }
  21172. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  21173. continue;
  21174. }
  21175. var world = mesh.getWorldMatrix();
  21176. var ray = rayFunction(world);
  21177. var result = mesh.intersects(ray, fastCheck);
  21178. if (!result || !result.hit)
  21179. continue;
  21180. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  21181. continue;
  21182. pickingInfo = result;
  21183. if (fastCheck) {
  21184. break;
  21185. }
  21186. }
  21187. return pickingInfo || new BABYLON.PickingInfo();
  21188. };
  21189. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  21190. if (!BABYLON.PickingInfo) {
  21191. return null;
  21192. }
  21193. var pickingInfos = new Array();
  21194. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  21195. var mesh = this.meshes[meshIndex];
  21196. if (predicate) {
  21197. if (!predicate(mesh)) {
  21198. continue;
  21199. }
  21200. }
  21201. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  21202. continue;
  21203. }
  21204. var world = mesh.getWorldMatrix();
  21205. var ray = rayFunction(world);
  21206. var result = mesh.intersects(ray, false);
  21207. if (!result || !result.hit)
  21208. continue;
  21209. pickingInfos.push(result);
  21210. }
  21211. return pickingInfos;
  21212. };
  21213. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  21214. if (!BABYLON.PickingInfo) {
  21215. return null;
  21216. }
  21217. var pickingInfo = null;
  21218. if (!camera) {
  21219. if (!this.activeCamera) {
  21220. return null;
  21221. }
  21222. camera = this.activeCamera;
  21223. }
  21224. if (this.spriteManagers.length > 0) {
  21225. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  21226. var spriteManager = this.spriteManagers[spriteIndex];
  21227. if (!spriteManager.isPickable) {
  21228. continue;
  21229. }
  21230. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  21231. if (!result || !result.hit)
  21232. continue;
  21233. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  21234. continue;
  21235. pickingInfo = result;
  21236. if (fastCheck) {
  21237. break;
  21238. }
  21239. }
  21240. }
  21241. return pickingInfo || new BABYLON.PickingInfo();
  21242. };
  21243. /** Launch a ray to try to pick a mesh in the scene
  21244. * @param x position on screen
  21245. * @param y position on screen
  21246. * @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
  21247. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  21248. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  21249. */
  21250. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  21251. var _this = this;
  21252. if (!BABYLON.PickingInfo) {
  21253. return null;
  21254. }
  21255. return this._internalPick(function (world) {
  21256. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  21257. return _this._tempPickingRay;
  21258. }, predicate, fastCheck);
  21259. };
  21260. /** Launch a ray to try to pick a sprite in the scene
  21261. * @param x position on screen
  21262. * @param y position on screen
  21263. * @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
  21264. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  21265. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  21266. */
  21267. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  21268. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  21269. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  21270. };
  21271. /** Use the given ray to pick a mesh in the scene
  21272. * @param ray The ray to use to pick meshes
  21273. * @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
  21274. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  21275. */
  21276. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  21277. var _this = this;
  21278. return this._internalPick(function (world) {
  21279. if (!_this._pickWithRayInverseMatrix) {
  21280. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  21281. }
  21282. world.invertToRef(_this._pickWithRayInverseMatrix);
  21283. if (!_this._cachedRayForTransform) {
  21284. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  21285. }
  21286. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  21287. return _this._cachedRayForTransform;
  21288. }, predicate, fastCheck);
  21289. };
  21290. /**
  21291. * Launch a ray to try to pick a mesh in the scene
  21292. * @param x X position on screen
  21293. * @param y Y position on screen
  21294. * @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
  21295. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  21296. */
  21297. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  21298. var _this = this;
  21299. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  21300. };
  21301. /**
  21302. * Launch a ray to try to pick a mesh in the scene
  21303. * @param ray Ray to use
  21304. * @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
  21305. */
  21306. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  21307. var _this = this;
  21308. return this._internalMultiPick(function (world) {
  21309. if (!_this._pickWithRayInverseMatrix) {
  21310. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  21311. }
  21312. world.invertToRef(_this._pickWithRayInverseMatrix);
  21313. if (!_this._cachedRayForTransform) {
  21314. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  21315. }
  21316. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  21317. return _this._cachedRayForTransform;
  21318. }, predicate);
  21319. };
  21320. Scene.prototype.setPointerOverMesh = function (mesh) {
  21321. if (this._pointerOverMesh === mesh) {
  21322. return;
  21323. }
  21324. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  21325. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  21326. }
  21327. this._pointerOverMesh = mesh;
  21328. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  21329. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  21330. }
  21331. };
  21332. Scene.prototype.getPointerOverMesh = function () {
  21333. return this._pointerOverMesh;
  21334. };
  21335. Scene.prototype.setPointerOverSprite = function (sprite) {
  21336. if (this._pointerOverSprite === sprite) {
  21337. return;
  21338. }
  21339. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  21340. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  21341. }
  21342. this._pointerOverSprite = sprite;
  21343. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  21344. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  21345. }
  21346. };
  21347. Scene.prototype.getPointerOverSprite = function () {
  21348. return this._pointerOverSprite;
  21349. };
  21350. // Physics
  21351. Scene.prototype.getPhysicsEngine = function () {
  21352. return this._physicsEngine;
  21353. };
  21354. /**
  21355. * Enables physics to the current scene
  21356. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  21357. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  21358. * @return {boolean} was the physics engine initialized
  21359. */
  21360. Scene.prototype.enablePhysics = function (gravity, plugin) {
  21361. if (gravity === void 0) { gravity = null; }
  21362. if (this._physicsEngine) {
  21363. return true;
  21364. }
  21365. try {
  21366. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  21367. return true;
  21368. }
  21369. catch (e) {
  21370. BABYLON.Tools.Error(e.message);
  21371. return false;
  21372. }
  21373. };
  21374. Scene.prototype.disablePhysicsEngine = function () {
  21375. if (!this._physicsEngine) {
  21376. return;
  21377. }
  21378. this._physicsEngine.dispose();
  21379. this._physicsEngine = null;
  21380. };
  21381. Scene.prototype.isPhysicsEnabled = function () {
  21382. return this._physicsEngine !== undefined;
  21383. };
  21384. Scene.prototype.deleteCompoundImpostor = function (compound) {
  21385. var mesh = compound.parts[0].mesh;
  21386. if (mesh.physicsImpostor) {
  21387. mesh.physicsImpostor.dispose();
  21388. mesh.physicsImpostor = null;
  21389. }
  21390. };
  21391. // Misc.
  21392. Scene.prototype._rebuildGeometries = function () {
  21393. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  21394. var geometry = _a[_i];
  21395. geometry._rebuild();
  21396. }
  21397. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  21398. var mesh = _c[_b];
  21399. mesh._rebuild();
  21400. }
  21401. if (this.postProcessManager) {
  21402. this.postProcessManager._rebuild();
  21403. }
  21404. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  21405. var layer = _e[_d];
  21406. layer._rebuild();
  21407. }
  21408. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  21409. var highlightLayer = _g[_f];
  21410. highlightLayer._rebuild();
  21411. }
  21412. if (this._boundingBoxRenderer) {
  21413. this._boundingBoxRenderer._rebuild();
  21414. }
  21415. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  21416. var system = _j[_h];
  21417. system.rebuild();
  21418. }
  21419. if (this._postProcessRenderPipelineManager) {
  21420. this._postProcessRenderPipelineManager._rebuild();
  21421. }
  21422. };
  21423. Scene.prototype._rebuildTextures = function () {
  21424. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  21425. var texture = _a[_i];
  21426. texture._rebuild();
  21427. }
  21428. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21429. };
  21430. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  21431. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  21432. if (replace === void 0) { replace = false; }
  21433. if (attachCameraControls === void 0) { attachCameraControls = false; }
  21434. // Dispose existing camera or light in replace mode.
  21435. if (replace) {
  21436. if (this.activeCamera) {
  21437. this.activeCamera.dispose();
  21438. this.activeCamera = null;
  21439. }
  21440. if (this.lights) {
  21441. for (var i = 0; i < this.lights.length; i++) {
  21442. this.lights[i].dispose();
  21443. }
  21444. }
  21445. }
  21446. // Light
  21447. if (this.lights.length === 0) {
  21448. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  21449. }
  21450. // Camera
  21451. if (!this.activeCamera) {
  21452. var worldExtends = this.getWorldExtends();
  21453. var worldSize = worldExtends.max.subtract(worldExtends.min);
  21454. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  21455. var camera;
  21456. var radius = worldSize.length() * 1.5;
  21457. if (createArcRotateCamera) {
  21458. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  21459. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  21460. arcRotateCamera.wheelPrecision = 100 / radius;
  21461. camera = arcRotateCamera;
  21462. }
  21463. else {
  21464. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  21465. freeCamera.setTarget(worldCenter);
  21466. camera = freeCamera;
  21467. }
  21468. camera.minZ = radius * 0.01;
  21469. camera.maxZ = radius * 100;
  21470. camera.speed = radius * 0.2;
  21471. this.activeCamera = camera;
  21472. var canvas = this.getEngine().getRenderingCanvas();
  21473. if (attachCameraControls && canvas) {
  21474. camera.attachControl(canvas);
  21475. }
  21476. }
  21477. };
  21478. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  21479. if (pbr === void 0) { pbr = false; }
  21480. if (scale === void 0) { scale = 1000; }
  21481. if (blur === void 0) { blur = 0; }
  21482. if (environmentTexture) {
  21483. this.environmentTexture = environmentTexture;
  21484. }
  21485. if (!this.environmentTexture) {
  21486. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  21487. return null;
  21488. }
  21489. // Skybox
  21490. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  21491. if (pbr) {
  21492. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  21493. hdrSkyboxMaterial.backFaceCulling = false;
  21494. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  21495. if (hdrSkyboxMaterial.reflectionTexture) {
  21496. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  21497. }
  21498. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  21499. hdrSkyboxMaterial.disableLighting = true;
  21500. hdrSkyboxMaterial.twoSidedLighting = true;
  21501. hdrSkybox.infiniteDistance = true;
  21502. hdrSkybox.material = hdrSkyboxMaterial;
  21503. }
  21504. else {
  21505. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  21506. skyboxMaterial.backFaceCulling = false;
  21507. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  21508. if (skyboxMaterial.reflectionTexture) {
  21509. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  21510. }
  21511. skyboxMaterial.disableLighting = true;
  21512. hdrSkybox.infiniteDistance = true;
  21513. hdrSkybox.material = skyboxMaterial;
  21514. }
  21515. return hdrSkybox;
  21516. };
  21517. Scene.prototype.createDefaultEnvironment = function (options) {
  21518. if (BABYLON.EnvironmentHelper) {
  21519. return new BABYLON.EnvironmentHelper(options, this);
  21520. }
  21521. return null;
  21522. };
  21523. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  21524. if (webVROptions === void 0) { webVROptions = {}; }
  21525. return new BABYLON.VRExperienceHelper(this, webVROptions);
  21526. };
  21527. // Tags
  21528. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  21529. if (tagsQuery === undefined) {
  21530. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  21531. return list;
  21532. }
  21533. var listByTags = [];
  21534. forEach = forEach || (function (item) { return; });
  21535. for (var i in list) {
  21536. var item = list[i];
  21537. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  21538. listByTags.push(item);
  21539. forEach(item);
  21540. }
  21541. }
  21542. return listByTags;
  21543. };
  21544. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  21545. return this._getByTags(this.meshes, tagsQuery, forEach);
  21546. };
  21547. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  21548. return this._getByTags(this.cameras, tagsQuery, forEach);
  21549. };
  21550. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  21551. return this._getByTags(this.lights, tagsQuery, forEach);
  21552. };
  21553. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  21554. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  21555. };
  21556. /**
  21557. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  21558. * This allowed control for front to back rendering or reversly depending of the special needs.
  21559. *
  21560. * @param renderingGroupId The rendering group id corresponding to its index
  21561. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  21562. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  21563. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  21564. */
  21565. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21566. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21567. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21568. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21569. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  21570. };
  21571. /**
  21572. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  21573. *
  21574. * @param renderingGroupId The rendering group id corresponding to its index
  21575. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  21576. * @param depth Automatically clears depth between groups if true and autoClear is true.
  21577. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  21578. */
  21579. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  21580. if (depth === void 0) { depth = true; }
  21581. if (stencil === void 0) { stencil = true; }
  21582. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  21583. };
  21584. /**
  21585. * Will flag all materials as dirty to trigger new shader compilation
  21586. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  21587. */
  21588. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  21589. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  21590. var material = _a[_i];
  21591. if (predicate && !predicate(material)) {
  21592. continue;
  21593. }
  21594. material.markAsDirty(flag);
  21595. }
  21596. };
  21597. // Statics
  21598. Scene._FOGMODE_NONE = 0;
  21599. Scene._FOGMODE_EXP = 1;
  21600. Scene._FOGMODE_EXP2 = 2;
  21601. Scene._FOGMODE_LINEAR = 3;
  21602. Scene._uniqueIdCounter = 0;
  21603. Scene.MinDeltaTime = 1.0;
  21604. Scene.MaxDeltaTime = 1000.0;
  21605. /** The distance in pixel that you have to move to prevent some events */
  21606. Scene.DragMovementThreshold = 10; // in pixels
  21607. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  21608. Scene.LongPressDelay = 500; // in milliseconds
  21609. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  21610. Scene.DoubleClickDelay = 300; // in milliseconds
  21611. /** If you need to check double click without raising a single click at first click, enable this flag */
  21612. Scene.ExclusiveDoubleClickMode = false;
  21613. return Scene;
  21614. }());
  21615. BABYLON.Scene = Scene;
  21616. })(BABYLON || (BABYLON = {}));
  21617. //# sourceMappingURL=babylon.scene.js.map
  21618. var BABYLON;
  21619. (function (BABYLON) {
  21620. var Buffer = /** @class */ (function () {
  21621. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  21622. if (instanced === void 0) { instanced = false; }
  21623. if (engine instanceof BABYLON.Mesh) {
  21624. this._engine = engine.getScene().getEngine();
  21625. }
  21626. else {
  21627. this._engine = engine;
  21628. }
  21629. this._updatable = updatable;
  21630. this._data = data;
  21631. this._strideSize = stride;
  21632. if (!postponeInternalCreation) {
  21633. this.create();
  21634. }
  21635. this._instanced = instanced;
  21636. this._instanceDivisor = instanced ? 1 : 0;
  21637. }
  21638. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  21639. // a lot of these parameters are ignored as they are overriden by the buffer
  21640. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  21641. };
  21642. // Properties
  21643. Buffer.prototype.isUpdatable = function () {
  21644. return this._updatable;
  21645. };
  21646. Buffer.prototype.getData = function () {
  21647. return this._data;
  21648. };
  21649. Buffer.prototype.getBuffer = function () {
  21650. return this._buffer;
  21651. };
  21652. Buffer.prototype.getStrideSize = function () {
  21653. return this._strideSize;
  21654. };
  21655. Buffer.prototype.getIsInstanced = function () {
  21656. return this._instanced;
  21657. };
  21658. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  21659. get: function () {
  21660. return this._instanceDivisor;
  21661. },
  21662. set: function (value) {
  21663. this._instanceDivisor = value;
  21664. if (value == 0) {
  21665. this._instanced = false;
  21666. }
  21667. else {
  21668. this._instanced = true;
  21669. }
  21670. },
  21671. enumerable: true,
  21672. configurable: true
  21673. });
  21674. // Methods
  21675. Buffer.prototype.create = function (data) {
  21676. if (data === void 0) { data = null; }
  21677. if (!data && this._buffer) {
  21678. return; // nothing to do
  21679. }
  21680. data = data || this._data;
  21681. if (!data) {
  21682. return;
  21683. }
  21684. if (!this._buffer) {
  21685. if (this._updatable) {
  21686. this._buffer = this._engine.createDynamicVertexBuffer(data);
  21687. this._data = data;
  21688. }
  21689. else {
  21690. this._buffer = this._engine.createVertexBuffer(data);
  21691. }
  21692. }
  21693. else if (this._updatable) {
  21694. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  21695. this._data = data;
  21696. }
  21697. };
  21698. Buffer.prototype._rebuild = function () {
  21699. this._buffer = null;
  21700. this.create(this._data);
  21701. };
  21702. Buffer.prototype.update = function (data) {
  21703. this.create(data);
  21704. };
  21705. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  21706. if (!this._buffer) {
  21707. return;
  21708. }
  21709. if (this._updatable) {
  21710. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  21711. this._data = null;
  21712. }
  21713. };
  21714. Buffer.prototype.dispose = function () {
  21715. if (!this._buffer) {
  21716. return;
  21717. }
  21718. if (this._engine._releaseBuffer(this._buffer)) {
  21719. this._buffer = null;
  21720. }
  21721. };
  21722. return Buffer;
  21723. }());
  21724. BABYLON.Buffer = Buffer;
  21725. })(BABYLON || (BABYLON = {}));
  21726. //# sourceMappingURL=babylon.buffer.js.map
  21727. var BABYLON;
  21728. (function (BABYLON) {
  21729. var VertexBuffer = /** @class */ (function () {
  21730. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  21731. if (!stride) {
  21732. // Deduce stride from kind
  21733. switch (kind) {
  21734. case VertexBuffer.PositionKind:
  21735. stride = 3;
  21736. break;
  21737. case VertexBuffer.NormalKind:
  21738. stride = 3;
  21739. break;
  21740. case VertexBuffer.UVKind:
  21741. case VertexBuffer.UV2Kind:
  21742. case VertexBuffer.UV3Kind:
  21743. case VertexBuffer.UV4Kind:
  21744. case VertexBuffer.UV5Kind:
  21745. case VertexBuffer.UV6Kind:
  21746. stride = 2;
  21747. break;
  21748. case VertexBuffer.TangentKind:
  21749. case VertexBuffer.ColorKind:
  21750. stride = 4;
  21751. break;
  21752. case VertexBuffer.MatricesIndicesKind:
  21753. case VertexBuffer.MatricesIndicesExtraKind:
  21754. stride = 4;
  21755. break;
  21756. case VertexBuffer.MatricesWeightsKind:
  21757. case VertexBuffer.MatricesWeightsExtraKind:
  21758. default:
  21759. stride = 4;
  21760. break;
  21761. }
  21762. }
  21763. if (data instanceof BABYLON.Buffer) {
  21764. if (!stride) {
  21765. stride = data.getStrideSize();
  21766. }
  21767. this._buffer = data;
  21768. this._ownsBuffer = false;
  21769. }
  21770. else {
  21771. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  21772. this._ownsBuffer = true;
  21773. }
  21774. this._stride = stride;
  21775. this._offset = offset ? offset : 0;
  21776. this._size = size ? size : stride;
  21777. this._kind = kind;
  21778. }
  21779. VertexBuffer.prototype._rebuild = function () {
  21780. if (!this._buffer) {
  21781. return;
  21782. }
  21783. this._buffer._rebuild();
  21784. };
  21785. /**
  21786. * Returns the kind of the VertexBuffer (string).
  21787. */
  21788. VertexBuffer.prototype.getKind = function () {
  21789. return this._kind;
  21790. };
  21791. // Properties
  21792. /**
  21793. * Boolean : is the VertexBuffer updatable ?
  21794. */
  21795. VertexBuffer.prototype.isUpdatable = function () {
  21796. return this._buffer.isUpdatable();
  21797. };
  21798. /**
  21799. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  21800. */
  21801. VertexBuffer.prototype.getData = function () {
  21802. return this._buffer.getData();
  21803. };
  21804. /**
  21805. * Returns the WebGLBuffer associated to the VertexBuffer.
  21806. */
  21807. VertexBuffer.prototype.getBuffer = function () {
  21808. return this._buffer.getBuffer();
  21809. };
  21810. /**
  21811. * Returns the stride of the VertexBuffer (integer).
  21812. */
  21813. VertexBuffer.prototype.getStrideSize = function () {
  21814. return this._stride;
  21815. };
  21816. /**
  21817. * Returns the offset (integer).
  21818. */
  21819. VertexBuffer.prototype.getOffset = function () {
  21820. return this._offset;
  21821. };
  21822. /**
  21823. * Returns the VertexBuffer total size (integer).
  21824. */
  21825. VertexBuffer.prototype.getSize = function () {
  21826. return this._size;
  21827. };
  21828. /**
  21829. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  21830. */
  21831. VertexBuffer.prototype.getIsInstanced = function () {
  21832. return this._buffer.getIsInstanced();
  21833. };
  21834. /**
  21835. * Returns the instancing divisor, zero for non-instanced (integer).
  21836. */
  21837. VertexBuffer.prototype.getInstanceDivisor = function () {
  21838. return this._buffer.instanceDivisor;
  21839. };
  21840. // Methods
  21841. /**
  21842. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  21843. * Returns the created WebGLBuffer.
  21844. */
  21845. VertexBuffer.prototype.create = function (data) {
  21846. return this._buffer.create(data);
  21847. };
  21848. /**
  21849. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  21850. * Returns the updated WebGLBuffer.
  21851. */
  21852. VertexBuffer.prototype.update = function (data) {
  21853. return this._buffer.update(data);
  21854. };
  21855. /**
  21856. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  21857. * Returns the directly updated WebGLBuffer.
  21858. */
  21859. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  21860. return this._buffer.updateDirectly(data, offset);
  21861. };
  21862. /**
  21863. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  21864. */
  21865. VertexBuffer.prototype.dispose = function () {
  21866. if (this._ownsBuffer) {
  21867. this._buffer.dispose();
  21868. }
  21869. };
  21870. Object.defineProperty(VertexBuffer, "PositionKind", {
  21871. get: function () {
  21872. return VertexBuffer._PositionKind;
  21873. },
  21874. enumerable: true,
  21875. configurable: true
  21876. });
  21877. Object.defineProperty(VertexBuffer, "NormalKind", {
  21878. get: function () {
  21879. return VertexBuffer._NormalKind;
  21880. },
  21881. enumerable: true,
  21882. configurable: true
  21883. });
  21884. Object.defineProperty(VertexBuffer, "TangentKind", {
  21885. get: function () {
  21886. return VertexBuffer._TangentKind;
  21887. },
  21888. enumerable: true,
  21889. configurable: true
  21890. });
  21891. Object.defineProperty(VertexBuffer, "UVKind", {
  21892. get: function () {
  21893. return VertexBuffer._UVKind;
  21894. },
  21895. enumerable: true,
  21896. configurable: true
  21897. });
  21898. Object.defineProperty(VertexBuffer, "UV2Kind", {
  21899. get: function () {
  21900. return VertexBuffer._UV2Kind;
  21901. },
  21902. enumerable: true,
  21903. configurable: true
  21904. });
  21905. Object.defineProperty(VertexBuffer, "UV3Kind", {
  21906. get: function () {
  21907. return VertexBuffer._UV3Kind;
  21908. },
  21909. enumerable: true,
  21910. configurable: true
  21911. });
  21912. Object.defineProperty(VertexBuffer, "UV4Kind", {
  21913. get: function () {
  21914. return VertexBuffer._UV4Kind;
  21915. },
  21916. enumerable: true,
  21917. configurable: true
  21918. });
  21919. Object.defineProperty(VertexBuffer, "UV5Kind", {
  21920. get: function () {
  21921. return VertexBuffer._UV5Kind;
  21922. },
  21923. enumerable: true,
  21924. configurable: true
  21925. });
  21926. Object.defineProperty(VertexBuffer, "UV6Kind", {
  21927. get: function () {
  21928. return VertexBuffer._UV6Kind;
  21929. },
  21930. enumerable: true,
  21931. configurable: true
  21932. });
  21933. Object.defineProperty(VertexBuffer, "ColorKind", {
  21934. get: function () {
  21935. return VertexBuffer._ColorKind;
  21936. },
  21937. enumerable: true,
  21938. configurable: true
  21939. });
  21940. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  21941. get: function () {
  21942. return VertexBuffer._MatricesIndicesKind;
  21943. },
  21944. enumerable: true,
  21945. configurable: true
  21946. });
  21947. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  21948. get: function () {
  21949. return VertexBuffer._MatricesWeightsKind;
  21950. },
  21951. enumerable: true,
  21952. configurable: true
  21953. });
  21954. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  21955. get: function () {
  21956. return VertexBuffer._MatricesIndicesExtraKind;
  21957. },
  21958. enumerable: true,
  21959. configurable: true
  21960. });
  21961. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  21962. get: function () {
  21963. return VertexBuffer._MatricesWeightsExtraKind;
  21964. },
  21965. enumerable: true,
  21966. configurable: true
  21967. });
  21968. // Enums
  21969. VertexBuffer._PositionKind = "position";
  21970. VertexBuffer._NormalKind = "normal";
  21971. VertexBuffer._TangentKind = "tangent";
  21972. VertexBuffer._UVKind = "uv";
  21973. VertexBuffer._UV2Kind = "uv2";
  21974. VertexBuffer._UV3Kind = "uv3";
  21975. VertexBuffer._UV4Kind = "uv4";
  21976. VertexBuffer._UV5Kind = "uv5";
  21977. VertexBuffer._UV6Kind = "uv6";
  21978. VertexBuffer._ColorKind = "color";
  21979. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  21980. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  21981. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  21982. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  21983. return VertexBuffer;
  21984. }());
  21985. BABYLON.VertexBuffer = VertexBuffer;
  21986. })(BABYLON || (BABYLON = {}));
  21987. //# sourceMappingURL=babylon.vertexBuffer.js.map
  21988. var BABYLON;
  21989. (function (BABYLON) {
  21990. var InternalTexture = /** @class */ (function () {
  21991. function InternalTexture(engine, dataSource) {
  21992. this.onLoadedObservable = new BABYLON.Observable();
  21993. // Private
  21994. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  21995. this._references = 1;
  21996. this._engine = engine;
  21997. this._dataSource = dataSource;
  21998. this._webGLTexture = engine._createTexture();
  21999. }
  22000. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  22001. get: function () {
  22002. return this._dataSource;
  22003. },
  22004. enumerable: true,
  22005. configurable: true
  22006. });
  22007. InternalTexture.prototype.incrementReferences = function () {
  22008. this._references++;
  22009. };
  22010. InternalTexture.prototype.updateSize = function (width, height, depth) {
  22011. if (depth === void 0) { depth = 1; }
  22012. this.width = width;
  22013. this.height = height;
  22014. this.depth = depth;
  22015. this.baseWidth = width;
  22016. this.baseHeight = height;
  22017. this.baseDepth = depth;
  22018. this._size = width * height * depth;
  22019. };
  22020. InternalTexture.prototype._rebuild = function () {
  22021. var _this = this;
  22022. var proxy;
  22023. this.isReady = false;
  22024. this._cachedCoordinatesMode = null;
  22025. this._cachedWrapU = null;
  22026. this._cachedWrapV = null;
  22027. this._cachedAnisotropicFilteringLevel = null;
  22028. switch (this._dataSource) {
  22029. case InternalTexture.DATASOURCE_TEMP:
  22030. return;
  22031. case InternalTexture.DATASOURCE_URL:
  22032. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  22033. _this.isReady = true;
  22034. }, null, this._buffer, undefined, this.format);
  22035. proxy._swapAndDie(this);
  22036. return;
  22037. case InternalTexture.DATASOURCE_RAW:
  22038. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression, this.type);
  22039. proxy._swapAndDie(this);
  22040. this.isReady = true;
  22041. return;
  22042. case InternalTexture.DATASOURCE_RAW3D:
  22043. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  22044. proxy._swapAndDie(this);
  22045. this.isReady = true;
  22046. return;
  22047. case InternalTexture.DATASOURCE_DYNAMIC:
  22048. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  22049. proxy._swapAndDie(this);
  22050. // The engine will make sure to update content so no need to flag it as isReady = true
  22051. return;
  22052. case InternalTexture.DATASOURCE_RENDERTARGET:
  22053. var options = new BABYLON.RenderTargetCreationOptions();
  22054. options.generateDepthBuffer = this._generateDepthBuffer;
  22055. options.generateMipMaps = this.generateMipMaps;
  22056. options.generateStencilBuffer = this._generateStencilBuffer;
  22057. options.samplingMode = this.samplingMode;
  22058. options.type = this.type;
  22059. if (this.isCube) {
  22060. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  22061. }
  22062. else {
  22063. var size = {
  22064. width: this.width,
  22065. height: this.height
  22066. };
  22067. proxy = this._engine.createRenderTargetTexture(size, options);
  22068. }
  22069. proxy._swapAndDie(this);
  22070. this.isReady = true;
  22071. return;
  22072. case InternalTexture.DATASOURCE_CUBE:
  22073. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  22074. _this.isReady = true;
  22075. }, null, this.format, this._extension);
  22076. proxy._swapAndDie(this);
  22077. return;
  22078. case InternalTexture.DATASOURCE_CUBERAW:
  22079. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  22080. proxy._swapAndDie(this);
  22081. this.isReady = true;
  22082. return;
  22083. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  22084. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  22085. if (proxy) {
  22086. proxy._swapAndDie(_this);
  22087. }
  22088. _this.isReady = true;
  22089. }, null, this.format, this._extension);
  22090. return;
  22091. }
  22092. };
  22093. InternalTexture.prototype._swapAndDie = function (target) {
  22094. target._webGLTexture = this._webGLTexture;
  22095. if (this._framebuffer) {
  22096. target._framebuffer = this._framebuffer;
  22097. }
  22098. if (this._depthStencilBuffer) {
  22099. target._depthStencilBuffer = this._depthStencilBuffer;
  22100. }
  22101. if (this._lodTextureHigh) {
  22102. if (target._lodTextureHigh) {
  22103. target._lodTextureHigh.dispose();
  22104. }
  22105. target._lodTextureHigh = this._lodTextureHigh;
  22106. }
  22107. if (this._lodTextureMid) {
  22108. if (target._lodTextureMid) {
  22109. target._lodTextureMid.dispose();
  22110. }
  22111. target._lodTextureMid = this._lodTextureMid;
  22112. }
  22113. if (this._lodTextureLow) {
  22114. if (target._lodTextureLow) {
  22115. target._lodTextureLow.dispose();
  22116. }
  22117. target._lodTextureLow = this._lodTextureLow;
  22118. }
  22119. var cache = this._engine.getLoadedTexturesCache();
  22120. var index = cache.indexOf(this);
  22121. if (index !== -1) {
  22122. cache.splice(index, 1);
  22123. }
  22124. };
  22125. InternalTexture.prototype.dispose = function () {
  22126. if (!this._webGLTexture) {
  22127. return;
  22128. }
  22129. this._references--;
  22130. if (this._references === 0) {
  22131. this._engine._releaseTexture(this);
  22132. this._webGLTexture = null;
  22133. }
  22134. };
  22135. InternalTexture.DATASOURCE_UNKNOWN = 0;
  22136. InternalTexture.DATASOURCE_URL = 1;
  22137. InternalTexture.DATASOURCE_TEMP = 2;
  22138. InternalTexture.DATASOURCE_RAW = 3;
  22139. InternalTexture.DATASOURCE_DYNAMIC = 4;
  22140. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  22141. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  22142. InternalTexture.DATASOURCE_CUBE = 7;
  22143. InternalTexture.DATASOURCE_CUBERAW = 8;
  22144. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  22145. InternalTexture.DATASOURCE_RAW3D = 10;
  22146. return InternalTexture;
  22147. }());
  22148. BABYLON.InternalTexture = InternalTexture;
  22149. })(BABYLON || (BABYLON = {}));
  22150. //# sourceMappingURL=babylon.internalTexture.js.map
  22151. var BABYLON;
  22152. (function (BABYLON) {
  22153. var BaseTexture = /** @class */ (function () {
  22154. function BaseTexture(scene) {
  22155. this._hasAlpha = false;
  22156. this.getAlphaFromRGB = false;
  22157. this.level = 1;
  22158. this.coordinatesIndex = 0;
  22159. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  22160. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  22161. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  22162. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  22163. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  22164. this.isCube = false;
  22165. this.is3D = false;
  22166. this.gammaSpace = true;
  22167. this.invertZ = false;
  22168. this.lodLevelInAlpha = false;
  22169. this.lodGenerationOffset = 0.0;
  22170. this.lodGenerationScale = 0.8;
  22171. this.isRenderTarget = false;
  22172. this.animations = new Array();
  22173. /**
  22174. * An event triggered when the texture is disposed.
  22175. * @type {BABYLON.Observable}
  22176. */
  22177. this.onDisposeObservable = new BABYLON.Observable();
  22178. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22179. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  22180. if (this._scene) {
  22181. this._scene.textures.push(this);
  22182. }
  22183. this._uid = null;
  22184. }
  22185. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  22186. get: function () {
  22187. return this._hasAlpha;
  22188. },
  22189. set: function (value) {
  22190. if (this._hasAlpha === value) {
  22191. return;
  22192. }
  22193. this._hasAlpha = value;
  22194. if (this._scene) {
  22195. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22196. }
  22197. },
  22198. enumerable: true,
  22199. configurable: true
  22200. });
  22201. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  22202. get: function () {
  22203. return this._coordinatesMode;
  22204. },
  22205. set: function (value) {
  22206. if (this._coordinatesMode === value) {
  22207. return;
  22208. }
  22209. this._coordinatesMode = value;
  22210. if (this._scene) {
  22211. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22212. }
  22213. },
  22214. enumerable: true,
  22215. configurable: true
  22216. });
  22217. Object.defineProperty(BaseTexture.prototype, "uid", {
  22218. get: function () {
  22219. if (!this._uid) {
  22220. this._uid = BABYLON.Tools.RandomId();
  22221. }
  22222. return this._uid;
  22223. },
  22224. enumerable: true,
  22225. configurable: true
  22226. });
  22227. BaseTexture.prototype.toString = function () {
  22228. return this.name;
  22229. };
  22230. BaseTexture.prototype.getClassName = function () {
  22231. return "BaseTexture";
  22232. };
  22233. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  22234. set: function (callback) {
  22235. if (this._onDisposeObserver) {
  22236. this.onDisposeObservable.remove(this._onDisposeObserver);
  22237. }
  22238. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22239. },
  22240. enumerable: true,
  22241. configurable: true
  22242. });
  22243. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  22244. get: function () {
  22245. return true;
  22246. },
  22247. enumerable: true,
  22248. configurable: true
  22249. });
  22250. BaseTexture.prototype.getScene = function () {
  22251. return this._scene;
  22252. };
  22253. BaseTexture.prototype.getTextureMatrix = function () {
  22254. return BABYLON.Matrix.IdentityReadOnly;
  22255. };
  22256. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  22257. return BABYLON.Matrix.IdentityReadOnly;
  22258. };
  22259. BaseTexture.prototype.getInternalTexture = function () {
  22260. return this._texture;
  22261. };
  22262. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  22263. return !this.isBlocking || this.isReady();
  22264. };
  22265. BaseTexture.prototype.isReady = function () {
  22266. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22267. this.delayLoad();
  22268. return false;
  22269. }
  22270. if (this._texture) {
  22271. return this._texture.isReady;
  22272. }
  22273. return false;
  22274. };
  22275. BaseTexture.prototype.getSize = function () {
  22276. if (this._texture && this._texture.width) {
  22277. return new BABYLON.Size(this._texture.width, this._texture.height);
  22278. }
  22279. if (this._texture && this._texture._size) {
  22280. return new BABYLON.Size(this._texture._size, this._texture._size);
  22281. }
  22282. return BABYLON.Size.Zero();
  22283. };
  22284. BaseTexture.prototype.getBaseSize = function () {
  22285. if (!this.isReady() || !this._texture)
  22286. return BABYLON.Size.Zero();
  22287. if (this._texture._size) {
  22288. return new BABYLON.Size(this._texture._size, this._texture._size);
  22289. }
  22290. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  22291. };
  22292. BaseTexture.prototype.scale = function (ratio) {
  22293. };
  22294. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  22295. get: function () {
  22296. return false;
  22297. },
  22298. enumerable: true,
  22299. configurable: true
  22300. });
  22301. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  22302. if (!this._scene) {
  22303. return null;
  22304. }
  22305. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  22306. for (var index = 0; index < texturesCache.length; index++) {
  22307. var texturesCacheEntry = texturesCache[index];
  22308. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  22309. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  22310. texturesCacheEntry.incrementReferences();
  22311. return texturesCacheEntry;
  22312. }
  22313. }
  22314. }
  22315. return null;
  22316. };
  22317. BaseTexture.prototype._rebuild = function () {
  22318. };
  22319. BaseTexture.prototype.delayLoad = function () {
  22320. };
  22321. BaseTexture.prototype.clone = function () {
  22322. return null;
  22323. };
  22324. Object.defineProperty(BaseTexture.prototype, "textureType", {
  22325. get: function () {
  22326. if (!this._texture) {
  22327. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  22328. }
  22329. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  22330. },
  22331. enumerable: true,
  22332. configurable: true
  22333. });
  22334. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  22335. get: function () {
  22336. if (!this._texture) {
  22337. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  22338. }
  22339. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  22340. },
  22341. enumerable: true,
  22342. configurable: true
  22343. });
  22344. BaseTexture.prototype.readPixels = function (faceIndex) {
  22345. if (faceIndex === void 0) { faceIndex = 0; }
  22346. if (!this._texture) {
  22347. return null;
  22348. }
  22349. var size = this.getSize();
  22350. var scene = this.getScene();
  22351. if (!scene) {
  22352. return null;
  22353. }
  22354. var engine = scene.getEngine();
  22355. if (this._texture.isCube) {
  22356. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  22357. }
  22358. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  22359. };
  22360. BaseTexture.prototype.releaseInternalTexture = function () {
  22361. if (this._texture) {
  22362. this._texture.dispose();
  22363. this._texture = null;
  22364. }
  22365. };
  22366. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  22367. get: function () {
  22368. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  22369. return null;
  22370. }
  22371. if (!this._texture._sphericalPolynomial) {
  22372. this._texture._sphericalPolynomial =
  22373. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  22374. }
  22375. return this._texture._sphericalPolynomial;
  22376. },
  22377. set: function (value) {
  22378. if (this._texture) {
  22379. this._texture._sphericalPolynomial = value;
  22380. }
  22381. },
  22382. enumerable: true,
  22383. configurable: true
  22384. });
  22385. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  22386. get: function () {
  22387. if (this._texture) {
  22388. return this._texture._lodTextureHigh;
  22389. }
  22390. return null;
  22391. },
  22392. enumerable: true,
  22393. configurable: true
  22394. });
  22395. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  22396. get: function () {
  22397. if (this._texture) {
  22398. return this._texture._lodTextureMid;
  22399. }
  22400. return null;
  22401. },
  22402. enumerable: true,
  22403. configurable: true
  22404. });
  22405. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  22406. get: function () {
  22407. if (this._texture) {
  22408. return this._texture._lodTextureLow;
  22409. }
  22410. return null;
  22411. },
  22412. enumerable: true,
  22413. configurable: true
  22414. });
  22415. BaseTexture.prototype.dispose = function () {
  22416. if (!this._scene) {
  22417. return;
  22418. }
  22419. // Animations
  22420. this._scene.stopAnimation(this);
  22421. // Remove from scene
  22422. this._scene._removePendingData(this);
  22423. var index = this._scene.textures.indexOf(this);
  22424. if (index >= 0) {
  22425. this._scene.textures.splice(index, 1);
  22426. }
  22427. if (this._texture === undefined) {
  22428. return;
  22429. }
  22430. // Release
  22431. this.releaseInternalTexture();
  22432. // Callback
  22433. this.onDisposeObservable.notifyObservers(this);
  22434. this.onDisposeObservable.clear();
  22435. };
  22436. BaseTexture.prototype.serialize = function () {
  22437. if (!this.name) {
  22438. return null;
  22439. }
  22440. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22441. // Animations
  22442. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22443. return serializationObject;
  22444. };
  22445. BaseTexture.WhenAllReady = function (textures, callback) {
  22446. var numRemaining = textures.length;
  22447. if (numRemaining === 0) {
  22448. callback();
  22449. return;
  22450. }
  22451. var _loop_1 = function () {
  22452. texture = textures[i];
  22453. if (texture.isReady()) {
  22454. if (--numRemaining === 0) {
  22455. callback();
  22456. }
  22457. }
  22458. else {
  22459. onLoadObservable = texture.onLoadObservable;
  22460. var onLoadCallback_1 = function () {
  22461. onLoadObservable.removeCallback(onLoadCallback_1);
  22462. if (--numRemaining === 0) {
  22463. callback();
  22464. }
  22465. };
  22466. onLoadObservable.add(onLoadCallback_1);
  22467. }
  22468. };
  22469. var texture, onLoadObservable;
  22470. for (var i = 0; i < textures.length; i++) {
  22471. _loop_1();
  22472. }
  22473. };
  22474. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  22475. __decorate([
  22476. BABYLON.serialize()
  22477. ], BaseTexture.prototype, "name", void 0);
  22478. __decorate([
  22479. BABYLON.serialize("hasAlpha")
  22480. ], BaseTexture.prototype, "_hasAlpha", void 0);
  22481. __decorate([
  22482. BABYLON.serialize()
  22483. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  22484. __decorate([
  22485. BABYLON.serialize()
  22486. ], BaseTexture.prototype, "level", void 0);
  22487. __decorate([
  22488. BABYLON.serialize()
  22489. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  22490. __decorate([
  22491. BABYLON.serialize("coordinatesMode")
  22492. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  22493. __decorate([
  22494. BABYLON.serialize()
  22495. ], BaseTexture.prototype, "wrapU", void 0);
  22496. __decorate([
  22497. BABYLON.serialize()
  22498. ], BaseTexture.prototype, "wrapV", void 0);
  22499. __decorate([
  22500. BABYLON.serialize()
  22501. ], BaseTexture.prototype, "wrapR", void 0);
  22502. __decorate([
  22503. BABYLON.serialize()
  22504. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  22505. __decorate([
  22506. BABYLON.serialize()
  22507. ], BaseTexture.prototype, "isCube", void 0);
  22508. __decorate([
  22509. BABYLON.serialize()
  22510. ], BaseTexture.prototype, "is3D", void 0);
  22511. __decorate([
  22512. BABYLON.serialize()
  22513. ], BaseTexture.prototype, "gammaSpace", void 0);
  22514. __decorate([
  22515. BABYLON.serialize()
  22516. ], BaseTexture.prototype, "invertZ", void 0);
  22517. __decorate([
  22518. BABYLON.serialize()
  22519. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  22520. __decorate([
  22521. BABYLON.serialize()
  22522. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  22523. __decorate([
  22524. BABYLON.serialize()
  22525. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  22526. __decorate([
  22527. BABYLON.serialize()
  22528. ], BaseTexture.prototype, "isRenderTarget", void 0);
  22529. return BaseTexture;
  22530. }());
  22531. BABYLON.BaseTexture = BaseTexture;
  22532. })(BABYLON || (BABYLON = {}));
  22533. //# sourceMappingURL=babylon.baseTexture.js.map
  22534. var BABYLON;
  22535. (function (BABYLON) {
  22536. var Texture = /** @class */ (function (_super) {
  22537. __extends(Texture, _super);
  22538. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  22539. if (noMipmap === void 0) { noMipmap = false; }
  22540. if (invertY === void 0) { invertY = true; }
  22541. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22542. if (onLoad === void 0) { onLoad = null; }
  22543. if (onError === void 0) { onError = null; }
  22544. if (buffer === void 0) { buffer = null; }
  22545. if (deleteBuffer === void 0) { deleteBuffer = false; }
  22546. var _this = _super.call(this, scene) || this;
  22547. _this.uOffset = 0;
  22548. _this.vOffset = 0;
  22549. _this.uScale = 1.0;
  22550. _this.vScale = 1.0;
  22551. _this.uAng = 0;
  22552. _this.vAng = 0;
  22553. _this.wAng = 0;
  22554. _this._isBlocking = true;
  22555. _this.name = url || "";
  22556. _this.url = url;
  22557. _this._noMipmap = noMipmap;
  22558. _this._invertY = invertY;
  22559. _this._samplingMode = samplingMode;
  22560. _this._buffer = buffer;
  22561. _this._deleteBuffer = deleteBuffer;
  22562. if (format) {
  22563. _this._format = format;
  22564. }
  22565. scene = _this.getScene();
  22566. if (!scene) {
  22567. return _this;
  22568. }
  22569. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  22570. var load = function () {
  22571. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  22572. _this.onLoadObservable.notifyObservers(_this);
  22573. }
  22574. if (onLoad) {
  22575. onLoad();
  22576. }
  22577. if (!_this.isBlocking && scene) {
  22578. scene.resetCachedMaterial();
  22579. }
  22580. };
  22581. if (!_this.url) {
  22582. _this._delayedOnLoad = load;
  22583. _this._delayedOnError = onError;
  22584. return _this;
  22585. }
  22586. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  22587. if (!_this._texture) {
  22588. if (!scene.useDelayedTextureLoading) {
  22589. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  22590. if (deleteBuffer) {
  22591. delete _this._buffer;
  22592. }
  22593. }
  22594. else {
  22595. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22596. _this._delayedOnLoad = load;
  22597. _this._delayedOnError = onError;
  22598. }
  22599. }
  22600. else {
  22601. if (_this._texture.isReady) {
  22602. BABYLON.Tools.SetImmediate(function () { return load(); });
  22603. }
  22604. else {
  22605. _this._texture.onLoadedObservable.add(load);
  22606. }
  22607. }
  22608. return _this;
  22609. }
  22610. Object.defineProperty(Texture.prototype, "noMipmap", {
  22611. get: function () {
  22612. return this._noMipmap;
  22613. },
  22614. enumerable: true,
  22615. configurable: true
  22616. });
  22617. Object.defineProperty(Texture.prototype, "isBlocking", {
  22618. get: function () {
  22619. return this._isBlocking;
  22620. },
  22621. set: function (value) {
  22622. this._isBlocking = value;
  22623. },
  22624. enumerable: true,
  22625. configurable: true
  22626. });
  22627. Object.defineProperty(Texture.prototype, "samplingMode", {
  22628. get: function () {
  22629. return this._samplingMode;
  22630. },
  22631. enumerable: true,
  22632. configurable: true
  22633. });
  22634. Texture.prototype.updateURL = function (url) {
  22635. this.url = url;
  22636. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22637. this.delayLoad();
  22638. };
  22639. Texture.prototype.delayLoad = function () {
  22640. var _this = this;
  22641. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22642. return;
  22643. }
  22644. var scene = this.getScene();
  22645. if (!scene) {
  22646. return;
  22647. }
  22648. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22649. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  22650. if (!this._texture) {
  22651. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  22652. if (this._deleteBuffer) {
  22653. delete this._buffer;
  22654. }
  22655. }
  22656. else {
  22657. if (this._texture.isReady) {
  22658. BABYLON.Tools.SetImmediate(function () {
  22659. if (!_this._delayedOnLoad) {
  22660. return;
  22661. }
  22662. _this._delayedOnLoad();
  22663. });
  22664. }
  22665. else {
  22666. if (this._delayedOnLoad) {
  22667. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  22668. }
  22669. }
  22670. }
  22671. };
  22672. Texture.prototype.updateSamplingMode = function (samplingMode) {
  22673. if (!this._texture) {
  22674. return;
  22675. }
  22676. var scene = this.getScene();
  22677. if (!scene) {
  22678. return;
  22679. }
  22680. this._samplingMode = samplingMode;
  22681. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  22682. };
  22683. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  22684. x *= this.uScale;
  22685. y *= this.vScale;
  22686. x -= 0.5 * this.uScale;
  22687. y -= 0.5 * this.vScale;
  22688. z -= 0.5;
  22689. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  22690. t.x += 0.5 * this.uScale + this.uOffset;
  22691. t.y += 0.5 * this.vScale + this.vOffset;
  22692. t.z += 0.5;
  22693. };
  22694. Texture.prototype.getTextureMatrix = function () {
  22695. var _this = this;
  22696. if (this.uOffset === this._cachedUOffset &&
  22697. this.vOffset === this._cachedVOffset &&
  22698. this.uScale === this._cachedUScale &&
  22699. this.vScale === this._cachedVScale &&
  22700. this.uAng === this._cachedUAng &&
  22701. this.vAng === this._cachedVAng &&
  22702. this.wAng === this._cachedWAng) {
  22703. return this._cachedTextureMatrix;
  22704. }
  22705. this._cachedUOffset = this.uOffset;
  22706. this._cachedVOffset = this.vOffset;
  22707. this._cachedUScale = this.uScale;
  22708. this._cachedVScale = this.vScale;
  22709. this._cachedUAng = this.uAng;
  22710. this._cachedVAng = this.vAng;
  22711. this._cachedWAng = this.wAng;
  22712. if (!this._cachedTextureMatrix) {
  22713. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22714. this._rowGenerationMatrix = new BABYLON.Matrix();
  22715. this._t0 = BABYLON.Vector3.Zero();
  22716. this._t1 = BABYLON.Vector3.Zero();
  22717. this._t2 = BABYLON.Vector3.Zero();
  22718. }
  22719. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  22720. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  22721. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  22722. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  22723. this._t1.subtractInPlace(this._t0);
  22724. this._t2.subtractInPlace(this._t0);
  22725. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22726. this._cachedTextureMatrix.m[0] = this._t1.x;
  22727. this._cachedTextureMatrix.m[1] = this._t1.y;
  22728. this._cachedTextureMatrix.m[2] = this._t1.z;
  22729. this._cachedTextureMatrix.m[4] = this._t2.x;
  22730. this._cachedTextureMatrix.m[5] = this._t2.y;
  22731. this._cachedTextureMatrix.m[6] = this._t2.z;
  22732. this._cachedTextureMatrix.m[8] = this._t0.x;
  22733. this._cachedTextureMatrix.m[9] = this._t0.y;
  22734. this._cachedTextureMatrix.m[10] = this._t0.z;
  22735. var scene = this.getScene();
  22736. if (!scene) {
  22737. return this._cachedTextureMatrix;
  22738. }
  22739. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  22740. return mat.hasTexture(_this);
  22741. });
  22742. return this._cachedTextureMatrix;
  22743. };
  22744. Texture.prototype.getReflectionTextureMatrix = function () {
  22745. var _this = this;
  22746. var scene = this.getScene();
  22747. if (!scene) {
  22748. return this._cachedTextureMatrix;
  22749. }
  22750. if (this.uOffset === this._cachedUOffset &&
  22751. this.vOffset === this._cachedVOffset &&
  22752. this.uScale === this._cachedUScale &&
  22753. this.vScale === this._cachedVScale &&
  22754. this.coordinatesMode === this._cachedCoordinatesMode) {
  22755. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  22756. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  22757. return this._cachedTextureMatrix;
  22758. }
  22759. }
  22760. else {
  22761. return this._cachedTextureMatrix;
  22762. }
  22763. }
  22764. if (!this._cachedTextureMatrix) {
  22765. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22766. }
  22767. if (!this._projectionModeMatrix) {
  22768. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  22769. }
  22770. this._cachedUOffset = this.uOffset;
  22771. this._cachedVOffset = this.vOffset;
  22772. this._cachedUScale = this.uScale;
  22773. this._cachedVScale = this.vScale;
  22774. this._cachedCoordinatesMode = this.coordinatesMode;
  22775. switch (this.coordinatesMode) {
  22776. case Texture.PLANAR_MODE:
  22777. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22778. this._cachedTextureMatrix[0] = this.uScale;
  22779. this._cachedTextureMatrix[5] = this.vScale;
  22780. this._cachedTextureMatrix[12] = this.uOffset;
  22781. this._cachedTextureMatrix[13] = this.vOffset;
  22782. break;
  22783. case Texture.PROJECTION_MODE:
  22784. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  22785. this._projectionModeMatrix.m[0] = 0.5;
  22786. this._projectionModeMatrix.m[5] = -0.5;
  22787. this._projectionModeMatrix.m[10] = 0.0;
  22788. this._projectionModeMatrix.m[12] = 0.5;
  22789. this._projectionModeMatrix.m[13] = 0.5;
  22790. this._projectionModeMatrix.m[14] = 1.0;
  22791. this._projectionModeMatrix.m[15] = 1.0;
  22792. var projectionMatrix = scene.getProjectionMatrix();
  22793. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  22794. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  22795. break;
  22796. default:
  22797. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22798. break;
  22799. }
  22800. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  22801. return (mat.getActiveTextures().indexOf(_this) !== -1);
  22802. });
  22803. return this._cachedTextureMatrix;
  22804. };
  22805. Texture.prototype.clone = function () {
  22806. var _this = this;
  22807. return BABYLON.SerializationHelper.Clone(function () {
  22808. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  22809. }, this);
  22810. };
  22811. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  22812. get: function () {
  22813. if (!this._onLoadObservable) {
  22814. this._onLoadObservable = new BABYLON.Observable();
  22815. }
  22816. return this._onLoadObservable;
  22817. },
  22818. enumerable: true,
  22819. configurable: true
  22820. });
  22821. Texture.prototype.serialize = function () {
  22822. var serializationObject = _super.prototype.serialize.call(this);
  22823. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  22824. serializationObject.base64String = this._buffer;
  22825. serializationObject.name = serializationObject.name.replace("data:", "");
  22826. }
  22827. return serializationObject;
  22828. };
  22829. Texture.prototype.getClassName = function () {
  22830. return "Texture";
  22831. };
  22832. Texture.prototype.dispose = function () {
  22833. _super.prototype.dispose.call(this);
  22834. if (this.onLoadObservable) {
  22835. this.onLoadObservable.clear();
  22836. this._onLoadObservable = null;
  22837. }
  22838. this._delayedOnLoad = null;
  22839. this._delayedOnError = null;
  22840. };
  22841. // Statics
  22842. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  22843. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22844. if (onLoad === void 0) { onLoad = null; }
  22845. if (onError === void 0) { onError = null; }
  22846. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  22847. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  22848. };
  22849. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  22850. if (parsedTexture.customType) {
  22851. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  22852. // Update Sampling Mode
  22853. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  22854. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  22855. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  22856. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  22857. }
  22858. }
  22859. return parsedCustomTexture;
  22860. }
  22861. if (parsedTexture.isCube) {
  22862. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  22863. }
  22864. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  22865. return null;
  22866. }
  22867. var texture = BABYLON.SerializationHelper.Parse(function () {
  22868. var generateMipMaps = true;
  22869. if (parsedTexture.noMipmap) {
  22870. generateMipMaps = false;
  22871. }
  22872. if (parsedTexture.mirrorPlane) {
  22873. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  22874. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  22875. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  22876. return mirrorTexture;
  22877. }
  22878. else if (parsedTexture.isRenderTarget) {
  22879. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  22880. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  22881. return renderTargetTexture;
  22882. }
  22883. else {
  22884. var texture;
  22885. if (parsedTexture.base64String) {
  22886. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  22887. }
  22888. else {
  22889. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  22890. }
  22891. return texture;
  22892. }
  22893. }, parsedTexture, scene);
  22894. // Update Sampling Mode
  22895. if (parsedTexture.samplingMode) {
  22896. var sampling = parsedTexture.samplingMode;
  22897. if (texture._samplingMode !== sampling) {
  22898. texture.updateSamplingMode(sampling);
  22899. }
  22900. }
  22901. // Animations
  22902. if (parsedTexture.animations) {
  22903. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  22904. var parsedAnimation = parsedTexture.animations[animationIndex];
  22905. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22906. }
  22907. }
  22908. return texture;
  22909. };
  22910. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  22911. if (deleteBuffer === void 0) { deleteBuffer = false; }
  22912. if (noMipmap === void 0) { noMipmap = false; }
  22913. if (invertY === void 0) { invertY = true; }
  22914. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22915. if (onLoad === void 0) { onLoad = null; }
  22916. if (onError === void 0) { onError = null; }
  22917. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  22918. if (name.substr(0, 5) !== "data:") {
  22919. name = "data:" + name;
  22920. }
  22921. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  22922. };
  22923. // Constants
  22924. Texture.NEAREST_SAMPLINGMODE = 1;
  22925. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  22926. Texture.BILINEAR_SAMPLINGMODE = 2;
  22927. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  22928. Texture.TRILINEAR_SAMPLINGMODE = 3;
  22929. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  22930. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  22931. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  22932. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  22933. Texture.NEAREST_LINEAR = 7;
  22934. Texture.NEAREST_NEAREST = 8;
  22935. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  22936. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  22937. Texture.LINEAR_LINEAR = 11;
  22938. Texture.LINEAR_NEAREST = 12;
  22939. Texture.EXPLICIT_MODE = 0;
  22940. Texture.SPHERICAL_MODE = 1;
  22941. Texture.PLANAR_MODE = 2;
  22942. Texture.CUBIC_MODE = 3;
  22943. Texture.PROJECTION_MODE = 4;
  22944. Texture.SKYBOX_MODE = 5;
  22945. Texture.INVCUBIC_MODE = 6;
  22946. Texture.EQUIRECTANGULAR_MODE = 7;
  22947. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  22948. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  22949. Texture.CLAMP_ADDRESSMODE = 0;
  22950. Texture.WRAP_ADDRESSMODE = 1;
  22951. Texture.MIRROR_ADDRESSMODE = 2;
  22952. __decorate([
  22953. BABYLON.serialize()
  22954. ], Texture.prototype, "url", void 0);
  22955. __decorate([
  22956. BABYLON.serialize()
  22957. ], Texture.prototype, "uOffset", void 0);
  22958. __decorate([
  22959. BABYLON.serialize()
  22960. ], Texture.prototype, "vOffset", void 0);
  22961. __decorate([
  22962. BABYLON.serialize()
  22963. ], Texture.prototype, "uScale", void 0);
  22964. __decorate([
  22965. BABYLON.serialize()
  22966. ], Texture.prototype, "vScale", void 0);
  22967. __decorate([
  22968. BABYLON.serialize()
  22969. ], Texture.prototype, "uAng", void 0);
  22970. __decorate([
  22971. BABYLON.serialize()
  22972. ], Texture.prototype, "vAng", void 0);
  22973. __decorate([
  22974. BABYLON.serialize()
  22975. ], Texture.prototype, "wAng", void 0);
  22976. __decorate([
  22977. BABYLON.serialize()
  22978. ], Texture.prototype, "isBlocking", null);
  22979. return Texture;
  22980. }(BABYLON.BaseTexture));
  22981. BABYLON.Texture = Texture;
  22982. })(BABYLON || (BABYLON = {}));
  22983. //# sourceMappingURL=babylon.texture.js.map
  22984. var BABYLON;
  22985. (function (BABYLON) {
  22986. var _InstancesBatch = /** @class */ (function () {
  22987. function _InstancesBatch() {
  22988. this.mustReturn = false;
  22989. this.visibleInstances = new Array();
  22990. this.renderSelf = new Array();
  22991. }
  22992. return _InstancesBatch;
  22993. }());
  22994. BABYLON._InstancesBatch = _InstancesBatch;
  22995. var Mesh = /** @class */ (function (_super) {
  22996. __extends(Mesh, _super);
  22997. /**
  22998. * @constructor
  22999. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  23000. * @param {Scene} scene The scene to add this mesh to.
  23001. * @param {Node} parent The parent of this mesh, if it has one
  23002. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  23003. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  23004. * When false, achieved by calling a clone(), also passing False.
  23005. * This will make creation of children, recursive.
  23006. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  23007. */
  23008. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  23009. if (scene === void 0) { scene = null; }
  23010. if (parent === void 0) { parent = null; }
  23011. if (source === void 0) { source = null; }
  23012. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  23013. var _this = _super.call(this, name, scene) || this;
  23014. // Events
  23015. /**
  23016. * An event triggered before rendering the mesh
  23017. * @type {BABYLON.Observable}
  23018. */
  23019. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23020. /**
  23021. * An event triggered after rendering the mesh
  23022. * @type {BABYLON.Observable}
  23023. */
  23024. _this.onAfterRenderObservable = new BABYLON.Observable();
  23025. /**
  23026. * An event triggered before drawing the mesh
  23027. * @type {BABYLON.Observable}
  23028. */
  23029. _this.onBeforeDrawObservable = new BABYLON.Observable();
  23030. // Members
  23031. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23032. _this.instances = new Array();
  23033. _this._LODLevels = new Array();
  23034. _this._visibleInstances = {};
  23035. _this._renderIdForInstances = new Array();
  23036. _this._batchCache = new _InstancesBatch();
  23037. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  23038. // Use by builder only to know what orientation were the mesh build in.
  23039. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  23040. _this.overrideMaterialSideOrientation = null;
  23041. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  23042. // Will be used to save a source mesh reference, If any
  23043. _this._source = null;
  23044. scene = _this.getScene();
  23045. if (source) {
  23046. // Source mesh
  23047. _this._source = source;
  23048. // Geometry
  23049. if (source._geometry) {
  23050. source._geometry.applyToMesh(_this);
  23051. }
  23052. // Deep copy
  23053. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source"], ["_poseMatrix", "_source"]);
  23054. // Tags
  23055. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  23056. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  23057. }
  23058. _this.metadata = source.metadata;
  23059. // Parent
  23060. _this.parent = source.parent;
  23061. // Pivot
  23062. _this.setPivotMatrix(source.getPivotMatrix());
  23063. _this.id = name + "." + source.id;
  23064. // Material
  23065. _this.material = source.material;
  23066. var index;
  23067. if (!doNotCloneChildren) {
  23068. // Children
  23069. var directDescendants = source.getDescendants(true);
  23070. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  23071. var child = directDescendants[index_1];
  23072. if (child.clone) {
  23073. child.clone(name + "." + child.name, _this);
  23074. }
  23075. }
  23076. }
  23077. // Physics clone
  23078. var physicsEngine = _this.getScene().getPhysicsEngine();
  23079. if (clonePhysicsImpostor && physicsEngine) {
  23080. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  23081. if (impostor) {
  23082. _this.physicsImpostor = impostor.clone(_this);
  23083. }
  23084. }
  23085. // Particles
  23086. for (index = 0; index < scene.particleSystems.length; index++) {
  23087. var system = scene.particleSystems[index];
  23088. if (system.emitter === source) {
  23089. system.clone(system.name, _this);
  23090. }
  23091. }
  23092. _this.computeWorldMatrix(true);
  23093. }
  23094. // Parent
  23095. if (parent !== null) {
  23096. _this.parent = parent;
  23097. }
  23098. return _this;
  23099. }
  23100. Object.defineProperty(Mesh, "FRONTSIDE", {
  23101. /**
  23102. * Mesh side orientation : usually the external or front surface
  23103. */
  23104. get: function () {
  23105. return Mesh._FRONTSIDE;
  23106. },
  23107. enumerable: true,
  23108. configurable: true
  23109. });
  23110. Object.defineProperty(Mesh, "BACKSIDE", {
  23111. /**
  23112. * Mesh side orientation : usually the internal or back surface
  23113. */
  23114. get: function () {
  23115. return Mesh._BACKSIDE;
  23116. },
  23117. enumerable: true,
  23118. configurable: true
  23119. });
  23120. Object.defineProperty(Mesh, "DOUBLESIDE", {
  23121. /**
  23122. * Mesh side orientation : both internal and external or front and back surfaces
  23123. */
  23124. get: function () {
  23125. return Mesh._DOUBLESIDE;
  23126. },
  23127. enumerable: true,
  23128. configurable: true
  23129. });
  23130. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  23131. /**
  23132. * Mesh side orientation : by default, `FRONTSIDE`
  23133. */
  23134. get: function () {
  23135. return Mesh._DEFAULTSIDE;
  23136. },
  23137. enumerable: true,
  23138. configurable: true
  23139. });
  23140. Object.defineProperty(Mesh, "NO_CAP", {
  23141. /**
  23142. * Mesh cap setting : no cap
  23143. */
  23144. get: function () {
  23145. return Mesh._NO_CAP;
  23146. },
  23147. enumerable: true,
  23148. configurable: true
  23149. });
  23150. Object.defineProperty(Mesh, "CAP_START", {
  23151. /**
  23152. * Mesh cap setting : one cap at the beginning of the mesh
  23153. */
  23154. get: function () {
  23155. return Mesh._CAP_START;
  23156. },
  23157. enumerable: true,
  23158. configurable: true
  23159. });
  23160. Object.defineProperty(Mesh, "CAP_END", {
  23161. /**
  23162. * Mesh cap setting : one cap at the end of the mesh
  23163. */
  23164. get: function () {
  23165. return Mesh._CAP_END;
  23166. },
  23167. enumerable: true,
  23168. configurable: true
  23169. });
  23170. Object.defineProperty(Mesh, "CAP_ALL", {
  23171. /**
  23172. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  23173. */
  23174. get: function () {
  23175. return Mesh._CAP_ALL;
  23176. },
  23177. enumerable: true,
  23178. configurable: true
  23179. });
  23180. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  23181. set: function (callback) {
  23182. if (this._onBeforeDrawObserver) {
  23183. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  23184. }
  23185. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  23186. },
  23187. enumerable: true,
  23188. configurable: true
  23189. });
  23190. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  23191. get: function () {
  23192. return this._morphTargetManager;
  23193. },
  23194. set: function (value) {
  23195. if (this._morphTargetManager === value) {
  23196. return;
  23197. }
  23198. this._morphTargetManager = value;
  23199. this._syncGeometryWithMorphTargetManager();
  23200. },
  23201. enumerable: true,
  23202. configurable: true
  23203. });
  23204. Object.defineProperty(Mesh.prototype, "source", {
  23205. get: function () {
  23206. return this._source;
  23207. },
  23208. enumerable: true,
  23209. configurable: true
  23210. });
  23211. // Methods
  23212. /**
  23213. * Returns the string "Mesh".
  23214. */
  23215. Mesh.prototype.getClassName = function () {
  23216. return "Mesh";
  23217. };
  23218. /**
  23219. * Returns a string.
  23220. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  23221. */
  23222. Mesh.prototype.toString = function (fullDetails) {
  23223. var ret = _super.prototype.toString.call(this, fullDetails);
  23224. ret += ", n vertices: " + this.getTotalVertices();
  23225. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  23226. if (this.animations) {
  23227. for (var i = 0; i < this.animations.length; i++) {
  23228. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  23229. }
  23230. }
  23231. if (fullDetails) {
  23232. if (this._geometry) {
  23233. var ib = this.getIndices();
  23234. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23235. if (vb && ib) {
  23236. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  23237. }
  23238. }
  23239. else {
  23240. ret += ", flat shading: UNKNOWN";
  23241. }
  23242. }
  23243. return ret;
  23244. };
  23245. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  23246. /**
  23247. * True if the mesh has some Levels Of Details (LOD).
  23248. * Returns a boolean.
  23249. */
  23250. get: function () {
  23251. return this._LODLevels.length > 0;
  23252. },
  23253. enumerable: true,
  23254. configurable: true
  23255. });
  23256. Mesh.prototype._sortLODLevels = function () {
  23257. this._LODLevels.sort(function (a, b) {
  23258. if (a.distance < b.distance) {
  23259. return 1;
  23260. }
  23261. if (a.distance > b.distance) {
  23262. return -1;
  23263. }
  23264. return 0;
  23265. });
  23266. };
  23267. /**
  23268. * Add a mesh as LOD level triggered at the given distance.
  23269. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23270. * @param {number} distance The distance from the center of the object to show this level
  23271. * @param {Mesh} mesh The mesh to be added as LOD level
  23272. * @return {Mesh} This mesh (for chaining)
  23273. */
  23274. Mesh.prototype.addLODLevel = function (distance, mesh) {
  23275. if (mesh && mesh._masterMesh) {
  23276. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  23277. return this;
  23278. }
  23279. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  23280. this._LODLevels.push(level);
  23281. if (mesh) {
  23282. mesh._masterMesh = this;
  23283. }
  23284. this._sortLODLevels();
  23285. return this;
  23286. };
  23287. /**
  23288. * Returns the LOD level mesh at the passed distance or null if not found.
  23289. * It is related to the method `addLODLevel(distance, mesh)`.
  23290. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23291. * Returns an object Mesh or `null`.
  23292. */
  23293. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  23294. for (var index = 0; index < this._LODLevels.length; index++) {
  23295. var level = this._LODLevels[index];
  23296. if (level.distance === distance) {
  23297. return level.mesh;
  23298. }
  23299. }
  23300. return null;
  23301. };
  23302. /**
  23303. * Remove a mesh from the LOD array
  23304. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23305. * @param {Mesh} mesh The mesh to be removed.
  23306. * @return {Mesh} This mesh (for chaining)
  23307. */
  23308. Mesh.prototype.removeLODLevel = function (mesh) {
  23309. for (var index = 0; index < this._LODLevels.length; index++) {
  23310. if (this._LODLevels[index].mesh === mesh) {
  23311. this._LODLevels.splice(index, 1);
  23312. if (mesh) {
  23313. mesh._masterMesh = null;
  23314. }
  23315. }
  23316. }
  23317. this._sortLODLevels();
  23318. return this;
  23319. };
  23320. /**
  23321. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  23322. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23323. */
  23324. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  23325. if (!this._LODLevels || this._LODLevels.length === 0) {
  23326. return this;
  23327. }
  23328. var bSphere;
  23329. if (boundingSphere) {
  23330. bSphere = boundingSphere;
  23331. }
  23332. else {
  23333. var boundingInfo = this.getBoundingInfo();
  23334. bSphere = boundingInfo.boundingSphere;
  23335. }
  23336. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  23337. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  23338. if (this.onLODLevelSelection) {
  23339. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  23340. }
  23341. return this;
  23342. }
  23343. for (var index = 0; index < this._LODLevels.length; index++) {
  23344. var level = this._LODLevels[index];
  23345. if (level.distance < distanceToCamera) {
  23346. if (level.mesh) {
  23347. level.mesh._preActivate();
  23348. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  23349. }
  23350. if (this.onLODLevelSelection) {
  23351. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  23352. }
  23353. return level.mesh;
  23354. }
  23355. }
  23356. if (this.onLODLevelSelection) {
  23357. this.onLODLevelSelection(distanceToCamera, this, this);
  23358. }
  23359. return this;
  23360. };
  23361. Object.defineProperty(Mesh.prototype, "geometry", {
  23362. /**
  23363. * Returns the mesh internal Geometry object.
  23364. */
  23365. get: function () {
  23366. return this._geometry;
  23367. },
  23368. enumerable: true,
  23369. configurable: true
  23370. });
  23371. /**
  23372. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  23373. */
  23374. Mesh.prototype.getTotalVertices = function () {
  23375. if (!this._geometry) {
  23376. return 0;
  23377. }
  23378. return this._geometry.getTotalVertices();
  23379. };
  23380. /**
  23381. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  23382. * 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.
  23383. * You can force the copy with forceCopy === true
  23384. * Returns null if the mesh has no geometry or no vertex buffer.
  23385. * Possible `kind` values :
  23386. * - BABYLON.VertexBuffer.PositionKind
  23387. * - BABYLON.VertexBuffer.UVKind
  23388. * - BABYLON.VertexBuffer.UV2Kind
  23389. * - BABYLON.VertexBuffer.UV3Kind
  23390. * - BABYLON.VertexBuffer.UV4Kind
  23391. * - BABYLON.VertexBuffer.UV5Kind
  23392. * - BABYLON.VertexBuffer.UV6Kind
  23393. * - BABYLON.VertexBuffer.ColorKind
  23394. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23395. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23396. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23397. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23398. */
  23399. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  23400. if (!this._geometry) {
  23401. return null;
  23402. }
  23403. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  23404. };
  23405. /**
  23406. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  23407. * Returns `null` if the mesh has no geometry.
  23408. * Possible `kind` values :
  23409. * - BABYLON.VertexBuffer.PositionKind
  23410. * - BABYLON.VertexBuffer.UVKind
  23411. * - BABYLON.VertexBuffer.UV2Kind
  23412. * - BABYLON.VertexBuffer.UV3Kind
  23413. * - BABYLON.VertexBuffer.UV4Kind
  23414. * - BABYLON.VertexBuffer.UV5Kind
  23415. * - BABYLON.VertexBuffer.UV6Kind
  23416. * - BABYLON.VertexBuffer.ColorKind
  23417. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23418. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23419. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23420. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23421. */
  23422. Mesh.prototype.getVertexBuffer = function (kind) {
  23423. if (!this._geometry) {
  23424. return null;
  23425. }
  23426. return this._geometry.getVertexBuffer(kind);
  23427. };
  23428. /**
  23429. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  23430. * Possible `kind` values :
  23431. * - BABYLON.VertexBuffer.PositionKind
  23432. * - BABYLON.VertexBuffer.UVKind
  23433. * - BABYLON.VertexBuffer.UV2Kind
  23434. * - BABYLON.VertexBuffer.UV3Kind
  23435. * - BABYLON.VertexBuffer.UV4Kind
  23436. * - BABYLON.VertexBuffer.UV5Kind
  23437. * - BABYLON.VertexBuffer.UV6Kind
  23438. * - BABYLON.VertexBuffer.ColorKind
  23439. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23440. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23441. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23442. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23443. */
  23444. Mesh.prototype.isVerticesDataPresent = function (kind) {
  23445. if (!this._geometry) {
  23446. if (this._delayInfo) {
  23447. return this._delayInfo.indexOf(kind) !== -1;
  23448. }
  23449. return false;
  23450. }
  23451. return this._geometry.isVerticesDataPresent(kind);
  23452. };
  23453. /**
  23454. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  23455. * Possible `kind` values :
  23456. * - BABYLON.VertexBuffer.PositionKind
  23457. * - BABYLON.VertexBuffer.UVKind
  23458. * - BABYLON.VertexBuffer.UV2Kind
  23459. * - BABYLON.VertexBuffer.UV3Kind
  23460. * - BABYLON.VertexBuffer.UV4Kind
  23461. * - BABYLON.VertexBuffer.UV5Kind
  23462. * - BABYLON.VertexBuffer.UV6Kind
  23463. * - BABYLON.VertexBuffer.ColorKind
  23464. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23465. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23466. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23467. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23468. */
  23469. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  23470. if (!this._geometry) {
  23471. if (this._delayInfo) {
  23472. return this._delayInfo.indexOf(kind) !== -1;
  23473. }
  23474. return false;
  23475. }
  23476. return this._geometry.isVertexBufferUpdatable(kind);
  23477. };
  23478. /**
  23479. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  23480. * Possible `kind` values :
  23481. * - BABYLON.VertexBuffer.PositionKind
  23482. * - BABYLON.VertexBuffer.UVKind
  23483. * - BABYLON.VertexBuffer.UV2Kind
  23484. * - BABYLON.VertexBuffer.UV3Kind
  23485. * - BABYLON.VertexBuffer.UV4Kind
  23486. * - BABYLON.VertexBuffer.UV5Kind
  23487. * - BABYLON.VertexBuffer.UV6Kind
  23488. * - BABYLON.VertexBuffer.ColorKind
  23489. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23490. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23491. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23492. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23493. */
  23494. Mesh.prototype.getVerticesDataKinds = function () {
  23495. if (!this._geometry) {
  23496. var result = new Array();
  23497. if (this._delayInfo) {
  23498. this._delayInfo.forEach(function (kind, index, array) {
  23499. result.push(kind);
  23500. });
  23501. }
  23502. return result;
  23503. }
  23504. return this._geometry.getVerticesDataKinds();
  23505. };
  23506. /**
  23507. * Returns a positive integer : the total number of indices in this mesh geometry.
  23508. * Returns zero if the mesh has no geometry.
  23509. */
  23510. Mesh.prototype.getTotalIndices = function () {
  23511. if (!this._geometry) {
  23512. return 0;
  23513. }
  23514. return this._geometry.getTotalIndices();
  23515. };
  23516. /**
  23517. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  23518. * 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.
  23519. * Returns an empty array if the mesh has no geometry.
  23520. */
  23521. Mesh.prototype.getIndices = function (copyWhenShared) {
  23522. if (!this._geometry) {
  23523. return [];
  23524. }
  23525. return this._geometry.getIndices(copyWhenShared);
  23526. };
  23527. Object.defineProperty(Mesh.prototype, "isBlocked", {
  23528. get: function () {
  23529. return this._masterMesh !== null && this._masterMesh !== undefined;
  23530. },
  23531. enumerable: true,
  23532. configurable: true
  23533. });
  23534. /**
  23535. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  23536. */
  23537. Mesh.prototype.isReady = function () {
  23538. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23539. return false;
  23540. }
  23541. return _super.prototype.isReady.call(this);
  23542. };
  23543. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  23544. /**
  23545. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  23546. * This property is pertinent only for updatable parametric shapes.
  23547. */
  23548. get: function () {
  23549. return this._areNormalsFrozen;
  23550. },
  23551. enumerable: true,
  23552. configurable: true
  23553. });
  23554. /**
  23555. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  23556. * It has no effect at all on other shapes.
  23557. * It prevents the mesh normals from being recomputed on next `positions` array update.
  23558. * Returns the Mesh.
  23559. */
  23560. Mesh.prototype.freezeNormals = function () {
  23561. this._areNormalsFrozen = true;
  23562. return this;
  23563. };
  23564. /**
  23565. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  23566. * It has no effect at all on other shapes.
  23567. * It reactivates the mesh normals computation if it was previously frozen.
  23568. * Returns the Mesh.
  23569. */
  23570. Mesh.prototype.unfreezeNormals = function () {
  23571. this._areNormalsFrozen = false;
  23572. return this;
  23573. };
  23574. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  23575. /**
  23576. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  23577. */
  23578. set: function (count) {
  23579. this._overridenInstanceCount = count;
  23580. },
  23581. enumerable: true,
  23582. configurable: true
  23583. });
  23584. // Methods
  23585. Mesh.prototype._preActivate = function () {
  23586. var sceneRenderId = this.getScene().getRenderId();
  23587. if (this._preActivateId === sceneRenderId) {
  23588. return this;
  23589. }
  23590. this._preActivateId = sceneRenderId;
  23591. this._visibleInstances = null;
  23592. return this;
  23593. };
  23594. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  23595. if (this._visibleInstances) {
  23596. this._visibleInstances.intermediateDefaultRenderId = renderId;
  23597. }
  23598. return this;
  23599. };
  23600. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  23601. if (!this._visibleInstances) {
  23602. this._visibleInstances = {};
  23603. this._visibleInstances.defaultRenderId = renderId;
  23604. this._visibleInstances.selfDefaultRenderId = this._renderId;
  23605. }
  23606. if (!this._visibleInstances[renderId]) {
  23607. this._visibleInstances[renderId] = new Array();
  23608. }
  23609. this._visibleInstances[renderId].push(instance);
  23610. return this;
  23611. };
  23612. /**
  23613. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  23614. * This means the mesh underlying bounding box and sphere are recomputed.
  23615. * Returns the Mesh.
  23616. */
  23617. Mesh.prototype.refreshBoundingInfo = function () {
  23618. return this._refreshBoundingInfo(false);
  23619. };
  23620. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  23621. if (this._boundingInfo && this._boundingInfo.isLocked) {
  23622. return this;
  23623. }
  23624. var data = this._getPositionData(applySkeleton);
  23625. if (data) {
  23626. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  23627. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23628. }
  23629. if (this.subMeshes) {
  23630. for (var index = 0; index < this.subMeshes.length; index++) {
  23631. this.subMeshes[index].refreshBoundingInfo();
  23632. }
  23633. }
  23634. this._updateBoundingInfo();
  23635. return this;
  23636. };
  23637. Mesh.prototype._getPositionData = function (applySkeleton) {
  23638. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23639. if (data && applySkeleton && this.skeleton) {
  23640. data = data.slice();
  23641. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  23642. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  23643. if (matricesWeightsData && matricesIndicesData) {
  23644. var needExtras = this.numBoneInfluencers > 4;
  23645. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  23646. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  23647. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  23648. var tempVector = BABYLON.Tmp.Vector3[0];
  23649. var finalMatrix = BABYLON.Tmp.Matrix[0];
  23650. var tempMatrix = BABYLON.Tmp.Matrix[1];
  23651. var matWeightIdx = 0;
  23652. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  23653. finalMatrix.reset();
  23654. var inf;
  23655. var weight;
  23656. for (inf = 0; inf < 4; inf++) {
  23657. weight = matricesWeightsData[matWeightIdx + inf];
  23658. if (weight <= 0)
  23659. break;
  23660. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23661. finalMatrix.addToSelf(tempMatrix);
  23662. }
  23663. if (needExtras) {
  23664. for (inf = 0; inf < 4; inf++) {
  23665. weight = matricesWeightsExtraData[matWeightIdx + inf];
  23666. if (weight <= 0)
  23667. break;
  23668. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23669. finalMatrix.addToSelf(tempMatrix);
  23670. }
  23671. }
  23672. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  23673. tempVector.toArray(data, index);
  23674. }
  23675. }
  23676. }
  23677. return data;
  23678. };
  23679. Mesh.prototype._createGlobalSubMesh = function (force) {
  23680. var totalVertices = this.getTotalVertices();
  23681. if (!totalVertices || !this.getIndices()) {
  23682. return null;
  23683. }
  23684. // Check if we need to recreate the submeshes
  23685. if (this.subMeshes && this.subMeshes.length > 0) {
  23686. var ib = this.getIndices();
  23687. if (!ib) {
  23688. return null;
  23689. }
  23690. var totalIndices = ib.length;
  23691. var needToRecreate = false;
  23692. if (force) {
  23693. needToRecreate = true;
  23694. }
  23695. else {
  23696. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  23697. var submesh = _a[_i];
  23698. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  23699. needToRecreate = true;
  23700. break;
  23701. }
  23702. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  23703. needToRecreate = true;
  23704. break;
  23705. }
  23706. }
  23707. }
  23708. if (!needToRecreate) {
  23709. return this.subMeshes[0];
  23710. }
  23711. }
  23712. this.releaseSubMeshes();
  23713. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  23714. };
  23715. Mesh.prototype.subdivide = function (count) {
  23716. if (count < 1) {
  23717. return;
  23718. }
  23719. var totalIndices = this.getTotalIndices();
  23720. var subdivisionSize = (totalIndices / count) | 0;
  23721. var offset = 0;
  23722. // Ensure that subdivisionSize is a multiple of 3
  23723. while (subdivisionSize % 3 !== 0) {
  23724. subdivisionSize++;
  23725. }
  23726. this.releaseSubMeshes();
  23727. for (var index = 0; index < count; index++) {
  23728. if (offset >= totalIndices) {
  23729. break;
  23730. }
  23731. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  23732. offset += subdivisionSize;
  23733. }
  23734. this.synchronizeInstances();
  23735. };
  23736. /**
  23737. * Sets the vertex data of the mesh geometry for the requested `kind`.
  23738. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  23739. * The `data` are either a numeric array either a Float32Array.
  23740. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  23741. * 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).
  23742. * Note that a new underlying VertexBuffer object is created each call.
  23743. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  23744. *
  23745. * Possible `kind` values :
  23746. * - BABYLON.VertexBuffer.PositionKind
  23747. * - BABYLON.VertexBuffer.UVKind
  23748. * - BABYLON.VertexBuffer.UV2Kind
  23749. * - BABYLON.VertexBuffer.UV3Kind
  23750. * - BABYLON.VertexBuffer.UV4Kind
  23751. * - BABYLON.VertexBuffer.UV5Kind
  23752. * - BABYLON.VertexBuffer.UV6Kind
  23753. * - BABYLON.VertexBuffer.ColorKind
  23754. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23755. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23756. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23757. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23758. *
  23759. * Returns the Mesh.
  23760. */
  23761. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  23762. if (updatable === void 0) { updatable = false; }
  23763. if (!this._geometry) {
  23764. var vertexData = new BABYLON.VertexData();
  23765. vertexData.set(data, kind);
  23766. var scene = this.getScene();
  23767. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  23768. }
  23769. else {
  23770. this._geometry.setVerticesData(kind, data, updatable, stride);
  23771. }
  23772. return this;
  23773. };
  23774. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  23775. if (updatable === void 0) { updatable = true; }
  23776. var vb = this.getVertexBuffer(kind);
  23777. if (!vb || vb.isUpdatable() === updatable) {
  23778. return;
  23779. }
  23780. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  23781. };
  23782. /**
  23783. * Sets the mesh VertexBuffer.
  23784. * Returns the Mesh.
  23785. */
  23786. Mesh.prototype.setVerticesBuffer = function (buffer) {
  23787. if (!this._geometry) {
  23788. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  23789. }
  23790. this._geometry.setVerticesBuffer(buffer);
  23791. return this;
  23792. };
  23793. /**
  23794. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  23795. * If the mesh has no geometry, it is simply returned as it is.
  23796. * The `data` are either a numeric array either a Float32Array.
  23797. * No new underlying VertexBuffer object is created.
  23798. * 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.
  23799. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  23800. *
  23801. * Possible `kind` values :
  23802. * - BABYLON.VertexBuffer.PositionKind
  23803. * - BABYLON.VertexBuffer.UVKind
  23804. * - BABYLON.VertexBuffer.UV2Kind
  23805. * - BABYLON.VertexBuffer.UV3Kind
  23806. * - BABYLON.VertexBuffer.UV4Kind
  23807. * - BABYLON.VertexBuffer.UV5Kind
  23808. * - BABYLON.VertexBuffer.UV6Kind
  23809. * - BABYLON.VertexBuffer.ColorKind
  23810. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23811. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23812. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23813. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23814. *
  23815. * Returns the Mesh.
  23816. */
  23817. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  23818. if (!this._geometry) {
  23819. return this;
  23820. }
  23821. if (!makeItUnique) {
  23822. this._geometry.updateVerticesData(kind, data, updateExtends);
  23823. }
  23824. else {
  23825. this.makeGeometryUnique();
  23826. this.updateVerticesData(kind, data, updateExtends, false);
  23827. }
  23828. return this;
  23829. };
  23830. /**
  23831. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  23832. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  23833. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  23834. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  23835. * Returns the Mesh.
  23836. */
  23837. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  23838. if (computeNormals === void 0) { computeNormals = true; }
  23839. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23840. if (!positions) {
  23841. return this;
  23842. }
  23843. positionFunction(positions);
  23844. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  23845. if (computeNormals) {
  23846. var indices = this.getIndices();
  23847. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23848. if (!normals) {
  23849. return this;
  23850. }
  23851. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  23852. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  23853. }
  23854. return this;
  23855. };
  23856. /**
  23857. * Creates a un-shared specific occurence of the geometry for the mesh.
  23858. * Returns the Mesh.
  23859. */
  23860. Mesh.prototype.makeGeometryUnique = function () {
  23861. if (!this._geometry) {
  23862. return this;
  23863. }
  23864. var oldGeometry = this._geometry;
  23865. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  23866. oldGeometry.releaseForMesh(this, true);
  23867. geometry.applyToMesh(this);
  23868. return this;
  23869. };
  23870. /**
  23871. * Sets the mesh indices.
  23872. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  23873. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  23874. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  23875. * This method creates a new index buffer each call.
  23876. * Returns the Mesh.
  23877. */
  23878. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  23879. if (totalVertices === void 0) { totalVertices = null; }
  23880. if (updatable === void 0) { updatable = false; }
  23881. if (!this._geometry) {
  23882. var vertexData = new BABYLON.VertexData();
  23883. vertexData.indices = indices;
  23884. var scene = this.getScene();
  23885. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  23886. }
  23887. else {
  23888. this._geometry.setIndices(indices, totalVertices, updatable);
  23889. }
  23890. return this;
  23891. };
  23892. /**
  23893. * Update the current index buffer
  23894. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  23895. * Returns the Mesh.
  23896. */
  23897. Mesh.prototype.updateIndices = function (indices, offset) {
  23898. if (!this._geometry) {
  23899. return this;
  23900. }
  23901. this._geometry.updateIndices(indices, offset);
  23902. return this;
  23903. };
  23904. /**
  23905. * Invert the geometry to move from a right handed system to a left handed one.
  23906. * Returns the Mesh.
  23907. */
  23908. Mesh.prototype.toLeftHanded = function () {
  23909. if (!this._geometry) {
  23910. return this;
  23911. }
  23912. this._geometry.toLeftHanded();
  23913. return this;
  23914. };
  23915. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  23916. if (!this._geometry) {
  23917. return this;
  23918. }
  23919. var engine = this.getScene().getEngine();
  23920. // Wireframe
  23921. var indexToBind;
  23922. if (this._unIndexed) {
  23923. indexToBind = null;
  23924. }
  23925. else {
  23926. switch (fillMode) {
  23927. case BABYLON.Material.PointFillMode:
  23928. indexToBind = null;
  23929. break;
  23930. case BABYLON.Material.WireFrameFillMode:
  23931. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  23932. break;
  23933. default:
  23934. case BABYLON.Material.TriangleFillMode:
  23935. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  23936. break;
  23937. }
  23938. }
  23939. // VBOs
  23940. this._geometry._bind(effect, indexToBind);
  23941. return this;
  23942. };
  23943. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  23944. if (alternate === void 0) { alternate = false; }
  23945. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23946. return this;
  23947. }
  23948. this.onBeforeDrawObservable.notifyObservers(this);
  23949. var scene = this.getScene();
  23950. var engine = scene.getEngine();
  23951. // Draw order
  23952. switch (fillMode) {
  23953. case BABYLON.Material.PointFillMode:
  23954. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23955. break;
  23956. case BABYLON.Material.WireFrameFillMode:
  23957. if (this._unIndexed) {
  23958. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23959. }
  23960. else {
  23961. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  23962. }
  23963. break;
  23964. default:
  23965. if (this._unIndexed) {
  23966. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23967. }
  23968. else {
  23969. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  23970. }
  23971. }
  23972. if (scene._isAlternateRenderingEnabled && !alternate) {
  23973. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  23974. if (!effect || !scene.activeCamera) {
  23975. return this;
  23976. }
  23977. scene._switchToAlternateCameraConfiguration(true);
  23978. this._effectiveMaterial.bindView(effect);
  23979. this._effectiveMaterial.bindViewProjection(effect);
  23980. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  23981. this._draw(subMesh, fillMode, instancesCount, true);
  23982. engine.setViewport(scene.activeCamera.viewport);
  23983. scene._switchToAlternateCameraConfiguration(false);
  23984. this._effectiveMaterial.bindView(effect);
  23985. this._effectiveMaterial.bindViewProjection(effect);
  23986. }
  23987. return this;
  23988. };
  23989. /**
  23990. * Registers for this mesh a javascript function called just before the rendering process.
  23991. * This function is passed the current mesh.
  23992. * Return the Mesh.
  23993. */
  23994. Mesh.prototype.registerBeforeRender = function (func) {
  23995. this.onBeforeRenderObservable.add(func);
  23996. return this;
  23997. };
  23998. /**
  23999. * Disposes a previously registered javascript function called before the rendering.
  24000. * This function is passed the current mesh.
  24001. * Returns the Mesh.
  24002. */
  24003. Mesh.prototype.unregisterBeforeRender = function (func) {
  24004. this.onBeforeRenderObservable.removeCallback(func);
  24005. return this;
  24006. };
  24007. /**
  24008. * Registers for this mesh a javascript function called just after the rendering is complete.
  24009. * This function is passed the current mesh.
  24010. * Returns the Mesh.
  24011. */
  24012. Mesh.prototype.registerAfterRender = function (func) {
  24013. this.onAfterRenderObservable.add(func);
  24014. return this;
  24015. };
  24016. /**
  24017. * Disposes a previously registered javascript function called after the rendering.
  24018. * This function is passed the current mesh.
  24019. * Return the Mesh.
  24020. */
  24021. Mesh.prototype.unregisterAfterRender = function (func) {
  24022. this.onAfterRenderObservable.removeCallback(func);
  24023. return this;
  24024. };
  24025. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  24026. var scene = this.getScene();
  24027. this._batchCache.mustReturn = false;
  24028. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  24029. this._batchCache.visibleInstances[subMeshId] = null;
  24030. if (this._visibleInstances) {
  24031. var currentRenderId = scene.getRenderId();
  24032. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  24033. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  24034. var selfRenderId = this._renderId;
  24035. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  24036. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  24037. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  24038. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  24039. }
  24040. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  24041. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  24042. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  24043. this._batchCache.mustReturn = true;
  24044. return this._batchCache;
  24045. }
  24046. if (currentRenderId !== selfRenderId) {
  24047. this._batchCache.renderSelf[subMeshId] = false;
  24048. }
  24049. }
  24050. this._renderIdForInstances[subMeshId] = currentRenderId;
  24051. }
  24052. return this._batchCache;
  24053. };
  24054. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  24055. var visibleInstances = batch.visibleInstances[subMesh._id];
  24056. if (!visibleInstances) {
  24057. return this;
  24058. }
  24059. var matricesCount = visibleInstances.length + 1;
  24060. var bufferSize = matricesCount * 16 * 4;
  24061. var currentInstancesBufferSize = this._instancesBufferSize;
  24062. var instancesBuffer = this._instancesBuffer;
  24063. while (this._instancesBufferSize < bufferSize) {
  24064. this._instancesBufferSize *= 2;
  24065. }
  24066. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  24067. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  24068. }
  24069. var offset = 0;
  24070. var instancesCount = 0;
  24071. var world = this.getWorldMatrix();
  24072. if (batch.renderSelf[subMesh._id]) {
  24073. world.copyToArray(this._instancesData, offset);
  24074. offset += 16;
  24075. instancesCount++;
  24076. }
  24077. if (visibleInstances) {
  24078. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  24079. var instance = visibleInstances[instanceIndex];
  24080. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  24081. offset += 16;
  24082. instancesCount++;
  24083. }
  24084. }
  24085. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  24086. if (instancesBuffer) {
  24087. instancesBuffer.dispose();
  24088. }
  24089. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  24090. this._instancesBuffer = instancesBuffer;
  24091. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  24092. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  24093. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  24094. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  24095. }
  24096. else {
  24097. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  24098. }
  24099. this._bind(subMesh, effect, fillMode);
  24100. this._draw(subMesh, fillMode, instancesCount);
  24101. engine.unbindInstanceAttributes();
  24102. return this;
  24103. };
  24104. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  24105. var scene = this.getScene();
  24106. var engine = scene.getEngine();
  24107. if (hardwareInstancedRendering) {
  24108. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  24109. }
  24110. else {
  24111. if (batch.renderSelf[subMesh._id]) {
  24112. // Draw
  24113. if (onBeforeDraw) {
  24114. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  24115. }
  24116. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  24117. }
  24118. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  24119. if (visibleInstancesForSubMesh) {
  24120. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  24121. var instance = visibleInstancesForSubMesh[instanceIndex];
  24122. // World
  24123. var world = instance.getWorldMatrix();
  24124. if (onBeforeDraw) {
  24125. onBeforeDraw(true, world, effectiveMaterial);
  24126. }
  24127. // Draw
  24128. this._draw(subMesh, fillMode);
  24129. }
  24130. }
  24131. }
  24132. return this;
  24133. };
  24134. /**
  24135. * Triggers the draw call for the mesh.
  24136. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  24137. * Returns the Mesh.
  24138. */
  24139. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  24140. this.checkOcclusionQuery();
  24141. if (this._isOccluded) {
  24142. return this;
  24143. }
  24144. var scene = this.getScene();
  24145. // Managing instances
  24146. var batch = this._getInstancesRenderList(subMesh._id);
  24147. if (batch.mustReturn) {
  24148. return this;
  24149. }
  24150. // Checking geometry state
  24151. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  24152. return this;
  24153. }
  24154. this.onBeforeRenderObservable.notifyObservers(this);
  24155. var engine = scene.getEngine();
  24156. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  24157. // Material
  24158. var material = subMesh.getMaterial();
  24159. if (!material) {
  24160. return this;
  24161. }
  24162. this._effectiveMaterial = material;
  24163. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  24164. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  24165. return this;
  24166. }
  24167. }
  24168. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  24169. return this;
  24170. }
  24171. // Alpha mode
  24172. if (enableAlphaMode) {
  24173. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  24174. }
  24175. // Outline - step 1
  24176. var savedDepthWrite = engine.getDepthWrite();
  24177. if (this.renderOutline) {
  24178. engine.setDepthWrite(false);
  24179. scene.getOutlineRenderer().render(subMesh, batch);
  24180. engine.setDepthWrite(savedDepthWrite);
  24181. }
  24182. var effect;
  24183. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  24184. effect = subMesh.effect;
  24185. }
  24186. else {
  24187. effect = this._effectiveMaterial.getEffect();
  24188. }
  24189. if (!effect) {
  24190. return this;
  24191. }
  24192. var reverse = this._effectiveMaterial._preBind(effect, this.overrideMaterialSideOrientation);
  24193. if (this._effectiveMaterial.forceDepthWrite) {
  24194. engine.setDepthWrite(true);
  24195. }
  24196. // Bind
  24197. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  24198. if (!hardwareInstancedRendering) {
  24199. this._bind(subMesh, effect, fillMode);
  24200. }
  24201. var world = this.getWorldMatrix();
  24202. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  24203. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  24204. }
  24205. else {
  24206. this._effectiveMaterial.bind(world, this);
  24207. }
  24208. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  24209. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  24210. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  24211. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  24212. }
  24213. // Draw
  24214. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  24215. // Unbind
  24216. this._effectiveMaterial.unbind();
  24217. // Outline - step 2
  24218. if (this.renderOutline && savedDepthWrite) {
  24219. engine.setDepthWrite(true);
  24220. engine.setColorWrite(false);
  24221. scene.getOutlineRenderer().render(subMesh, batch);
  24222. engine.setColorWrite(true);
  24223. }
  24224. // Overlay
  24225. if (this.renderOverlay) {
  24226. var currentMode = engine.getAlphaMode();
  24227. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  24228. scene.getOutlineRenderer().render(subMesh, batch, true);
  24229. engine.setAlphaMode(currentMode);
  24230. }
  24231. this.onAfterRenderObservable.notifyObservers(this);
  24232. return this;
  24233. };
  24234. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  24235. if (isInstance && effectiveMaterial) {
  24236. effectiveMaterial.bindOnlyWorldMatrix(world);
  24237. }
  24238. };
  24239. /**
  24240. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  24241. */
  24242. Mesh.prototype.getEmittedParticleSystems = function () {
  24243. var results = new Array();
  24244. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  24245. var particleSystem = this.getScene().particleSystems[index];
  24246. if (particleSystem.emitter === this) {
  24247. results.push(particleSystem);
  24248. }
  24249. }
  24250. return results;
  24251. };
  24252. /**
  24253. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  24254. */
  24255. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  24256. var results = new Array();
  24257. var descendants = this.getDescendants();
  24258. descendants.push(this);
  24259. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  24260. var particleSystem = this.getScene().particleSystems[index];
  24261. var emitter = particleSystem.emitter;
  24262. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  24263. results.push(particleSystem);
  24264. }
  24265. }
  24266. return results;
  24267. };
  24268. Mesh.prototype._checkDelayState = function () {
  24269. var scene = this.getScene();
  24270. if (this._geometry) {
  24271. this._geometry.load(scene);
  24272. }
  24273. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24274. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  24275. this._queueLoad(this, scene);
  24276. }
  24277. return this;
  24278. };
  24279. Mesh.prototype._queueLoad = function (mesh, scene) {
  24280. var _this = this;
  24281. scene._addPendingData(mesh);
  24282. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  24283. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  24284. if (data instanceof ArrayBuffer) {
  24285. _this._delayLoadingFunction(data, _this);
  24286. }
  24287. else {
  24288. _this._delayLoadingFunction(JSON.parse(data), _this);
  24289. }
  24290. _this.instances.forEach(function (instance) {
  24291. instance._syncSubMeshes();
  24292. });
  24293. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24294. scene._removePendingData(_this);
  24295. }, function () { }, scene.database, getBinaryData);
  24296. return this;
  24297. };
  24298. /**
  24299. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  24300. */
  24301. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  24302. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  24303. return false;
  24304. }
  24305. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  24306. return false;
  24307. }
  24308. this._checkDelayState();
  24309. return true;
  24310. };
  24311. /**
  24312. * Sets the mesh material by the material or multiMaterial `id` property.
  24313. * The material `id` is a string identifying the material or the multiMaterial.
  24314. * This method returns the Mesh.
  24315. */
  24316. Mesh.prototype.setMaterialByID = function (id) {
  24317. var materials = this.getScene().materials;
  24318. var index;
  24319. for (index = materials.length - 1; index > -1; index--) {
  24320. if (materials[index].id === id) {
  24321. this.material = materials[index];
  24322. return this;
  24323. }
  24324. }
  24325. // Multi
  24326. var multiMaterials = this.getScene().multiMaterials;
  24327. for (index = multiMaterials.length - 1; index > -1; index--) {
  24328. if (multiMaterials[index].id === id) {
  24329. this.material = multiMaterials[index];
  24330. return this;
  24331. }
  24332. }
  24333. return this;
  24334. };
  24335. /**
  24336. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  24337. */
  24338. Mesh.prototype.getAnimatables = function () {
  24339. var results = new Array();
  24340. if (this.material) {
  24341. results.push(this.material);
  24342. }
  24343. if (this.skeleton) {
  24344. results.push(this.skeleton);
  24345. }
  24346. return results;
  24347. };
  24348. /**
  24349. * Modifies the mesh geometry according to the passed transformation matrix.
  24350. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  24351. * The mesh normals are modified accordingly the same transformation.
  24352. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  24353. * Note that, under the hood, this method sets a new VertexBuffer each call.
  24354. * Returns the Mesh.
  24355. */
  24356. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  24357. // Position
  24358. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24359. return this;
  24360. }
  24361. var submeshes = this.subMeshes.splice(0);
  24362. this._resetPointsArrayCache();
  24363. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24364. var temp = new Array();
  24365. var index;
  24366. for (index = 0; index < data.length; index += 3) {
  24367. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  24368. }
  24369. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  24370. // Normals
  24371. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24372. return this;
  24373. }
  24374. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24375. temp = [];
  24376. for (index = 0; index < data.length; index += 3) {
  24377. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  24378. }
  24379. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  24380. // flip faces?
  24381. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  24382. this.flipFaces();
  24383. }
  24384. // Restore submeshes
  24385. this.releaseSubMeshes();
  24386. this.subMeshes = submeshes;
  24387. return this;
  24388. };
  24389. /**
  24390. * Modifies the mesh geometry according to its own current World Matrix.
  24391. * The mesh World Matrix is then reset.
  24392. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  24393. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  24394. * Note that, under the hood, this method sets a new VertexBuffer each call.
  24395. * Returns the Mesh.
  24396. */
  24397. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  24398. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  24399. this.scaling.copyFromFloats(1, 1, 1);
  24400. this.position.copyFromFloats(0, 0, 0);
  24401. this.rotation.copyFromFloats(0, 0, 0);
  24402. //only if quaternion is already set
  24403. if (this.rotationQuaternion) {
  24404. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  24405. }
  24406. this._worldMatrix = BABYLON.Matrix.Identity();
  24407. return this;
  24408. };
  24409. Object.defineProperty(Mesh.prototype, "_positions", {
  24410. // Cache
  24411. get: function () {
  24412. if (this._geometry) {
  24413. return this._geometry._positions;
  24414. }
  24415. return null;
  24416. },
  24417. enumerable: true,
  24418. configurable: true
  24419. });
  24420. Mesh.prototype._resetPointsArrayCache = function () {
  24421. if (this._geometry) {
  24422. this._geometry._resetPointsArrayCache();
  24423. }
  24424. return this;
  24425. };
  24426. Mesh.prototype._generatePointsArray = function () {
  24427. if (this._geometry) {
  24428. return this._geometry._generatePointsArray();
  24429. }
  24430. return false;
  24431. };
  24432. /**
  24433. * Returns a new Mesh object generated from the current mesh properties.
  24434. * This method must not get confused with createInstance().
  24435. * The parameter `name` is a string, the name given to the new mesh.
  24436. * The optional parameter `newParent` can be any Node object (default `null`).
  24437. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  24438. * 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.
  24439. */
  24440. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  24441. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  24442. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  24443. };
  24444. /**
  24445. * Disposes the Mesh.
  24446. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  24447. * Returns nothing.
  24448. */
  24449. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  24450. var _this = this;
  24451. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  24452. this.morphTargetManager = null;
  24453. if (this._geometry) {
  24454. this._geometry.releaseForMesh(this, true);
  24455. }
  24456. // Sources
  24457. var meshes = this.getScene().meshes;
  24458. meshes.forEach(function (abstractMesh) {
  24459. var mesh = abstractMesh;
  24460. if (mesh._source && mesh._source === _this) {
  24461. mesh._source = null;
  24462. }
  24463. });
  24464. this._source = null;
  24465. // Instances
  24466. if (this._instancesBuffer) {
  24467. this._instancesBuffer.dispose();
  24468. this._instancesBuffer = null;
  24469. }
  24470. while (this.instances.length) {
  24471. this.instances[0].dispose();
  24472. }
  24473. // Highlight layers.
  24474. var highlightLayers = this.getScene().highlightLayers;
  24475. for (var i = 0; i < highlightLayers.length; i++) {
  24476. var highlightLayer = highlightLayers[i];
  24477. if (highlightLayer) {
  24478. highlightLayer.removeMesh(this);
  24479. highlightLayer.removeExcludedMesh(this);
  24480. }
  24481. }
  24482. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  24483. };
  24484. /**
  24485. * Modifies the mesh geometry according to a displacement map.
  24486. * 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.
  24487. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  24488. * This method returns nothing.
  24489. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  24490. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  24491. * 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.
  24492. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  24493. * The parameter `uvScale` is an optional vector2 used to scale UV.
  24494. *
  24495. * Returns the Mesh.
  24496. */
  24497. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  24498. var _this = this;
  24499. var scene = this.getScene();
  24500. var onload = function (img) {
  24501. // Getting height map data
  24502. var canvas = document.createElement("canvas");
  24503. var context = canvas.getContext("2d");
  24504. var heightMapWidth = img.width;
  24505. var heightMapHeight = img.height;
  24506. canvas.width = heightMapWidth;
  24507. canvas.height = heightMapHeight;
  24508. context.drawImage(img, 0, 0);
  24509. // Create VertexData from map data
  24510. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  24511. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  24512. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  24513. //execute success callback, if set
  24514. if (onSuccess) {
  24515. onSuccess(_this);
  24516. }
  24517. };
  24518. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  24519. return this;
  24520. };
  24521. /**
  24522. * Modifies the mesh geometry according to a displacementMap buffer.
  24523. * 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.
  24524. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  24525. * This method returns nothing.
  24526. * 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.
  24527. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  24528. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  24529. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  24530. * The parameter `uvScale` is an optional vector2 used to scale UV.
  24531. *
  24532. * Returns the Mesh.
  24533. */
  24534. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  24535. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  24536. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  24537. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24538. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  24539. return this;
  24540. }
  24541. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24542. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24543. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  24544. var position = BABYLON.Vector3.Zero();
  24545. var normal = BABYLON.Vector3.Zero();
  24546. var uv = BABYLON.Vector2.Zero();
  24547. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  24548. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  24549. for (var index = 0; index < positions.length; index += 3) {
  24550. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  24551. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  24552. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  24553. // Compute height
  24554. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  24555. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  24556. var pos = (u + v * heightMapWidth) * 4;
  24557. var r = buffer[pos] / 255.0;
  24558. var g = buffer[pos + 1] / 255.0;
  24559. var b = buffer[pos + 2] / 255.0;
  24560. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  24561. normal.normalize();
  24562. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  24563. position = position.add(normal);
  24564. position.toArray(positions, index);
  24565. }
  24566. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  24567. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  24568. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  24569. return this;
  24570. };
  24571. /**
  24572. * Modify the mesh to get a flat shading rendering.
  24573. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  24574. * This method returns the Mesh.
  24575. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  24576. */
  24577. Mesh.prototype.convertToFlatShadedMesh = function () {
  24578. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  24579. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  24580. var kinds = this.getVerticesDataKinds();
  24581. var vbs = {};
  24582. var data = {};
  24583. var newdata = {};
  24584. var updatableNormals = false;
  24585. var kindIndex;
  24586. var kind;
  24587. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24588. kind = kinds[kindIndex];
  24589. var vertexBuffer = this.getVertexBuffer(kind);
  24590. if (kind === BABYLON.VertexBuffer.NormalKind) {
  24591. updatableNormals = vertexBuffer.isUpdatable();
  24592. kinds.splice(kindIndex, 1);
  24593. kindIndex--;
  24594. continue;
  24595. }
  24596. vbs[kind] = vertexBuffer;
  24597. data[kind] = vbs[kind].getData();
  24598. newdata[kind] = [];
  24599. }
  24600. // Save previous submeshes
  24601. var previousSubmeshes = this.subMeshes.slice(0);
  24602. var indices = this.getIndices();
  24603. var totalIndices = this.getTotalIndices();
  24604. // Generating unique vertices per face
  24605. var index;
  24606. for (index = 0; index < totalIndices; index++) {
  24607. var vertexIndex = indices[index];
  24608. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24609. kind = kinds[kindIndex];
  24610. var stride = vbs[kind].getStrideSize();
  24611. for (var offset = 0; offset < stride; offset++) {
  24612. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  24613. }
  24614. }
  24615. }
  24616. // Updating faces & normal
  24617. var normals = [];
  24618. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  24619. for (index = 0; index < totalIndices; index += 3) {
  24620. indices[index] = index;
  24621. indices[index + 1] = index + 1;
  24622. indices[index + 2] = index + 2;
  24623. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  24624. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  24625. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  24626. var p1p2 = p1.subtract(p2);
  24627. var p3p2 = p3.subtract(p2);
  24628. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  24629. // Store same normals for every vertex
  24630. for (var localIndex = 0; localIndex < 3; localIndex++) {
  24631. normals.push(normal.x);
  24632. normals.push(normal.y);
  24633. normals.push(normal.z);
  24634. }
  24635. }
  24636. this.setIndices(indices);
  24637. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  24638. // Updating vertex buffers
  24639. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24640. kind = kinds[kindIndex];
  24641. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24642. }
  24643. // Updating submeshes
  24644. this.releaseSubMeshes();
  24645. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24646. var previousOne = previousSubmeshes[submeshIndex];
  24647. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24648. }
  24649. this.synchronizeInstances();
  24650. return this;
  24651. };
  24652. /**
  24653. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  24654. * In other words, more vertices, no more indices and a single bigger VBO.
  24655. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  24656. * Returns the Mesh.
  24657. */
  24658. Mesh.prototype.convertToUnIndexedMesh = function () {
  24659. /// <summary>Remove indices by unfolding faces into buffers</summary>
  24660. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  24661. var kinds = this.getVerticesDataKinds();
  24662. var vbs = {};
  24663. var data = {};
  24664. var newdata = {};
  24665. var kindIndex;
  24666. var kind;
  24667. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24668. kind = kinds[kindIndex];
  24669. var vertexBuffer = this.getVertexBuffer(kind);
  24670. vbs[kind] = vertexBuffer;
  24671. data[kind] = vbs[kind].getData();
  24672. newdata[kind] = [];
  24673. }
  24674. // Save previous submeshes
  24675. var previousSubmeshes = this.subMeshes.slice(0);
  24676. var indices = this.getIndices();
  24677. var totalIndices = this.getTotalIndices();
  24678. // Generating unique vertices per face
  24679. var index;
  24680. for (index = 0; index < totalIndices; index++) {
  24681. var vertexIndex = indices[index];
  24682. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24683. kind = kinds[kindIndex];
  24684. var stride = vbs[kind].getStrideSize();
  24685. for (var offset = 0; offset < stride; offset++) {
  24686. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  24687. }
  24688. }
  24689. }
  24690. // Updating indices
  24691. for (index = 0; index < totalIndices; index += 3) {
  24692. indices[index] = index;
  24693. indices[index + 1] = index + 1;
  24694. indices[index + 2] = index + 2;
  24695. }
  24696. this.setIndices(indices);
  24697. // Updating vertex buffers
  24698. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24699. kind = kinds[kindIndex];
  24700. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24701. }
  24702. // Updating submeshes
  24703. this.releaseSubMeshes();
  24704. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24705. var previousOne = previousSubmeshes[submeshIndex];
  24706. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24707. }
  24708. this._unIndexed = true;
  24709. this.synchronizeInstances();
  24710. return this;
  24711. };
  24712. /**
  24713. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  24714. * This method returns the Mesh.
  24715. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  24716. */
  24717. Mesh.prototype.flipFaces = function (flipNormals) {
  24718. if (flipNormals === void 0) { flipNormals = false; }
  24719. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  24720. var i;
  24721. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  24722. for (i = 0; i < vertex_data.normals.length; i++) {
  24723. vertex_data.normals[i] *= -1;
  24724. }
  24725. }
  24726. if (vertex_data.indices) {
  24727. var temp;
  24728. for (i = 0; i < vertex_data.indices.length; i += 3) {
  24729. // reassign indices
  24730. temp = vertex_data.indices[i + 1];
  24731. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  24732. vertex_data.indices[i + 2] = temp;
  24733. }
  24734. }
  24735. vertex_data.applyToMesh(this);
  24736. return this;
  24737. };
  24738. // Instances
  24739. /**
  24740. * Creates a new InstancedMesh object from the mesh model.
  24741. * An instance shares the same properties and the same material than its model.
  24742. * Only these properties of each instance can then be set individually :
  24743. * - position
  24744. * - rotation
  24745. * - rotationQuaternion
  24746. * - setPivotMatrix
  24747. * - scaling
  24748. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  24749. * Warning : this method is not supported for Line mesh and LineSystem
  24750. */
  24751. Mesh.prototype.createInstance = function (name) {
  24752. return new BABYLON.InstancedMesh(name, this);
  24753. };
  24754. /**
  24755. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  24756. * After this call, all the mesh instances have the same submeshes than the current mesh.
  24757. * This method returns the Mesh.
  24758. */
  24759. Mesh.prototype.synchronizeInstances = function () {
  24760. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  24761. var instance = this.instances[instanceIndex];
  24762. instance._syncSubMeshes();
  24763. }
  24764. return this;
  24765. };
  24766. /**
  24767. * Simplify the mesh according to the given array of settings.
  24768. * Function will return immediately and will simplify async. It returns the Mesh.
  24769. * @param settings a collection of simplification settings.
  24770. * @param parallelProcessing should all levels calculate parallel or one after the other.
  24771. * @param type the type of simplification to run.
  24772. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  24773. */
  24774. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  24775. if (parallelProcessing === void 0) { parallelProcessing = true; }
  24776. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  24777. this.getScene().simplificationQueue.addTask({
  24778. settings: settings,
  24779. parallelProcessing: parallelProcessing,
  24780. mesh: this,
  24781. simplificationType: simplificationType,
  24782. successCallback: successCallback
  24783. });
  24784. return this;
  24785. };
  24786. /**
  24787. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  24788. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  24789. * This should be used together with the simplification to avoid disappearing triangles.
  24790. * Returns the Mesh.
  24791. * @param successCallback an optional success callback to be called after the optimization finished.
  24792. */
  24793. Mesh.prototype.optimizeIndices = function (successCallback) {
  24794. var _this = this;
  24795. var indices = this.getIndices();
  24796. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24797. if (!positions || !indices) {
  24798. return this;
  24799. }
  24800. var vectorPositions = new Array();
  24801. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  24802. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  24803. }
  24804. var dupes = new Array();
  24805. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  24806. var realPos = vectorPositions.length - 1 - iteration;
  24807. var testedPosition = vectorPositions[realPos];
  24808. for (var j = 0; j < realPos; ++j) {
  24809. var againstPosition = vectorPositions[j];
  24810. if (testedPosition.equals(againstPosition)) {
  24811. dupes[realPos] = j;
  24812. break;
  24813. }
  24814. }
  24815. }, function () {
  24816. for (var i = 0; i < indices.length; ++i) {
  24817. indices[i] = dupes[indices[i]] || indices[i];
  24818. }
  24819. //indices are now reordered
  24820. var originalSubMeshes = _this.subMeshes.slice(0);
  24821. _this.setIndices(indices);
  24822. _this.subMeshes = originalSubMeshes;
  24823. if (successCallback) {
  24824. successCallback(_this);
  24825. }
  24826. });
  24827. return this;
  24828. };
  24829. Mesh.prototype.serialize = function (serializationObject) {
  24830. serializationObject.name = this.name;
  24831. serializationObject.id = this.id;
  24832. serializationObject.type = this.getClassName();
  24833. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  24834. serializationObject.tags = BABYLON.Tags.GetTags(this);
  24835. }
  24836. serializationObject.position = this.position.asArray();
  24837. if (this.rotationQuaternion) {
  24838. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  24839. }
  24840. else if (this.rotation) {
  24841. serializationObject.rotation = this.rotation.asArray();
  24842. }
  24843. serializationObject.scaling = this.scaling.asArray();
  24844. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  24845. serializationObject.isEnabled = this.isEnabled();
  24846. serializationObject.isVisible = this.isVisible;
  24847. serializationObject.infiniteDistance = this.infiniteDistance;
  24848. serializationObject.pickable = this.isPickable;
  24849. serializationObject.receiveShadows = this.receiveShadows;
  24850. serializationObject.billboardMode = this.billboardMode;
  24851. serializationObject.visibility = this.visibility;
  24852. serializationObject.checkCollisions = this.checkCollisions;
  24853. serializationObject.isBlocker = this.isBlocker;
  24854. // Parent
  24855. if (this.parent) {
  24856. serializationObject.parentId = this.parent.id;
  24857. }
  24858. // Geometry
  24859. var geometry = this._geometry;
  24860. if (geometry) {
  24861. var geometryId = geometry.id;
  24862. serializationObject.geometryId = geometryId;
  24863. // SubMeshes
  24864. serializationObject.subMeshes = [];
  24865. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  24866. var subMesh = this.subMeshes[subIndex];
  24867. serializationObject.subMeshes.push({
  24868. materialIndex: subMesh.materialIndex,
  24869. verticesStart: subMesh.verticesStart,
  24870. verticesCount: subMesh.verticesCount,
  24871. indexStart: subMesh.indexStart,
  24872. indexCount: subMesh.indexCount
  24873. });
  24874. }
  24875. }
  24876. // Material
  24877. if (this.material) {
  24878. serializationObject.materialId = this.material.id;
  24879. }
  24880. else {
  24881. this.material = null;
  24882. }
  24883. // Morph targets
  24884. if (this.morphTargetManager) {
  24885. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  24886. }
  24887. // Skeleton
  24888. if (this.skeleton) {
  24889. serializationObject.skeletonId = this.skeleton.id;
  24890. }
  24891. // Physics
  24892. //TODO implement correct serialization for physics impostors.
  24893. var impostor = this.getPhysicsImpostor();
  24894. if (impostor) {
  24895. serializationObject.physicsMass = impostor.getParam("mass");
  24896. serializationObject.physicsFriction = impostor.getParam("friction");
  24897. serializationObject.physicsRestitution = impostor.getParam("mass");
  24898. serializationObject.physicsImpostor = impostor.type;
  24899. }
  24900. // Metadata
  24901. if (this.metadata) {
  24902. serializationObject.metadata = this.metadata;
  24903. }
  24904. // Instances
  24905. serializationObject.instances = [];
  24906. for (var index = 0; index < this.instances.length; index++) {
  24907. var instance = this.instances[index];
  24908. var serializationInstance = {
  24909. name: instance.name,
  24910. position: instance.position.asArray(),
  24911. scaling: instance.scaling.asArray()
  24912. };
  24913. if (instance.rotationQuaternion) {
  24914. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  24915. }
  24916. else if (instance.rotation) {
  24917. serializationInstance.rotation = instance.rotation.asArray();
  24918. }
  24919. serializationObject.instances.push(serializationInstance);
  24920. // Animations
  24921. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  24922. serializationInstance.ranges = instance.serializeAnimationRanges();
  24923. }
  24924. //
  24925. // Animations
  24926. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24927. serializationObject.ranges = this.serializeAnimationRanges();
  24928. // Layer mask
  24929. serializationObject.layerMask = this.layerMask;
  24930. // Alpha
  24931. serializationObject.alphaIndex = this.alphaIndex;
  24932. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  24933. // Overlay
  24934. serializationObject.overlayAlpha = this.overlayAlpha;
  24935. serializationObject.overlayColor = this.overlayColor.asArray();
  24936. serializationObject.renderOverlay = this.renderOverlay;
  24937. // Fog
  24938. serializationObject.applyFog = this.applyFog;
  24939. // Action Manager
  24940. if (this.actionManager) {
  24941. serializationObject.actions = this.actionManager.serialize(this.name);
  24942. }
  24943. };
  24944. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  24945. if (!this.geometry) {
  24946. return;
  24947. }
  24948. this._markSubMeshesAsAttributesDirty();
  24949. var morphTargetManager = this._morphTargetManager;
  24950. if (morphTargetManager && morphTargetManager.vertexCount) {
  24951. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  24952. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  24953. this.morphTargetManager = null;
  24954. return;
  24955. }
  24956. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  24957. var morphTarget = morphTargetManager.getActiveTarget(index);
  24958. var positions = morphTarget.getPositions();
  24959. if (!positions) {
  24960. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  24961. return;
  24962. }
  24963. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  24964. var normals = morphTarget.getNormals();
  24965. if (normals) {
  24966. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  24967. }
  24968. var tangents = morphTarget.getTangents();
  24969. if (tangents) {
  24970. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  24971. }
  24972. }
  24973. }
  24974. else {
  24975. var index = 0;
  24976. // Positions
  24977. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  24978. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  24979. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  24980. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  24981. }
  24982. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  24983. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  24984. }
  24985. index++;
  24986. }
  24987. }
  24988. };
  24989. // Statics
  24990. /**
  24991. * Returns a new Mesh object parsed from the source provided.
  24992. * The parameter `parsedMesh` is the source.
  24993. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  24994. */
  24995. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  24996. var mesh;
  24997. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  24998. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  24999. }
  25000. else {
  25001. mesh = new Mesh(parsedMesh.name, scene);
  25002. }
  25003. mesh.id = parsedMesh.id;
  25004. if (BABYLON.Tags) {
  25005. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  25006. }
  25007. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  25008. if (parsedMesh.metadata !== undefined) {
  25009. mesh.metadata = parsedMesh.metadata;
  25010. }
  25011. if (parsedMesh.rotationQuaternion) {
  25012. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  25013. }
  25014. else if (parsedMesh.rotation) {
  25015. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  25016. }
  25017. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  25018. if (parsedMesh.localMatrix) {
  25019. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  25020. }
  25021. else if (parsedMesh.pivotMatrix) {
  25022. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  25023. }
  25024. mesh.setEnabled(parsedMesh.isEnabled);
  25025. mesh.isVisible = parsedMesh.isVisible;
  25026. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  25027. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  25028. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  25029. if (parsedMesh.applyFog !== undefined) {
  25030. mesh.applyFog = parsedMesh.applyFog;
  25031. }
  25032. if (parsedMesh.pickable !== undefined) {
  25033. mesh.isPickable = parsedMesh.pickable;
  25034. }
  25035. if (parsedMesh.alphaIndex !== undefined) {
  25036. mesh.alphaIndex = parsedMesh.alphaIndex;
  25037. }
  25038. mesh.receiveShadows = parsedMesh.receiveShadows;
  25039. mesh.billboardMode = parsedMesh.billboardMode;
  25040. if (parsedMesh.visibility !== undefined) {
  25041. mesh.visibility = parsedMesh.visibility;
  25042. }
  25043. mesh.checkCollisions = parsedMesh.checkCollisions;
  25044. if (parsedMesh.isBlocker !== undefined) {
  25045. mesh.isBlocker = parsedMesh.isBlocker;
  25046. }
  25047. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  25048. // freezeWorldMatrix
  25049. if (parsedMesh.freezeWorldMatrix) {
  25050. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  25051. }
  25052. // Parent
  25053. if (parsedMesh.parentId) {
  25054. mesh._waitingParentId = parsedMesh.parentId;
  25055. }
  25056. // Actions
  25057. if (parsedMesh.actions !== undefined) {
  25058. mesh._waitingActions = parsedMesh.actions;
  25059. }
  25060. // Overlay
  25061. if (parsedMesh.overlayAlpha !== undefined) {
  25062. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  25063. }
  25064. if (parsedMesh.overlayColor !== undefined) {
  25065. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  25066. }
  25067. if (parsedMesh.renderOverlay !== undefined) {
  25068. mesh.renderOverlay = parsedMesh.renderOverlay;
  25069. }
  25070. // Geometry
  25071. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  25072. if (parsedMesh.delayLoadingFile) {
  25073. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  25074. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  25075. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  25076. if (parsedMesh._binaryInfo) {
  25077. mesh._binaryInfo = parsedMesh._binaryInfo;
  25078. }
  25079. mesh._delayInfo = [];
  25080. if (parsedMesh.hasUVs) {
  25081. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  25082. }
  25083. if (parsedMesh.hasUVs2) {
  25084. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  25085. }
  25086. if (parsedMesh.hasUVs3) {
  25087. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  25088. }
  25089. if (parsedMesh.hasUVs4) {
  25090. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  25091. }
  25092. if (parsedMesh.hasUVs5) {
  25093. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  25094. }
  25095. if (parsedMesh.hasUVs6) {
  25096. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  25097. }
  25098. if (parsedMesh.hasColors) {
  25099. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  25100. }
  25101. if (parsedMesh.hasMatricesIndices) {
  25102. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25103. }
  25104. if (parsedMesh.hasMatricesWeights) {
  25105. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25106. }
  25107. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  25108. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  25109. mesh._checkDelayState();
  25110. }
  25111. }
  25112. else {
  25113. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  25114. }
  25115. // Material
  25116. if (parsedMesh.materialId) {
  25117. mesh.setMaterialByID(parsedMesh.materialId);
  25118. }
  25119. else {
  25120. mesh.material = null;
  25121. }
  25122. // Morph targets
  25123. if (parsedMesh.morphTargetManagerId > -1) {
  25124. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  25125. }
  25126. // Skeleton
  25127. if (parsedMesh.skeletonId > -1) {
  25128. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  25129. if (parsedMesh.numBoneInfluencers) {
  25130. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  25131. }
  25132. }
  25133. // Animations
  25134. if (parsedMesh.animations) {
  25135. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  25136. var parsedAnimation = parsedMesh.animations[animationIndex];
  25137. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25138. }
  25139. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  25140. }
  25141. if (parsedMesh.autoAnimate) {
  25142. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  25143. }
  25144. // Layer Mask
  25145. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  25146. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  25147. }
  25148. else {
  25149. mesh.layerMask = 0x0FFFFFFF;
  25150. }
  25151. // Physics
  25152. if (parsedMesh.physicsImpostor) {
  25153. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  25154. mass: parsedMesh.physicsMass,
  25155. friction: parsedMesh.physicsFriction,
  25156. restitution: parsedMesh.physicsRestitution
  25157. }, scene);
  25158. }
  25159. // Instances
  25160. if (parsedMesh.instances) {
  25161. for (var index = 0; index < parsedMesh.instances.length; index++) {
  25162. var parsedInstance = parsedMesh.instances[index];
  25163. var instance = mesh.createInstance(parsedInstance.name);
  25164. if (BABYLON.Tags) {
  25165. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  25166. }
  25167. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  25168. if (parsedInstance.parentId) {
  25169. instance._waitingParentId = parsedInstance.parentId;
  25170. }
  25171. if (parsedInstance.rotationQuaternion) {
  25172. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  25173. }
  25174. else if (parsedInstance.rotation) {
  25175. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  25176. }
  25177. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  25178. instance.checkCollisions = mesh.checkCollisions;
  25179. if (parsedMesh.animations) {
  25180. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  25181. parsedAnimation = parsedMesh.animations[animationIndex];
  25182. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25183. }
  25184. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  25185. }
  25186. }
  25187. }
  25188. return mesh;
  25189. };
  25190. /**
  25191. * Creates a ribbon mesh.
  25192. * Please consider using the same method from the MeshBuilder class instead.
  25193. * 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.
  25194. *
  25195. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  25196. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  25197. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  25198. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  25199. * 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.
  25200. * 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.
  25201. * 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
  25202. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25203. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25204. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25205. */
  25206. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  25207. if (closeArray === void 0) { closeArray = false; }
  25208. if (updatable === void 0) { updatable = false; }
  25209. return BABYLON.MeshBuilder.CreateRibbon(name, {
  25210. pathArray: pathArray,
  25211. closeArray: closeArray,
  25212. closePath: closePath,
  25213. offset: offset,
  25214. updatable: updatable,
  25215. sideOrientation: sideOrientation,
  25216. instance: instance
  25217. }, scene);
  25218. };
  25219. /**
  25220. * Creates a plane polygonal mesh. By default, this is a disc.
  25221. * Please consider using the same method from the MeshBuilder class instead.
  25222. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  25223. * 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.
  25224. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25225. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25226. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25227. */
  25228. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  25229. if (scene === void 0) { scene = null; }
  25230. var options = {
  25231. radius: radius,
  25232. tessellation: tessellation,
  25233. sideOrientation: sideOrientation,
  25234. updatable: updatable
  25235. };
  25236. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  25237. };
  25238. /**
  25239. * Creates a box mesh.
  25240. * Please consider using the same method from the MeshBuilder class instead.
  25241. * The parameter `size` sets the size (float) of each box side (default 1).
  25242. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25243. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25244. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25245. */
  25246. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  25247. if (scene === void 0) { scene = null; }
  25248. var options = {
  25249. size: size,
  25250. sideOrientation: sideOrientation,
  25251. updatable: updatable
  25252. };
  25253. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  25254. };
  25255. /**
  25256. * Creates a sphere mesh.
  25257. * Please consider using the same method from the MeshBuilder class instead.
  25258. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  25259. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  25260. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25261. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25262. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25263. */
  25264. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  25265. var options = {
  25266. segments: segments,
  25267. diameterX: diameter,
  25268. diameterY: diameter,
  25269. diameterZ: diameter,
  25270. sideOrientation: sideOrientation,
  25271. updatable: updatable
  25272. };
  25273. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  25274. };
  25275. /**
  25276. * Creates a cylinder or a cone mesh.
  25277. * Please consider using the same method from the MeshBuilder class instead.
  25278. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  25279. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  25280. * 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.
  25281. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  25282. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  25283. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25284. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25285. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25286. */
  25287. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  25288. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  25289. if (scene !== undefined) {
  25290. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  25291. updatable = scene;
  25292. }
  25293. scene = subdivisions;
  25294. subdivisions = 1;
  25295. }
  25296. var options = {
  25297. height: height,
  25298. diameterTop: diameterTop,
  25299. diameterBottom: diameterBottom,
  25300. tessellation: tessellation,
  25301. subdivisions: subdivisions,
  25302. sideOrientation: sideOrientation,
  25303. updatable: updatable
  25304. };
  25305. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  25306. };
  25307. // Torus (Code from SharpDX.org)
  25308. /**
  25309. * Creates a torus mesh.
  25310. * Please consider using the same method from the MeshBuilder class instead.
  25311. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  25312. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  25313. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  25314. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25315. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25316. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25317. */
  25318. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  25319. var options = {
  25320. diameter: diameter,
  25321. thickness: thickness,
  25322. tessellation: tessellation,
  25323. sideOrientation: sideOrientation,
  25324. updatable: updatable
  25325. };
  25326. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  25327. };
  25328. /**
  25329. * Creates a torus knot mesh.
  25330. * Please consider using the same method from the MeshBuilder class instead.
  25331. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  25332. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  25333. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  25334. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  25335. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25336. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25337. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25338. */
  25339. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  25340. var options = {
  25341. radius: radius,
  25342. tube: tube,
  25343. radialSegments: radialSegments,
  25344. tubularSegments: tubularSegments,
  25345. p: p,
  25346. q: q,
  25347. sideOrientation: sideOrientation,
  25348. updatable: updatable
  25349. };
  25350. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  25351. };
  25352. /**
  25353. * Creates a line mesh.
  25354. * Please consider using the same method from the MeshBuilder class instead.
  25355. * 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.
  25356. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  25357. * The parameter `points` is an array successive Vector3.
  25358. * 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
  25359. * When updating an instance, remember that only point positions can change, not the number of points.
  25360. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25361. */
  25362. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  25363. if (scene === void 0) { scene = null; }
  25364. if (updatable === void 0) { updatable = false; }
  25365. if (instance === void 0) { instance = null; }
  25366. var options = {
  25367. points: points,
  25368. updatable: updatable,
  25369. instance: instance
  25370. };
  25371. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  25372. };
  25373. /**
  25374. * Creates a dashed line mesh.
  25375. * Please consider using the same method from the MeshBuilder class instead.
  25376. * 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.
  25377. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  25378. * The parameter `points` is an array successive Vector3.
  25379. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  25380. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  25381. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  25382. * 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
  25383. * When updating an instance, remember that only point positions can change, not the number of points.
  25384. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25385. */
  25386. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  25387. if (scene === void 0) { scene = null; }
  25388. var options = {
  25389. points: points,
  25390. dashSize: dashSize,
  25391. gapSize: gapSize,
  25392. dashNb: dashNb,
  25393. updatable: updatable,
  25394. instance: instance
  25395. };
  25396. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  25397. };
  25398. /**
  25399. * Creates a polygon mesh.
  25400. * Please consider using the same method from the MeshBuilder class instead.
  25401. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  25402. * 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.
  25403. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25404. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25405. * Remember you can only change the shape positions, not their number when updating a polygon.
  25406. */
  25407. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  25408. var options = {
  25409. shape: shape,
  25410. holes: holes,
  25411. updatable: updatable,
  25412. sideOrientation: sideOrientation
  25413. };
  25414. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  25415. };
  25416. /**
  25417. * Creates an extruded polygon mesh, with depth in the Y direction.
  25418. * Please consider using the same method from the MeshBuilder class instead.
  25419. */
  25420. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  25421. var options = {
  25422. shape: shape,
  25423. holes: holes,
  25424. depth: depth,
  25425. updatable: updatable,
  25426. sideOrientation: sideOrientation
  25427. };
  25428. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  25429. };
  25430. /**
  25431. * Creates an extruded shape mesh.
  25432. * 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.
  25433. * Please consider using the same method from the MeshBuilder class instead.
  25434. *
  25435. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  25436. * 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
  25437. * extruded along the Z axis.
  25438. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  25439. * 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.
  25440. * The parameter `scale` (float, default 1) is the value to scale the shape.
  25441. * 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
  25442. * 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
  25443. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  25444. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25445. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25446. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25447. */
  25448. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  25449. if (scene === void 0) { scene = null; }
  25450. var options = {
  25451. shape: shape,
  25452. path: path,
  25453. scale: scale,
  25454. rotation: rotation,
  25455. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  25456. sideOrientation: sideOrientation,
  25457. instance: instance,
  25458. updatable: updatable
  25459. };
  25460. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  25461. };
  25462. /**
  25463. * Creates an custom extruded shape mesh.
  25464. * 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.
  25465. * Please consider using the same method from the MeshBuilder class instead.
  25466. *
  25467. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  25468. * 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
  25469. * extruded along the Z axis.
  25470. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  25471. * 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
  25472. * and the distance of this point from the begining of the path :
  25473. * ```javascript
  25474. * var rotationFunction = function(i, distance) {
  25475. * // do things
  25476. * return rotationValue; }
  25477. * ```
  25478. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  25479. * 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
  25480. * and the distance of this point from the begining of the path :
  25481. * ```javascript
  25482. * var scaleFunction = function(i, distance) {
  25483. * // do things
  25484. * return scaleValue;}
  25485. * ```
  25486. * It must returns a float value that will be the scale value applied to the shape on each path point.
  25487. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  25488. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  25489. * 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
  25490. * 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
  25491. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  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.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  25497. var options = {
  25498. shape: shape,
  25499. path: path,
  25500. scaleFunction: scaleFunction,
  25501. rotationFunction: rotationFunction,
  25502. ribbonCloseArray: ribbonCloseArray,
  25503. ribbonClosePath: ribbonClosePath,
  25504. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  25505. sideOrientation: sideOrientation,
  25506. instance: instance,
  25507. updatable: updatable
  25508. };
  25509. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  25510. };
  25511. /**
  25512. * Creates lathe mesh.
  25513. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  25514. * Please consider using the same method from the MeshBuilder class instead.
  25515. * 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
  25516. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  25517. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  25518. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  25519. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25520. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25521. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25522. */
  25523. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  25524. var options = {
  25525. shape: shape,
  25526. radius: radius,
  25527. tessellation: tessellation,
  25528. sideOrientation: sideOrientation,
  25529. updatable: updatable
  25530. };
  25531. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  25532. };
  25533. /**
  25534. * Creates a plane mesh.
  25535. * Please consider using the same method from the MeshBuilder class instead.
  25536. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  25537. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25538. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25539. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25540. */
  25541. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  25542. var options = {
  25543. size: size,
  25544. width: size,
  25545. height: size,
  25546. sideOrientation: sideOrientation,
  25547. updatable: updatable
  25548. };
  25549. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  25550. };
  25551. /**
  25552. * Creates a ground mesh.
  25553. * Please consider using the same method from the MeshBuilder class instead.
  25554. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  25555. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  25556. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25557. */
  25558. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  25559. var options = {
  25560. width: width,
  25561. height: height,
  25562. subdivisions: subdivisions,
  25563. updatable: updatable
  25564. };
  25565. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  25566. };
  25567. /**
  25568. * Creates a tiled ground mesh.
  25569. * Please consider using the same method from the MeshBuilder class instead.
  25570. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  25571. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  25572. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  25573. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  25574. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  25575. * numbers of subdivisions on the ground width and height of each tile.
  25576. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25577. */
  25578. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  25579. var options = {
  25580. xmin: xmin,
  25581. zmin: zmin,
  25582. xmax: xmax,
  25583. zmax: zmax,
  25584. subdivisions: subdivisions,
  25585. precision: precision,
  25586. updatable: updatable
  25587. };
  25588. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  25589. };
  25590. /**
  25591. * Creates a ground mesh from a height map.
  25592. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  25593. * Please consider using the same method from the MeshBuilder class instead.
  25594. * The parameter `url` sets the URL of the height map image resource.
  25595. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  25596. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  25597. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  25598. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  25599. * 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).
  25600. * This function is passed the newly built mesh :
  25601. * ```javascript
  25602. * function(mesh) { // do things
  25603. * return; }
  25604. * ```
  25605. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25606. */
  25607. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  25608. var options = {
  25609. width: width,
  25610. height: height,
  25611. subdivisions: subdivisions,
  25612. minHeight: minHeight,
  25613. maxHeight: maxHeight,
  25614. updatable: updatable,
  25615. onReady: onReady
  25616. };
  25617. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  25618. };
  25619. /**
  25620. * Creates a tube mesh.
  25621. * 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.
  25622. * Please consider using the same method from the MeshBuilder class instead.
  25623. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  25624. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  25625. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  25626. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  25627. * 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.
  25628. * It must return a radius value (positive float) :
  25629. * ```javascript
  25630. * var radiusFunction = function(i, distance) {
  25631. * // do things
  25632. * return radius; }
  25633. * ```
  25634. * 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
  25635. * 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
  25636. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25637. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25638. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25639. */
  25640. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  25641. var options = {
  25642. path: path,
  25643. radius: radius,
  25644. tessellation: tessellation,
  25645. radiusFunction: radiusFunction,
  25646. arc: 1,
  25647. cap: cap,
  25648. updatable: updatable,
  25649. sideOrientation: sideOrientation,
  25650. instance: instance
  25651. };
  25652. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  25653. };
  25654. /**
  25655. * Creates a polyhedron mesh.
  25656. * Please consider using the same method from the MeshBuilder class instead.
  25657. * 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
  25658. * to choose the wanted type.
  25659. * The parameter `size` (positive float, default 1) sets the polygon size.
  25660. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  25661. * 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`.
  25662. * 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
  25663. * 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)`).
  25664. * 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
  25665. * 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.
  25666. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25667. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25668. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25669. */
  25670. Mesh.CreatePolyhedron = function (name, options, scene) {
  25671. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  25672. };
  25673. /**
  25674. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  25675. * Please consider using the same method from the MeshBuilder class instead.
  25676. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  25677. * 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`).
  25678. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  25679. * 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.
  25680. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25681. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25682. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25683. */
  25684. Mesh.CreateIcoSphere = function (name, options, scene) {
  25685. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  25686. };
  25687. /**
  25688. * Creates a decal mesh.
  25689. * Please consider using the same method from the MeshBuilder class instead.
  25690. * 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.
  25691. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  25692. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  25693. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  25694. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  25695. */
  25696. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  25697. var options = {
  25698. position: position,
  25699. normal: normal,
  25700. size: size,
  25701. angle: angle
  25702. };
  25703. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  25704. };
  25705. // Skeletons
  25706. /**
  25707. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25708. */
  25709. Mesh.prototype.setPositionsForCPUSkinning = function () {
  25710. if (!this._sourcePositions) {
  25711. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25712. if (!source) {
  25713. return this._sourcePositions;
  25714. }
  25715. this._sourcePositions = new Float32Array(source);
  25716. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  25717. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  25718. }
  25719. }
  25720. return this._sourcePositions;
  25721. };
  25722. /**
  25723. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25724. */
  25725. Mesh.prototype.setNormalsForCPUSkinning = function () {
  25726. if (!this._sourceNormals) {
  25727. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25728. if (!source) {
  25729. return this._sourceNormals;
  25730. }
  25731. this._sourceNormals = new Float32Array(source);
  25732. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  25733. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  25734. }
  25735. }
  25736. return this._sourceNormals;
  25737. };
  25738. /**
  25739. * Updates the vertex buffer by applying transformation from the bones.
  25740. * Returns the Mesh.
  25741. *
  25742. * @param {skeleton} skeleton to apply
  25743. */
  25744. Mesh.prototype.applySkeleton = function (skeleton) {
  25745. if (!this.geometry) {
  25746. return this;
  25747. }
  25748. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  25749. return this;
  25750. }
  25751. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  25752. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25753. return this;
  25754. }
  25755. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25756. return this;
  25757. }
  25758. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25759. return this;
  25760. }
  25761. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25762. return this;
  25763. }
  25764. if (!this._sourcePositions) {
  25765. var submeshes = this.subMeshes.slice();
  25766. this.setPositionsForCPUSkinning();
  25767. this.subMeshes = submeshes;
  25768. }
  25769. if (!this._sourceNormals) {
  25770. this.setNormalsForCPUSkinning();
  25771. }
  25772. // positionsData checks for not being Float32Array will only pass at most once
  25773. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25774. if (!positionsData) {
  25775. return this;
  25776. }
  25777. if (!(positionsData instanceof Float32Array)) {
  25778. positionsData = new Float32Array(positionsData);
  25779. }
  25780. // normalsData checks for not being Float32Array will only pass at most once
  25781. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25782. if (!normalsData) {
  25783. return this;
  25784. }
  25785. if (!(normalsData instanceof Float32Array)) {
  25786. normalsData = new Float32Array(normalsData);
  25787. }
  25788. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  25789. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  25790. if (!matricesWeightsData || !matricesIndicesData) {
  25791. return this;
  25792. }
  25793. var needExtras = this.numBoneInfluencers > 4;
  25794. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  25795. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  25796. var skeletonMatrices = skeleton.getTransformMatrices(this);
  25797. var tempVector3 = BABYLON.Vector3.Zero();
  25798. var finalMatrix = new BABYLON.Matrix();
  25799. var tempMatrix = new BABYLON.Matrix();
  25800. var matWeightIdx = 0;
  25801. var inf;
  25802. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  25803. var weight;
  25804. for (inf = 0; inf < 4; inf++) {
  25805. weight = matricesWeightsData[matWeightIdx + inf];
  25806. if (weight > 0) {
  25807. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25808. finalMatrix.addToSelf(tempMatrix);
  25809. }
  25810. else
  25811. break;
  25812. }
  25813. if (needExtras) {
  25814. for (inf = 0; inf < 4; inf++) {
  25815. weight = matricesWeightsExtraData[matWeightIdx + inf];
  25816. if (weight > 0) {
  25817. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25818. finalMatrix.addToSelf(tempMatrix);
  25819. }
  25820. else
  25821. break;
  25822. }
  25823. }
  25824. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  25825. tempVector3.toArray(positionsData, index);
  25826. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  25827. tempVector3.toArray(normalsData, index);
  25828. finalMatrix.reset();
  25829. }
  25830. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  25831. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  25832. return this;
  25833. };
  25834. // Tools
  25835. /**
  25836. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  25837. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  25838. */
  25839. Mesh.MinMax = function (meshes) {
  25840. var minVector = null;
  25841. var maxVector = null;
  25842. meshes.forEach(function (mesh, index, array) {
  25843. var boundingInfo = mesh.getBoundingInfo();
  25844. var boundingBox = boundingInfo.boundingBox;
  25845. if (!minVector || !maxVector) {
  25846. minVector = boundingBox.minimumWorld;
  25847. maxVector = boundingBox.maximumWorld;
  25848. }
  25849. else {
  25850. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  25851. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  25852. }
  25853. });
  25854. if (!minVector || !maxVector) {
  25855. return {
  25856. min: BABYLON.Vector3.Zero(),
  25857. max: BABYLON.Vector3.Zero()
  25858. };
  25859. }
  25860. return {
  25861. min: minVector,
  25862. max: maxVector
  25863. };
  25864. };
  25865. /**
  25866. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  25867. */
  25868. Mesh.Center = function (meshesOrMinMaxVector) {
  25869. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  25870. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  25871. };
  25872. /**
  25873. * Merge the array of meshes into a single mesh for performance reasons.
  25874. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  25875. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  25876. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  25877. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  25878. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  25879. */
  25880. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  25881. if (disposeSource === void 0) { disposeSource = true; }
  25882. var index;
  25883. if (!allow32BitsIndices) {
  25884. var totalVertices = 0;
  25885. // Counting vertices
  25886. for (index = 0; index < meshes.length; index++) {
  25887. if (meshes[index]) {
  25888. totalVertices += meshes[index].getTotalVertices();
  25889. if (totalVertices > 65536) {
  25890. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  25891. return null;
  25892. }
  25893. }
  25894. }
  25895. }
  25896. // Merge
  25897. var vertexData = null;
  25898. var otherVertexData;
  25899. var indiceArray = new Array();
  25900. var source = null;
  25901. for (index = 0; index < meshes.length; index++) {
  25902. if (meshes[index]) {
  25903. meshes[index].computeWorldMatrix(true);
  25904. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  25905. otherVertexData.transform(meshes[index].getWorldMatrix());
  25906. if (vertexData) {
  25907. vertexData.merge(otherVertexData);
  25908. }
  25909. else {
  25910. vertexData = otherVertexData;
  25911. source = meshes[index];
  25912. }
  25913. if (subdivideWithSubMeshes) {
  25914. indiceArray.push(meshes[index].getTotalIndices());
  25915. }
  25916. }
  25917. }
  25918. source = source;
  25919. if (!meshSubclass) {
  25920. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  25921. }
  25922. vertexData.applyToMesh(meshSubclass);
  25923. // Setting properties
  25924. meshSubclass.material = source.material;
  25925. meshSubclass.checkCollisions = source.checkCollisions;
  25926. // Cleaning
  25927. if (disposeSource) {
  25928. for (index = 0; index < meshes.length; index++) {
  25929. if (meshes[index]) {
  25930. meshes[index].dispose();
  25931. }
  25932. }
  25933. }
  25934. // Subdivide
  25935. if (subdivideWithSubMeshes) {
  25936. //-- Suppresions du submesh global
  25937. meshSubclass.releaseSubMeshes();
  25938. index = 0;
  25939. var offset = 0;
  25940. //-- aplique la subdivision en fonction du tableau d'indices
  25941. while (index < indiceArray.length) {
  25942. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  25943. offset += indiceArray[index];
  25944. index++;
  25945. }
  25946. }
  25947. return meshSubclass;
  25948. };
  25949. // Consts
  25950. Mesh._FRONTSIDE = 0;
  25951. Mesh._BACKSIDE = 1;
  25952. Mesh._DOUBLESIDE = 2;
  25953. Mesh._DEFAULTSIDE = 0;
  25954. Mesh._NO_CAP = 0;
  25955. Mesh._CAP_START = 1;
  25956. Mesh._CAP_END = 2;
  25957. Mesh._CAP_ALL = 3;
  25958. return Mesh;
  25959. }(BABYLON.AbstractMesh));
  25960. BABYLON.Mesh = Mesh;
  25961. })(BABYLON || (BABYLON = {}));
  25962. //# sourceMappingURL=babylon.mesh.js.map
  25963. var BABYLON;
  25964. (function (BABYLON) {
  25965. var BaseSubMesh = /** @class */ (function () {
  25966. function BaseSubMesh() {
  25967. }
  25968. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  25969. get: function () {
  25970. return this._materialEffect;
  25971. },
  25972. enumerable: true,
  25973. configurable: true
  25974. });
  25975. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  25976. if (defines === void 0) { defines = null; }
  25977. if (this._materialEffect === effect) {
  25978. if (!effect) {
  25979. this._materialDefines = null;
  25980. }
  25981. return;
  25982. }
  25983. this._materialDefines = defines;
  25984. this._materialEffect = effect;
  25985. };
  25986. return BaseSubMesh;
  25987. }());
  25988. BABYLON.BaseSubMesh = BaseSubMesh;
  25989. var SubMesh = /** @class */ (function (_super) {
  25990. __extends(SubMesh, _super);
  25991. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  25992. if (createBoundingBox === void 0) { createBoundingBox = true; }
  25993. var _this = _super.call(this) || this;
  25994. _this.materialIndex = materialIndex;
  25995. _this.verticesStart = verticesStart;
  25996. _this.verticesCount = verticesCount;
  25997. _this.indexStart = indexStart;
  25998. _this.indexCount = indexCount;
  25999. _this._renderId = 0;
  26000. _this._mesh = mesh;
  26001. _this._renderingMesh = renderingMesh || mesh;
  26002. mesh.subMeshes.push(_this);
  26003. _this._trianglePlanes = [];
  26004. _this._id = mesh.subMeshes.length - 1;
  26005. if (createBoundingBox) {
  26006. _this.refreshBoundingInfo();
  26007. mesh.computeWorldMatrix(true);
  26008. }
  26009. return _this;
  26010. }
  26011. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  26012. if (createBoundingBox === void 0) { createBoundingBox = true; }
  26013. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  26014. };
  26015. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  26016. get: function () {
  26017. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  26018. },
  26019. enumerable: true,
  26020. configurable: true
  26021. });
  26022. /**
  26023. * Returns the submesh BoudingInfo object.
  26024. */
  26025. SubMesh.prototype.getBoundingInfo = function () {
  26026. if (this.IsGlobal) {
  26027. return this._mesh.getBoundingInfo();
  26028. }
  26029. return this._boundingInfo;
  26030. };
  26031. /**
  26032. * Sets the submesh BoundingInfo.
  26033. * Return the SubMesh.
  26034. */
  26035. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  26036. this._boundingInfo = boundingInfo;
  26037. return this;
  26038. };
  26039. /**
  26040. * Returns the mesh of the current submesh.
  26041. */
  26042. SubMesh.prototype.getMesh = function () {
  26043. return this._mesh;
  26044. };
  26045. /**
  26046. * Returns the rendering mesh of the submesh.
  26047. */
  26048. SubMesh.prototype.getRenderingMesh = function () {
  26049. return this._renderingMesh;
  26050. };
  26051. /**
  26052. * Returns the submesh material.
  26053. */
  26054. SubMesh.prototype.getMaterial = function () {
  26055. var rootMaterial = this._renderingMesh.material;
  26056. if (rootMaterial && rootMaterial.getSubMaterial) {
  26057. var multiMaterial = rootMaterial;
  26058. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  26059. if (this._currentMaterial !== effectiveMaterial) {
  26060. this._currentMaterial = effectiveMaterial;
  26061. this._materialDefines = null;
  26062. }
  26063. return effectiveMaterial;
  26064. }
  26065. if (!rootMaterial) {
  26066. return this._mesh.getScene().defaultMaterial;
  26067. }
  26068. return rootMaterial;
  26069. };
  26070. // Methods
  26071. /**
  26072. * Sets a new updated BoundingInfo object to the submesh.
  26073. * Returns the SubMesh.
  26074. */
  26075. SubMesh.prototype.refreshBoundingInfo = function () {
  26076. this._lastColliderWorldVertices = null;
  26077. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  26078. return this;
  26079. }
  26080. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26081. if (!data) {
  26082. this._boundingInfo = this._mesh.getBoundingInfo();
  26083. return this;
  26084. }
  26085. var indices = this._renderingMesh.getIndices();
  26086. var extend;
  26087. //is this the only submesh?
  26088. if (this.indexStart === 0 && this.indexCount === indices.length) {
  26089. var boundingInfo = this._renderingMesh.getBoundingInfo();
  26090. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  26091. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  26092. }
  26093. else {
  26094. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  26095. }
  26096. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26097. return this;
  26098. };
  26099. SubMesh.prototype._checkCollision = function (collider) {
  26100. var boundingInfo = this._renderingMesh.getBoundingInfo();
  26101. return boundingInfo._checkCollision(collider);
  26102. };
  26103. /**
  26104. * Updates the submesh BoundingInfo.
  26105. * Returns the Submesh.
  26106. */
  26107. SubMesh.prototype.updateBoundingInfo = function (world) {
  26108. var boundingInfo = this.getBoundingInfo();
  26109. if (!boundingInfo) {
  26110. this.refreshBoundingInfo();
  26111. boundingInfo = this.getBoundingInfo();
  26112. }
  26113. boundingInfo.update(world);
  26114. return this;
  26115. };
  26116. /**
  26117. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  26118. * Boolean returned.
  26119. */
  26120. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  26121. var boundingInfo = this.getBoundingInfo();
  26122. if (!boundingInfo) {
  26123. return false;
  26124. }
  26125. return boundingInfo.isInFrustum(frustumPlanes);
  26126. };
  26127. /**
  26128. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  26129. * Boolean returned.
  26130. */
  26131. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  26132. var boundingInfo = this.getBoundingInfo();
  26133. if (!boundingInfo) {
  26134. return false;
  26135. }
  26136. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  26137. };
  26138. /**
  26139. * Renders the submesh.
  26140. * Returns it.
  26141. */
  26142. SubMesh.prototype.render = function (enableAlphaMode) {
  26143. this._renderingMesh.render(this, enableAlphaMode);
  26144. return this;
  26145. };
  26146. /**
  26147. * Returns a new Index Buffer.
  26148. * Type returned : WebGLBuffer.
  26149. */
  26150. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  26151. if (!this._linesIndexBuffer) {
  26152. var linesIndices = [];
  26153. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  26154. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  26155. }
  26156. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  26157. this.linesIndexCount = linesIndices.length;
  26158. }
  26159. return this._linesIndexBuffer;
  26160. };
  26161. /**
  26162. * True is the passed Ray intersects the submesh bounding box.
  26163. * Boolean returned.
  26164. */
  26165. SubMesh.prototype.canIntersects = function (ray) {
  26166. var boundingInfo = this.getBoundingInfo();
  26167. if (!boundingInfo) {
  26168. return false;
  26169. }
  26170. return ray.intersectsBox(boundingInfo.boundingBox);
  26171. };
  26172. /**
  26173. * Returns an object IntersectionInfo.
  26174. */
  26175. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  26176. var intersectInfo = null;
  26177. // LineMesh first as it's also a Mesh...
  26178. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  26179. var lineMesh = this._mesh;
  26180. // Line test
  26181. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  26182. var p0 = positions[indices[index]];
  26183. var p1 = positions[indices[index + 1]];
  26184. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  26185. if (length < 0) {
  26186. continue;
  26187. }
  26188. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  26189. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  26190. if (fastCheck) {
  26191. break;
  26192. }
  26193. }
  26194. }
  26195. }
  26196. else {
  26197. // Triangles test
  26198. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  26199. var p0 = positions[indices[index]];
  26200. var p1 = positions[indices[index + 1]];
  26201. var p2 = positions[indices[index + 2]];
  26202. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  26203. if (currentIntersectInfo) {
  26204. if (currentIntersectInfo.distance < 0) {
  26205. continue;
  26206. }
  26207. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  26208. intersectInfo = currentIntersectInfo;
  26209. intersectInfo.faceId = index / 3;
  26210. if (fastCheck) {
  26211. break;
  26212. }
  26213. }
  26214. }
  26215. }
  26216. }
  26217. return intersectInfo;
  26218. };
  26219. SubMesh.prototype._rebuild = function () {
  26220. if (this._linesIndexBuffer) {
  26221. this._linesIndexBuffer = null;
  26222. }
  26223. };
  26224. // Clone
  26225. /**
  26226. * Creates a new Submesh from the passed Mesh.
  26227. */
  26228. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  26229. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  26230. if (!this.IsGlobal) {
  26231. var boundingInfo = this.getBoundingInfo();
  26232. if (!boundingInfo) {
  26233. return result;
  26234. }
  26235. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  26236. }
  26237. return result;
  26238. };
  26239. // Dispose
  26240. /**
  26241. * Disposes the Submesh.
  26242. * Returns nothing.
  26243. */
  26244. SubMesh.prototype.dispose = function () {
  26245. if (this._linesIndexBuffer) {
  26246. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  26247. this._linesIndexBuffer = null;
  26248. }
  26249. // Remove from mesh
  26250. var index = this._mesh.subMeshes.indexOf(this);
  26251. this._mesh.subMeshes.splice(index, 1);
  26252. };
  26253. // Statics
  26254. /**
  26255. * Creates a new Submesh from the passed parameters :
  26256. * - materialIndex (integer) : the index of the main mesh material.
  26257. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  26258. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  26259. * - mesh (Mesh) : the main mesh to create the submesh from.
  26260. * - renderingMesh (optional Mesh) : rendering mesh.
  26261. */
  26262. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  26263. var minVertexIndex = Number.MAX_VALUE;
  26264. var maxVertexIndex = -Number.MAX_VALUE;
  26265. renderingMesh = (renderingMesh || mesh);
  26266. var indices = renderingMesh.getIndices();
  26267. for (var index = startIndex; index < startIndex + indexCount; index++) {
  26268. var vertexIndex = indices[index];
  26269. if (vertexIndex < minVertexIndex)
  26270. minVertexIndex = vertexIndex;
  26271. if (vertexIndex > maxVertexIndex)
  26272. maxVertexIndex = vertexIndex;
  26273. }
  26274. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  26275. };
  26276. return SubMesh;
  26277. }(BaseSubMesh));
  26278. BABYLON.SubMesh = SubMesh;
  26279. })(BABYLON || (BABYLON = {}));
  26280. //# sourceMappingURL=babylon.subMesh.js.map
  26281. var BABYLON;
  26282. (function (BABYLON) {
  26283. var EffectFallbacks = /** @class */ (function () {
  26284. function EffectFallbacks() {
  26285. this._defines = {};
  26286. this._currentRank = 32;
  26287. this._maxRank = -1;
  26288. }
  26289. EffectFallbacks.prototype.unBindMesh = function () {
  26290. this._mesh = null;
  26291. };
  26292. EffectFallbacks.prototype.addFallback = function (rank, define) {
  26293. if (!this._defines[rank]) {
  26294. if (rank < this._currentRank) {
  26295. this._currentRank = rank;
  26296. }
  26297. if (rank > this._maxRank) {
  26298. this._maxRank = rank;
  26299. }
  26300. this._defines[rank] = new Array();
  26301. }
  26302. this._defines[rank].push(define);
  26303. };
  26304. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  26305. this._mesh = mesh;
  26306. if (rank < this._currentRank) {
  26307. this._currentRank = rank;
  26308. }
  26309. if (rank > this._maxRank) {
  26310. this._maxRank = rank;
  26311. }
  26312. };
  26313. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  26314. get: function () {
  26315. return this._currentRank <= this._maxRank;
  26316. },
  26317. enumerable: true,
  26318. configurable: true
  26319. });
  26320. EffectFallbacks.prototype.reduce = function (currentDefines) {
  26321. // First we try to switch to CPU skinning
  26322. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  26323. this._mesh.computeBonesUsingShaders = false;
  26324. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  26325. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  26326. var scene = this._mesh.getScene();
  26327. for (var index = 0; index < scene.meshes.length; index++) {
  26328. var otherMesh = scene.meshes[index];
  26329. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  26330. otherMesh.computeBonesUsingShaders = false;
  26331. }
  26332. }
  26333. }
  26334. else {
  26335. var currentFallbacks = this._defines[this._currentRank];
  26336. if (currentFallbacks) {
  26337. for (var index = 0; index < currentFallbacks.length; index++) {
  26338. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  26339. }
  26340. }
  26341. this._currentRank++;
  26342. }
  26343. return currentDefines;
  26344. };
  26345. return EffectFallbacks;
  26346. }());
  26347. BABYLON.EffectFallbacks = EffectFallbacks;
  26348. var EffectCreationOptions = /** @class */ (function () {
  26349. function EffectCreationOptions() {
  26350. }
  26351. return EffectCreationOptions;
  26352. }());
  26353. BABYLON.EffectCreationOptions = EffectCreationOptions;
  26354. var Effect = /** @class */ (function () {
  26355. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  26356. if (samplers === void 0) { samplers = null; }
  26357. if (defines === void 0) { defines = null; }
  26358. if (fallbacks === void 0) { fallbacks = null; }
  26359. if (onCompiled === void 0) { onCompiled = null; }
  26360. if (onError === void 0) { onError = null; }
  26361. var _this = this;
  26362. this.uniqueId = 0;
  26363. this.onCompileObservable = new BABYLON.Observable();
  26364. this.onErrorObservable = new BABYLON.Observable();
  26365. this.onBindObservable = new BABYLON.Observable();
  26366. this._uniformBuffersNames = {};
  26367. this._isReady = false;
  26368. this._compilationError = "";
  26369. this.name = baseName;
  26370. if (attributesNamesOrOptions.attributes) {
  26371. var options = attributesNamesOrOptions;
  26372. this._engine = uniformsNamesOrEngine;
  26373. this._attributesNames = options.attributes;
  26374. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  26375. this._samplers = options.samplers;
  26376. this.defines = options.defines;
  26377. this.onError = options.onError;
  26378. this.onCompiled = options.onCompiled;
  26379. this._fallbacks = options.fallbacks;
  26380. this._indexParameters = options.indexParameters;
  26381. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  26382. if (options.uniformBuffersNames) {
  26383. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  26384. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  26385. }
  26386. }
  26387. }
  26388. else {
  26389. this._engine = engine;
  26390. this.defines = defines;
  26391. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  26392. this._samplers = samplers;
  26393. this._attributesNames = attributesNamesOrOptions;
  26394. this.onError = onError;
  26395. this.onCompiled = onCompiled;
  26396. this._indexParameters = indexParameters;
  26397. this._fallbacks = fallbacks;
  26398. }
  26399. this.uniqueId = Effect._uniqueIdSeed++;
  26400. var vertexSource;
  26401. var fragmentSource;
  26402. if (baseName.vertexElement) {
  26403. vertexSource = document.getElementById(baseName.vertexElement);
  26404. if (!vertexSource) {
  26405. vertexSource = baseName.vertexElement;
  26406. }
  26407. }
  26408. else {
  26409. vertexSource = baseName.vertex || baseName;
  26410. }
  26411. if (baseName.fragmentElement) {
  26412. fragmentSource = document.getElementById(baseName.fragmentElement);
  26413. if (!fragmentSource) {
  26414. fragmentSource = baseName.fragmentElement;
  26415. }
  26416. }
  26417. else {
  26418. fragmentSource = baseName.fragment || baseName;
  26419. }
  26420. this._loadVertexShader(vertexSource, function (vertexCode) {
  26421. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  26422. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  26423. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  26424. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  26425. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  26426. if (baseName) {
  26427. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  26428. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  26429. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  26430. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  26431. }
  26432. else {
  26433. _this._vertexSourceCode = migratedVertexCode;
  26434. _this._fragmentSourceCode = migratedFragmentCode;
  26435. }
  26436. _this._prepareEffect();
  26437. });
  26438. });
  26439. });
  26440. });
  26441. });
  26442. });
  26443. }
  26444. Object.defineProperty(Effect.prototype, "key", {
  26445. get: function () {
  26446. return this._key;
  26447. },
  26448. enumerable: true,
  26449. configurable: true
  26450. });
  26451. // Properties
  26452. Effect.prototype.isReady = function () {
  26453. return this._isReady;
  26454. };
  26455. Effect.prototype.getEngine = function () {
  26456. return this._engine;
  26457. };
  26458. Effect.prototype.getProgram = function () {
  26459. return this._program;
  26460. };
  26461. Effect.prototype.getAttributesNames = function () {
  26462. return this._attributesNames;
  26463. };
  26464. Effect.prototype.getAttributeLocation = function (index) {
  26465. return this._attributes[index];
  26466. };
  26467. Effect.prototype.getAttributeLocationByName = function (name) {
  26468. var index = this._attributesNames.indexOf(name);
  26469. return this._attributes[index];
  26470. };
  26471. Effect.prototype.getAttributesCount = function () {
  26472. return this._attributes.length;
  26473. };
  26474. Effect.prototype.getUniformIndex = function (uniformName) {
  26475. return this._uniformsNames.indexOf(uniformName);
  26476. };
  26477. Effect.prototype.getUniform = function (uniformName) {
  26478. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  26479. };
  26480. Effect.prototype.getSamplers = function () {
  26481. return this._samplers;
  26482. };
  26483. Effect.prototype.getCompilationError = function () {
  26484. return this._compilationError;
  26485. };
  26486. // Methods
  26487. Effect.prototype.executeWhenCompiled = function (func) {
  26488. if (this.isReady()) {
  26489. func(this);
  26490. return;
  26491. }
  26492. this.onCompileObservable.add(function (effect) {
  26493. func(effect);
  26494. });
  26495. };
  26496. Effect.prototype._loadVertexShader = function (vertex, callback) {
  26497. if (BABYLON.Tools.IsWindowObjectExist()) {
  26498. // DOM element ?
  26499. if (vertex instanceof HTMLElement) {
  26500. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  26501. callback(vertexCode);
  26502. return;
  26503. }
  26504. }
  26505. // Base64 encoded ?
  26506. if (vertex.substr(0, 7) === "base64:") {
  26507. var vertexBinary = window.atob(vertex.substr(7));
  26508. callback(vertexBinary);
  26509. return;
  26510. }
  26511. // Is in local store ?
  26512. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  26513. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  26514. return;
  26515. }
  26516. var vertexShaderUrl;
  26517. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  26518. vertexShaderUrl = vertex;
  26519. }
  26520. else {
  26521. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  26522. }
  26523. // Vertex shader
  26524. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  26525. };
  26526. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  26527. if (BABYLON.Tools.IsWindowObjectExist()) {
  26528. // DOM element ?
  26529. if (fragment instanceof HTMLElement) {
  26530. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  26531. callback(fragmentCode);
  26532. return;
  26533. }
  26534. }
  26535. // Base64 encoded ?
  26536. if (fragment.substr(0, 7) === "base64:") {
  26537. var fragmentBinary = window.atob(fragment.substr(7));
  26538. callback(fragmentBinary);
  26539. return;
  26540. }
  26541. // Is in local store ?
  26542. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  26543. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  26544. return;
  26545. }
  26546. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  26547. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  26548. return;
  26549. }
  26550. var fragmentShaderUrl;
  26551. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  26552. fragmentShaderUrl = fragment;
  26553. }
  26554. else {
  26555. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  26556. }
  26557. // Fragment shader
  26558. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  26559. };
  26560. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  26561. // Rebuild shaders source code
  26562. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  26563. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  26564. vertexCode = prefix + vertexCode;
  26565. fragmentCode = prefix + fragmentCode;
  26566. // Number lines of shaders source code
  26567. var i = 2;
  26568. var regex = /\n/gm;
  26569. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  26570. i = 2;
  26571. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  26572. // Dump shaders name and formatted source code
  26573. if (this.name.vertexElement) {
  26574. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  26575. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  26576. }
  26577. else if (this.name.vertex) {
  26578. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  26579. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  26580. }
  26581. else {
  26582. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  26583. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  26584. }
  26585. };
  26586. ;
  26587. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  26588. var preparedSourceCode = this._processPrecision(sourceCode);
  26589. if (this._engine.webGLVersion == 1) {
  26590. callback(preparedSourceCode);
  26591. return;
  26592. }
  26593. // Already converted
  26594. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  26595. callback(preparedSourceCode.replace("#version 300 es", ""));
  26596. return;
  26597. }
  26598. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  26599. // Remove extensions
  26600. // #extension GL_OES_standard_derivatives : enable
  26601. // #extension GL_EXT_shader_texture_lod : enable
  26602. // #extension GL_EXT_frag_depth : enable
  26603. // #extension GL_EXT_draw_buffers : require
  26604. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  26605. var result = preparedSourceCode.replace(regex, "");
  26606. // Migrate to GLSL v300
  26607. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  26608. result = result.replace(/attribute[ \t]/g, "in ");
  26609. result = result.replace(/[ \t]attribute/g, " in");
  26610. if (isFragment) {
  26611. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  26612. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  26613. result = result.replace(/texture2D\s*\(/g, "texture(");
  26614. result = result.replace(/textureCube\s*\(/g, "texture(");
  26615. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  26616. result = result.replace(/gl_FragColor/g, "glFragColor");
  26617. result = result.replace(/gl_FragData/g, "glFragData");
  26618. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  26619. }
  26620. callback(result);
  26621. };
  26622. Effect.prototype._processIncludes = function (sourceCode, callback) {
  26623. var _this = this;
  26624. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  26625. var match = regex.exec(sourceCode);
  26626. var returnValue = new String(sourceCode);
  26627. while (match != null) {
  26628. var includeFile = match[1];
  26629. // Uniform declaration
  26630. if (includeFile.indexOf("__decl__") !== -1) {
  26631. includeFile = includeFile.replace(/__decl__/, "");
  26632. if (this._engine.supportsUniformBuffers) {
  26633. includeFile = includeFile.replace(/Vertex/, "Ubo");
  26634. includeFile = includeFile.replace(/Fragment/, "Ubo");
  26635. }
  26636. includeFile = includeFile + "Declaration";
  26637. }
  26638. if (Effect.IncludesShadersStore[includeFile]) {
  26639. // Substitution
  26640. var includeContent = Effect.IncludesShadersStore[includeFile];
  26641. if (match[2]) {
  26642. var splits = match[3].split(",");
  26643. for (var index = 0; index < splits.length; index += 2) {
  26644. var source = new RegExp(splits[index], "g");
  26645. var dest = splits[index + 1];
  26646. includeContent = includeContent.replace(source, dest);
  26647. }
  26648. }
  26649. if (match[4]) {
  26650. var indexString = match[5];
  26651. if (indexString.indexOf("..") !== -1) {
  26652. var indexSplits = indexString.split("..");
  26653. var minIndex = parseInt(indexSplits[0]);
  26654. var maxIndex = parseInt(indexSplits[1]);
  26655. var sourceIncludeContent = includeContent.slice(0);
  26656. includeContent = "";
  26657. if (isNaN(maxIndex)) {
  26658. maxIndex = this._indexParameters[indexSplits[1]];
  26659. }
  26660. for (var i = minIndex; i < maxIndex; i++) {
  26661. if (!this._engine.supportsUniformBuffers) {
  26662. // Ubo replacement
  26663. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  26664. return p1 + "{X}";
  26665. });
  26666. }
  26667. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  26668. }
  26669. }
  26670. else {
  26671. if (!this._engine.supportsUniformBuffers) {
  26672. // Ubo replacement
  26673. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  26674. return p1 + "{X}";
  26675. });
  26676. }
  26677. includeContent = includeContent.replace(/\{X\}/g, indexString);
  26678. }
  26679. }
  26680. // Replace
  26681. returnValue = returnValue.replace(match[0], includeContent);
  26682. }
  26683. else {
  26684. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  26685. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  26686. Effect.IncludesShadersStore[includeFile] = fileContent;
  26687. _this._processIncludes(returnValue, callback);
  26688. });
  26689. return;
  26690. }
  26691. match = regex.exec(sourceCode);
  26692. }
  26693. callback(returnValue);
  26694. };
  26695. Effect.prototype._processPrecision = function (source) {
  26696. if (source.indexOf("precision highp float") === -1) {
  26697. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  26698. source = "precision mediump float;\n" + source;
  26699. }
  26700. else {
  26701. source = "precision highp float;\n" + source;
  26702. }
  26703. }
  26704. else {
  26705. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  26706. source = source.replace("precision highp float", "precision mediump float");
  26707. }
  26708. }
  26709. return source;
  26710. };
  26711. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  26712. var _this = this;
  26713. this._isReady = false;
  26714. this._vertexSourceCodeOverride = vertexSourceCode;
  26715. this._fragmentSourceCodeOverride = fragmentSourceCode;
  26716. this.onError = function (effect, error) {
  26717. if (onError) {
  26718. onError(error);
  26719. }
  26720. };
  26721. this.onCompiled = function () {
  26722. var scenes = _this.getEngine().scenes;
  26723. for (var i = 0; i < scenes.length; i++) {
  26724. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26725. }
  26726. if (onCompiled) {
  26727. onCompiled(_this._program);
  26728. }
  26729. };
  26730. this._fallbacks = null;
  26731. this._prepareEffect();
  26732. };
  26733. Effect.prototype._prepareEffect = function () {
  26734. var attributesNames = this._attributesNames;
  26735. var defines = this.defines;
  26736. var fallbacks = this._fallbacks;
  26737. this._valueCache = {};
  26738. var previousProgram = this._program;
  26739. try {
  26740. var engine = this._engine;
  26741. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  26742. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  26743. }
  26744. else {
  26745. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  26746. }
  26747. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  26748. if (engine.webGLVersion > 1) {
  26749. for (var name in this._uniformBuffersNames) {
  26750. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  26751. }
  26752. }
  26753. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  26754. this._attributes = engine.getAttributes(this._program, attributesNames);
  26755. var index;
  26756. for (index = 0; index < this._samplers.length; index++) {
  26757. var sampler = this.getUniform(this._samplers[index]);
  26758. if (sampler == null) {
  26759. this._samplers.splice(index, 1);
  26760. index--;
  26761. }
  26762. }
  26763. engine.bindSamplers(this);
  26764. this._compilationError = "";
  26765. this._isReady = true;
  26766. if (this.onCompiled) {
  26767. this.onCompiled(this);
  26768. }
  26769. this.onCompileObservable.notifyObservers(this);
  26770. this.onCompileObservable.clear();
  26771. // Unbind mesh reference in fallbacks
  26772. if (this._fallbacks) {
  26773. this._fallbacks.unBindMesh();
  26774. }
  26775. if (previousProgram) {
  26776. this.getEngine()._deleteProgram(previousProgram);
  26777. }
  26778. }
  26779. catch (e) {
  26780. this._compilationError = e.message;
  26781. // Let's go through fallbacks then
  26782. BABYLON.Tools.Error("Unable to compile effect:");
  26783. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  26784. return " " + uniform;
  26785. }));
  26786. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  26787. return " " + attribute;
  26788. }));
  26789. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  26790. BABYLON.Tools.Error("Error: " + this._compilationError);
  26791. if (previousProgram) {
  26792. this._program = previousProgram;
  26793. this._isReady = true;
  26794. if (this.onError) {
  26795. this.onError(this, this._compilationError);
  26796. }
  26797. this.onErrorObservable.notifyObservers(this);
  26798. }
  26799. if (fallbacks && fallbacks.isMoreFallbacks) {
  26800. BABYLON.Tools.Error("Trying next fallback.");
  26801. this.defines = fallbacks.reduce(this.defines);
  26802. this._prepareEffect();
  26803. }
  26804. else {
  26805. if (this.onError) {
  26806. this.onError(this, this._compilationError);
  26807. }
  26808. this.onErrorObservable.notifyObservers(this);
  26809. this.onErrorObservable.clear();
  26810. // Unbind mesh reference in fallbacks
  26811. if (this._fallbacks) {
  26812. this._fallbacks.unBindMesh();
  26813. }
  26814. }
  26815. }
  26816. };
  26817. Object.defineProperty(Effect.prototype, "isSupported", {
  26818. get: function () {
  26819. return this._compilationError === "";
  26820. },
  26821. enumerable: true,
  26822. configurable: true
  26823. });
  26824. Effect.prototype._bindTexture = function (channel, texture) {
  26825. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  26826. };
  26827. Effect.prototype.setTexture = function (channel, texture) {
  26828. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  26829. };
  26830. Effect.prototype.setTextureArray = function (channel, textures) {
  26831. if (this._samplers.indexOf(channel + "Ex") === -1) {
  26832. var initialPos = this._samplers.indexOf(channel);
  26833. for (var index = 1; index < textures.length; index++) {
  26834. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  26835. }
  26836. }
  26837. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  26838. };
  26839. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  26840. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  26841. };
  26842. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  26843. var cache = this._valueCache[uniformName];
  26844. var flag = matrix.updateFlag;
  26845. if (cache !== undefined && cache === flag) {
  26846. return false;
  26847. }
  26848. this._valueCache[uniformName] = flag;
  26849. return true;
  26850. };
  26851. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  26852. var cache = this._valueCache[uniformName];
  26853. if (!cache) {
  26854. cache = [x, y];
  26855. this._valueCache[uniformName] = cache;
  26856. return true;
  26857. }
  26858. var changed = false;
  26859. if (cache[0] !== x) {
  26860. cache[0] = x;
  26861. changed = true;
  26862. }
  26863. if (cache[1] !== y) {
  26864. cache[1] = y;
  26865. changed = true;
  26866. }
  26867. return changed;
  26868. };
  26869. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  26870. var cache = this._valueCache[uniformName];
  26871. if (!cache) {
  26872. cache = [x, y, z];
  26873. this._valueCache[uniformName] = cache;
  26874. return true;
  26875. }
  26876. var changed = false;
  26877. if (cache[0] !== x) {
  26878. cache[0] = x;
  26879. changed = true;
  26880. }
  26881. if (cache[1] !== y) {
  26882. cache[1] = y;
  26883. changed = true;
  26884. }
  26885. if (cache[2] !== z) {
  26886. cache[2] = z;
  26887. changed = true;
  26888. }
  26889. return changed;
  26890. };
  26891. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  26892. var cache = this._valueCache[uniformName];
  26893. if (!cache) {
  26894. cache = [x, y, z, w];
  26895. this._valueCache[uniformName] = cache;
  26896. return true;
  26897. }
  26898. var changed = false;
  26899. if (cache[0] !== x) {
  26900. cache[0] = x;
  26901. changed = true;
  26902. }
  26903. if (cache[1] !== y) {
  26904. cache[1] = y;
  26905. changed = true;
  26906. }
  26907. if (cache[2] !== z) {
  26908. cache[2] = z;
  26909. changed = true;
  26910. }
  26911. if (cache[3] !== w) {
  26912. cache[3] = w;
  26913. changed = true;
  26914. }
  26915. return changed;
  26916. };
  26917. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  26918. var bufferName = this._uniformBuffersNames[name];
  26919. if (Effect._baseCache[bufferName] === buffer) {
  26920. return;
  26921. }
  26922. Effect._baseCache[bufferName] = buffer;
  26923. this._engine.bindUniformBufferBase(buffer, bufferName);
  26924. };
  26925. Effect.prototype.bindUniformBlock = function (blockName, index) {
  26926. this._engine.bindUniformBlock(this._program, blockName, index);
  26927. };
  26928. Effect.prototype.setIntArray = function (uniformName, array) {
  26929. this._valueCache[uniformName] = null;
  26930. this._engine.setIntArray(this.getUniform(uniformName), array);
  26931. return this;
  26932. };
  26933. Effect.prototype.setIntArray2 = function (uniformName, array) {
  26934. this._valueCache[uniformName] = null;
  26935. this._engine.setIntArray2(this.getUniform(uniformName), array);
  26936. return this;
  26937. };
  26938. Effect.prototype.setIntArray3 = function (uniformName, array) {
  26939. this._valueCache[uniformName] = null;
  26940. this._engine.setIntArray3(this.getUniform(uniformName), array);
  26941. return this;
  26942. };
  26943. Effect.prototype.setIntArray4 = function (uniformName, array) {
  26944. this._valueCache[uniformName] = null;
  26945. this._engine.setIntArray4(this.getUniform(uniformName), array);
  26946. return this;
  26947. };
  26948. Effect.prototype.setFloatArray = function (uniformName, array) {
  26949. this._valueCache[uniformName] = null;
  26950. this._engine.setFloatArray(this.getUniform(uniformName), array);
  26951. return this;
  26952. };
  26953. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  26954. this._valueCache[uniformName] = null;
  26955. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  26956. return this;
  26957. };
  26958. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  26959. this._valueCache[uniformName] = null;
  26960. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  26961. return this;
  26962. };
  26963. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  26964. this._valueCache[uniformName] = null;
  26965. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  26966. return this;
  26967. };
  26968. Effect.prototype.setArray = function (uniformName, array) {
  26969. this._valueCache[uniformName] = null;
  26970. this._engine.setArray(this.getUniform(uniformName), array);
  26971. return this;
  26972. };
  26973. Effect.prototype.setArray2 = function (uniformName, array) {
  26974. this._valueCache[uniformName] = null;
  26975. this._engine.setArray2(this.getUniform(uniformName), array);
  26976. return this;
  26977. };
  26978. Effect.prototype.setArray3 = function (uniformName, array) {
  26979. this._valueCache[uniformName] = null;
  26980. this._engine.setArray3(this.getUniform(uniformName), array);
  26981. return this;
  26982. };
  26983. Effect.prototype.setArray4 = function (uniformName, array) {
  26984. this._valueCache[uniformName] = null;
  26985. this._engine.setArray4(this.getUniform(uniformName), array);
  26986. return this;
  26987. };
  26988. Effect.prototype.setMatrices = function (uniformName, matrices) {
  26989. if (!matrices) {
  26990. return this;
  26991. }
  26992. this._valueCache[uniformName] = null;
  26993. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  26994. return this;
  26995. };
  26996. Effect.prototype.setMatrix = function (uniformName, matrix) {
  26997. if (this._cacheMatrix(uniformName, matrix)) {
  26998. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  26999. }
  27000. return this;
  27001. };
  27002. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  27003. this._valueCache[uniformName] = null;
  27004. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  27005. return this;
  27006. };
  27007. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  27008. this._valueCache[uniformName] = null;
  27009. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  27010. return this;
  27011. };
  27012. Effect.prototype.setFloat = function (uniformName, value) {
  27013. var cache = this._valueCache[uniformName];
  27014. if (cache !== undefined && cache === value)
  27015. return this;
  27016. this._valueCache[uniformName] = value;
  27017. this._engine.setFloat(this.getUniform(uniformName), value);
  27018. return this;
  27019. };
  27020. Effect.prototype.setBool = function (uniformName, bool) {
  27021. var cache = this._valueCache[uniformName];
  27022. if (cache !== undefined && cache === bool)
  27023. return this;
  27024. this._valueCache[uniformName] = bool;
  27025. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  27026. return this;
  27027. };
  27028. Effect.prototype.setVector2 = function (uniformName, vector2) {
  27029. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  27030. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  27031. }
  27032. return this;
  27033. };
  27034. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  27035. if (this._cacheFloat2(uniformName, x, y)) {
  27036. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  27037. }
  27038. return this;
  27039. };
  27040. Effect.prototype.setVector3 = function (uniformName, vector3) {
  27041. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  27042. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  27043. }
  27044. return this;
  27045. };
  27046. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  27047. if (this._cacheFloat3(uniformName, x, y, z)) {
  27048. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  27049. }
  27050. return this;
  27051. };
  27052. Effect.prototype.setVector4 = function (uniformName, vector4) {
  27053. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  27054. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  27055. }
  27056. return this;
  27057. };
  27058. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  27059. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  27060. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  27061. }
  27062. return this;
  27063. };
  27064. Effect.prototype.setColor3 = function (uniformName, color3) {
  27065. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  27066. this._engine.setColor3(this.getUniform(uniformName), color3);
  27067. }
  27068. return this;
  27069. };
  27070. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  27071. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  27072. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  27073. }
  27074. return this;
  27075. };
  27076. Effect.ResetCache = function () {
  27077. Effect._baseCache = {};
  27078. };
  27079. Effect._uniqueIdSeed = 0;
  27080. Effect._baseCache = {};
  27081. // Statics
  27082. Effect.ShadersStore = {};
  27083. Effect.IncludesShadersStore = {};
  27084. return Effect;
  27085. }());
  27086. BABYLON.Effect = Effect;
  27087. })(BABYLON || (BABYLON = {}));
  27088. //# sourceMappingURL=babylon.effect.js.map
  27089. var BABYLON;
  27090. (function (BABYLON) {
  27091. var MaterialHelper = /** @class */ (function () {
  27092. function MaterialHelper() {
  27093. }
  27094. MaterialHelper.BindEyePosition = function (effect, scene) {
  27095. if (scene._forcedViewPosition) {
  27096. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  27097. return;
  27098. }
  27099. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  27100. };
  27101. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  27102. defines._needUVs = true;
  27103. defines[key] = true;
  27104. if (texture.getTextureMatrix().isIdentity(true)) {
  27105. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  27106. if (texture.coordinatesIndex === 0) {
  27107. defines["MAINUV1"] = true;
  27108. }
  27109. else {
  27110. defines["MAINUV2"] = true;
  27111. }
  27112. }
  27113. else {
  27114. defines[key + "DIRECTUV"] = 0;
  27115. }
  27116. };
  27117. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  27118. var matrix = texture.getTextureMatrix();
  27119. if (!matrix.isIdentity(true)) {
  27120. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  27121. }
  27122. };
  27123. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  27124. if (defines._areMiscDirty) {
  27125. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  27126. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  27127. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  27128. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  27129. }
  27130. };
  27131. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  27132. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  27133. var changed = false;
  27134. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  27135. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  27136. changed = true;
  27137. }
  27138. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  27139. defines["ALPHATEST"] = !defines["ALPHATEST"];
  27140. changed = true;
  27141. }
  27142. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  27143. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  27144. changed = true;
  27145. }
  27146. if (defines["INSTANCES"] !== useInstances) {
  27147. defines["INSTANCES"] = useInstances;
  27148. changed = true;
  27149. }
  27150. if (changed) {
  27151. defines.markAsUnprocessed();
  27152. }
  27153. };
  27154. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  27155. if (useMorphTargets === void 0) { useMorphTargets = false; }
  27156. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  27157. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  27158. return false;
  27159. }
  27160. defines._normals = defines._needNormals;
  27161. defines._uvs = defines._needUVs;
  27162. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  27163. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  27164. defines["TANGENT"] = true;
  27165. }
  27166. if (defines._needUVs) {
  27167. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  27168. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  27169. }
  27170. else {
  27171. defines["UV1"] = false;
  27172. defines["UV2"] = false;
  27173. }
  27174. if (useVertexColor) {
  27175. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  27176. defines["VERTEXCOLOR"] = hasVertexColors;
  27177. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  27178. }
  27179. if (useBones) {
  27180. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  27181. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  27182. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  27183. }
  27184. else {
  27185. defines["NUM_BONE_INFLUENCERS"] = 0;
  27186. defines["BonesPerMesh"] = 0;
  27187. }
  27188. }
  27189. if (useMorphTargets) {
  27190. var manager = mesh.morphTargetManager;
  27191. if (manager) {
  27192. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  27193. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  27194. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  27195. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  27196. }
  27197. else {
  27198. defines["MORPHTARGETS_TANGENT"] = false;
  27199. defines["MORPHTARGETS_NORMAL"] = false;
  27200. defines["MORPHTARGETS"] = false;
  27201. defines["NUM_MORPH_INFLUENCERS"] = 0;
  27202. }
  27203. }
  27204. return true;
  27205. };
  27206. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  27207. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  27208. if (disableLighting === void 0) { disableLighting = false; }
  27209. if (!defines._areLightsDirty) {
  27210. return defines._needNormals;
  27211. }
  27212. var lightIndex = 0;
  27213. var needNormals = false;
  27214. var needRebuild = false;
  27215. var lightmapMode = false;
  27216. var shadowEnabled = false;
  27217. var specularEnabled = false;
  27218. if (scene.lightsEnabled && !disableLighting) {
  27219. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  27220. var light = _a[_i];
  27221. needNormals = true;
  27222. if (defines["LIGHT" + lightIndex] === undefined) {
  27223. needRebuild = true;
  27224. }
  27225. defines["LIGHT" + lightIndex] = true;
  27226. defines["SPOTLIGHT" + lightIndex] = false;
  27227. defines["HEMILIGHT" + lightIndex] = false;
  27228. defines["POINTLIGHT" + lightIndex] = false;
  27229. defines["DIRLIGHT" + lightIndex] = false;
  27230. var type;
  27231. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  27232. type = "SPOTLIGHT" + lightIndex;
  27233. }
  27234. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  27235. type = "HEMILIGHT" + lightIndex;
  27236. }
  27237. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  27238. type = "POINTLIGHT" + lightIndex;
  27239. }
  27240. else {
  27241. type = "DIRLIGHT" + lightIndex;
  27242. }
  27243. defines[type] = true;
  27244. // Specular
  27245. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  27246. specularEnabled = true;
  27247. }
  27248. // Shadows
  27249. defines["SHADOW" + lightIndex] = false;
  27250. defines["SHADOWPCF" + lightIndex] = false;
  27251. defines["SHADOWESM" + lightIndex] = false;
  27252. defines["SHADOWCUBE" + lightIndex] = false;
  27253. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  27254. var shadowGenerator = light.getShadowGenerator();
  27255. if (shadowGenerator) {
  27256. shadowEnabled = true;
  27257. shadowGenerator.prepareDefines(defines, lightIndex);
  27258. }
  27259. }
  27260. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  27261. lightmapMode = true;
  27262. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  27263. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  27264. }
  27265. else {
  27266. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  27267. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  27268. }
  27269. lightIndex++;
  27270. if (lightIndex === maxSimultaneousLights)
  27271. break;
  27272. }
  27273. }
  27274. defines["SPECULARTERM"] = specularEnabled;
  27275. defines["SHADOWS"] = shadowEnabled;
  27276. // Resetting all other lights if any
  27277. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  27278. if (defines["LIGHT" + index] !== undefined) {
  27279. defines["LIGHT" + index] = false;
  27280. defines["HEMILIGHT" + lightIndex] = false;
  27281. defines["POINTLIGHT" + lightIndex] = false;
  27282. defines["DIRLIGHT" + lightIndex] = false;
  27283. defines["SPOTLIGHT" + lightIndex] = false;
  27284. defines["SHADOW" + lightIndex] = false;
  27285. }
  27286. }
  27287. var caps = scene.getEngine().getCaps();
  27288. if (defines["SHADOWFLOAT"] === undefined) {
  27289. needRebuild = true;
  27290. }
  27291. defines["SHADOWFLOAT"] = shadowEnabled &&
  27292. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  27293. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  27294. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  27295. if (needRebuild) {
  27296. defines.rebuild();
  27297. }
  27298. return needNormals;
  27299. };
  27300. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  27301. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  27302. var uniformsList;
  27303. var uniformBuffersList = null;
  27304. if (uniformsListOrOptions.uniformsNames) {
  27305. var options = uniformsListOrOptions;
  27306. uniformsList = options.uniformsNames;
  27307. uniformBuffersList = options.uniformBuffersNames;
  27308. samplersList = options.samplers;
  27309. defines = options.defines;
  27310. maxSimultaneousLights = options.maxSimultaneousLights;
  27311. }
  27312. else {
  27313. uniformsList = uniformsListOrOptions;
  27314. if (!samplersList) {
  27315. samplersList = [];
  27316. }
  27317. }
  27318. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  27319. if (!defines["LIGHT" + lightIndex]) {
  27320. break;
  27321. }
  27322. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  27323. if (uniformBuffersList) {
  27324. uniformBuffersList.push("Light" + lightIndex);
  27325. }
  27326. samplersList.push("shadowSampler" + lightIndex);
  27327. }
  27328. if (defines["NUM_MORPH_INFLUENCERS"]) {
  27329. uniformsList.push("morphTargetInfluences");
  27330. }
  27331. };
  27332. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  27333. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  27334. if (rank === void 0) { rank = 0; }
  27335. var lightFallbackRank = 0;
  27336. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  27337. if (!defines["LIGHT" + lightIndex]) {
  27338. break;
  27339. }
  27340. if (lightIndex > 0) {
  27341. lightFallbackRank = rank + lightIndex;
  27342. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  27343. }
  27344. if (!defines["SHADOWS"]) {
  27345. if (defines["SHADOW" + lightIndex]) {
  27346. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  27347. }
  27348. if (defines["SHADOWPCF" + lightIndex]) {
  27349. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  27350. }
  27351. if (defines["SHADOWESM" + lightIndex]) {
  27352. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  27353. }
  27354. }
  27355. }
  27356. return lightFallbackRank++;
  27357. };
  27358. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  27359. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  27360. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  27361. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  27362. var manager = mesh.morphTargetManager;
  27363. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  27364. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  27365. for (var index = 0; index < influencers; index++) {
  27366. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  27367. if (normal) {
  27368. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  27369. }
  27370. if (tangent) {
  27371. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  27372. }
  27373. if (attribs.length > maxAttributesCount) {
  27374. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  27375. }
  27376. }
  27377. }
  27378. };
  27379. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  27380. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  27381. fallbacks.addCPUSkinningFallback(0, mesh);
  27382. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27383. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27384. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  27385. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  27386. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  27387. }
  27388. }
  27389. };
  27390. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  27391. if (defines["INSTANCES"]) {
  27392. attribs.push("world0");
  27393. attribs.push("world1");
  27394. attribs.push("world2");
  27395. attribs.push("world3");
  27396. }
  27397. };
  27398. // Bindings
  27399. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  27400. if (light.shadowEnabled && mesh.receiveShadows) {
  27401. var shadowGenerator = light.getShadowGenerator();
  27402. if (shadowGenerator) {
  27403. shadowGenerator.bindShadowLight(lightIndex, effect);
  27404. }
  27405. }
  27406. };
  27407. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  27408. light.transferToEffect(effect, lightIndex + "");
  27409. };
  27410. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  27411. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  27412. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  27413. var lightIndex = 0;
  27414. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  27415. var light = _a[_i];
  27416. var scaledIntensity = light.getScaledIntensity();
  27417. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  27418. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  27419. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  27420. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  27421. if (defines["SPECULARTERM"]) {
  27422. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  27423. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  27424. }
  27425. // Shadows
  27426. if (scene.shadowsEnabled) {
  27427. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  27428. }
  27429. light._uniformBuffer.update();
  27430. lightIndex++;
  27431. if (lightIndex === maxSimultaneousLights)
  27432. break;
  27433. }
  27434. };
  27435. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  27436. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  27437. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  27438. effect.setColor3("vFogColor", scene.fogColor);
  27439. }
  27440. };
  27441. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  27442. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  27443. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  27444. if (matrices && effect) {
  27445. effect.setMatrices("mBones", matrices);
  27446. }
  27447. }
  27448. };
  27449. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  27450. var manager = abstractMesh.morphTargetManager;
  27451. if (!abstractMesh || !manager) {
  27452. return;
  27453. }
  27454. effect.setFloatArray("morphTargetInfluences", manager.influences);
  27455. };
  27456. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  27457. if (defines["LOGARITHMICDEPTH"]) {
  27458. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  27459. }
  27460. };
  27461. MaterialHelper.BindClipPlane = function (effect, scene) {
  27462. if (scene.clipPlane) {
  27463. var clipPlane = scene.clipPlane;
  27464. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  27465. }
  27466. };
  27467. return MaterialHelper;
  27468. }());
  27469. BABYLON.MaterialHelper = MaterialHelper;
  27470. })(BABYLON || (BABYLON = {}));
  27471. //# sourceMappingURL=babylon.materialHelper.js.map
  27472. var __assign = (this && this.__assign) || Object.assign || function(t) {
  27473. for (var s, i = 1, n = arguments.length; i < n; i++) {
  27474. s = arguments[i];
  27475. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  27476. t[p] = s[p];
  27477. }
  27478. return t;
  27479. };
  27480. var BABYLON;
  27481. (function (BABYLON) {
  27482. var MaterialDefines = /** @class */ (function () {
  27483. function MaterialDefines() {
  27484. this._isDirty = true;
  27485. this._areLightsDirty = true;
  27486. this._areAttributesDirty = true;
  27487. this._areTexturesDirty = true;
  27488. this._areFresnelDirty = true;
  27489. this._areMiscDirty = true;
  27490. this._areImageProcessingDirty = true;
  27491. this._normals = false;
  27492. this._uvs = false;
  27493. this._needNormals = false;
  27494. this._needUVs = false;
  27495. }
  27496. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  27497. get: function () {
  27498. return this._isDirty;
  27499. },
  27500. enumerable: true,
  27501. configurable: true
  27502. });
  27503. MaterialDefines.prototype.markAsProcessed = function () {
  27504. this._isDirty = false;
  27505. this._areAttributesDirty = false;
  27506. this._areTexturesDirty = false;
  27507. this._areFresnelDirty = false;
  27508. this._areLightsDirty = false;
  27509. this._areMiscDirty = false;
  27510. this._areImageProcessingDirty = false;
  27511. };
  27512. MaterialDefines.prototype.markAsUnprocessed = function () {
  27513. this._isDirty = true;
  27514. };
  27515. MaterialDefines.prototype.markAllAsDirty = function () {
  27516. this._areTexturesDirty = true;
  27517. this._areAttributesDirty = true;
  27518. this._areLightsDirty = true;
  27519. this._areFresnelDirty = true;
  27520. this._areMiscDirty = true;
  27521. this._areImageProcessingDirty = true;
  27522. this._isDirty = true;
  27523. };
  27524. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  27525. this._areImageProcessingDirty = true;
  27526. this._isDirty = true;
  27527. };
  27528. MaterialDefines.prototype.markAsLightDirty = function () {
  27529. this._areLightsDirty = true;
  27530. this._isDirty = true;
  27531. };
  27532. MaterialDefines.prototype.markAsAttributesDirty = function () {
  27533. this._areAttributesDirty = true;
  27534. this._isDirty = true;
  27535. };
  27536. MaterialDefines.prototype.markAsTexturesDirty = function () {
  27537. this._areTexturesDirty = true;
  27538. this._isDirty = true;
  27539. };
  27540. MaterialDefines.prototype.markAsFresnelDirty = function () {
  27541. this._areFresnelDirty = true;
  27542. this._isDirty = true;
  27543. };
  27544. MaterialDefines.prototype.markAsMiscDirty = function () {
  27545. this._areMiscDirty = true;
  27546. this._isDirty = true;
  27547. };
  27548. MaterialDefines.prototype.rebuild = function () {
  27549. if (this._keys) {
  27550. delete this._keys;
  27551. }
  27552. this._keys = [];
  27553. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  27554. var key = _a[_i];
  27555. if (key[0] === "_") {
  27556. continue;
  27557. }
  27558. this._keys.push(key);
  27559. }
  27560. };
  27561. MaterialDefines.prototype.isEqual = function (other) {
  27562. if (this._keys.length !== other._keys.length) {
  27563. return false;
  27564. }
  27565. for (var index = 0; index < this._keys.length; index++) {
  27566. var prop = this._keys[index];
  27567. if (this[prop] !== other[prop]) {
  27568. return false;
  27569. }
  27570. }
  27571. return true;
  27572. };
  27573. MaterialDefines.prototype.cloneTo = function (other) {
  27574. if (this._keys.length !== other._keys.length) {
  27575. other._keys = this._keys.slice(0);
  27576. }
  27577. for (var index = 0; index < this._keys.length; index++) {
  27578. var prop = this._keys[index];
  27579. other[prop] = this[prop];
  27580. }
  27581. };
  27582. MaterialDefines.prototype.reset = function () {
  27583. for (var index = 0; index < this._keys.length; index++) {
  27584. var prop = this._keys[index];
  27585. if (typeof (this[prop]) === "number") {
  27586. this[prop] = 0;
  27587. }
  27588. else {
  27589. this[prop] = false;
  27590. }
  27591. }
  27592. };
  27593. MaterialDefines.prototype.toString = function () {
  27594. var result = "";
  27595. for (var index = 0; index < this._keys.length; index++) {
  27596. var prop = this._keys[index];
  27597. var value = this[prop];
  27598. if (typeof (value) === "number") {
  27599. result += "#define " + prop + " " + this[prop] + "\n";
  27600. }
  27601. else if (value) {
  27602. result += "#define " + prop + "\n";
  27603. }
  27604. }
  27605. return result;
  27606. };
  27607. return MaterialDefines;
  27608. }());
  27609. BABYLON.MaterialDefines = MaterialDefines;
  27610. var Material = /** @class */ (function () {
  27611. function Material(name, scene, doNotAdd) {
  27612. this.checkReadyOnEveryCall = false;
  27613. this.checkReadyOnlyOnce = false;
  27614. this.state = "";
  27615. this.alpha = 1.0;
  27616. this._backFaceCulling = true;
  27617. this.doNotSerialize = false;
  27618. this.storeEffectOnSubMeshes = false;
  27619. /**
  27620. * An event triggered when the material is disposed.
  27621. * @type {BABYLON.Observable}
  27622. */
  27623. this.onDisposeObservable = new BABYLON.Observable();
  27624. /**
  27625. * An event triggered when the material is bound.
  27626. * @type {BABYLON.Observable}
  27627. */
  27628. this.onBindObservable = new BABYLON.Observable();
  27629. /**
  27630. * An event triggered when the material is unbound.
  27631. * @type {BABYLON.Observable}
  27632. */
  27633. this.onUnBindObservable = new BABYLON.Observable();
  27634. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  27635. this._needDepthPrePass = false;
  27636. this.disableDepthWrite = false;
  27637. this.forceDepthWrite = false;
  27638. this.separateCullingPass = false;
  27639. this._fogEnabled = true;
  27640. this.pointSize = 1.0;
  27641. this.zOffset = 0;
  27642. this._wasPreviouslyReady = false;
  27643. this._fillMode = Material.TriangleFillMode;
  27644. this.name = name;
  27645. this.id = name || BABYLON.Tools.RandomId();
  27646. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  27647. if (this._scene.useRightHandedSystem) {
  27648. this.sideOrientation = Material.ClockWiseSideOrientation;
  27649. }
  27650. else {
  27651. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  27652. }
  27653. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  27654. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  27655. if (!doNotAdd) {
  27656. this._scene.materials.push(this);
  27657. }
  27658. }
  27659. Object.defineProperty(Material, "TriangleFillMode", {
  27660. get: function () {
  27661. return Material._TriangleFillMode;
  27662. },
  27663. enumerable: true,
  27664. configurable: true
  27665. });
  27666. Object.defineProperty(Material, "WireFrameFillMode", {
  27667. get: function () {
  27668. return Material._WireFrameFillMode;
  27669. },
  27670. enumerable: true,
  27671. configurable: true
  27672. });
  27673. Object.defineProperty(Material, "PointFillMode", {
  27674. get: function () {
  27675. return Material._PointFillMode;
  27676. },
  27677. enumerable: true,
  27678. configurable: true
  27679. });
  27680. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  27681. get: function () {
  27682. return Material._ClockWiseSideOrientation;
  27683. },
  27684. enumerable: true,
  27685. configurable: true
  27686. });
  27687. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  27688. get: function () {
  27689. return Material._CounterClockWiseSideOrientation;
  27690. },
  27691. enumerable: true,
  27692. configurable: true
  27693. });
  27694. Object.defineProperty(Material, "TextureDirtyFlag", {
  27695. get: function () {
  27696. return Material._TextureDirtyFlag;
  27697. },
  27698. enumerable: true,
  27699. configurable: true
  27700. });
  27701. Object.defineProperty(Material, "LightDirtyFlag", {
  27702. get: function () {
  27703. return Material._LightDirtyFlag;
  27704. },
  27705. enumerable: true,
  27706. configurable: true
  27707. });
  27708. Object.defineProperty(Material, "FresnelDirtyFlag", {
  27709. get: function () {
  27710. return Material._FresnelDirtyFlag;
  27711. },
  27712. enumerable: true,
  27713. configurable: true
  27714. });
  27715. Object.defineProperty(Material, "AttributesDirtyFlag", {
  27716. get: function () {
  27717. return Material._AttributesDirtyFlag;
  27718. },
  27719. enumerable: true,
  27720. configurable: true
  27721. });
  27722. Object.defineProperty(Material, "MiscDirtyFlag", {
  27723. get: function () {
  27724. return Material._MiscDirtyFlag;
  27725. },
  27726. enumerable: true,
  27727. configurable: true
  27728. });
  27729. Object.defineProperty(Material.prototype, "backFaceCulling", {
  27730. get: function () {
  27731. return this._backFaceCulling;
  27732. },
  27733. set: function (value) {
  27734. if (this._backFaceCulling === value) {
  27735. return;
  27736. }
  27737. this._backFaceCulling = value;
  27738. this.markAsDirty(Material.TextureDirtyFlag);
  27739. },
  27740. enumerable: true,
  27741. configurable: true
  27742. });
  27743. Object.defineProperty(Material.prototype, "onDispose", {
  27744. set: function (callback) {
  27745. if (this._onDisposeObserver) {
  27746. this.onDisposeObservable.remove(this._onDisposeObserver);
  27747. }
  27748. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27749. },
  27750. enumerable: true,
  27751. configurable: true
  27752. });
  27753. Object.defineProperty(Material.prototype, "onBind", {
  27754. set: function (callback) {
  27755. if (this._onBindObserver) {
  27756. this.onBindObservable.remove(this._onBindObserver);
  27757. }
  27758. this._onBindObserver = this.onBindObservable.add(callback);
  27759. },
  27760. enumerable: true,
  27761. configurable: true
  27762. });
  27763. Object.defineProperty(Material.prototype, "alphaMode", {
  27764. get: function () {
  27765. return this._alphaMode;
  27766. },
  27767. set: function (value) {
  27768. if (this._alphaMode === value) {
  27769. return;
  27770. }
  27771. this._alphaMode = value;
  27772. this.markAsDirty(Material.TextureDirtyFlag);
  27773. },
  27774. enumerable: true,
  27775. configurable: true
  27776. });
  27777. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  27778. get: function () {
  27779. return this._needDepthPrePass;
  27780. },
  27781. set: function (value) {
  27782. if (this._needDepthPrePass === value) {
  27783. return;
  27784. }
  27785. this._needDepthPrePass = value;
  27786. if (this._needDepthPrePass) {
  27787. this.checkReadyOnEveryCall = true;
  27788. }
  27789. },
  27790. enumerable: true,
  27791. configurable: true
  27792. });
  27793. Object.defineProperty(Material.prototype, "fogEnabled", {
  27794. get: function () {
  27795. return this._fogEnabled;
  27796. },
  27797. set: function (value) {
  27798. if (this._fogEnabled === value) {
  27799. return;
  27800. }
  27801. this._fogEnabled = value;
  27802. this.markAsDirty(Material.MiscDirtyFlag);
  27803. },
  27804. enumerable: true,
  27805. configurable: true
  27806. });
  27807. Object.defineProperty(Material.prototype, "wireframe", {
  27808. get: function () {
  27809. return this._fillMode === Material.WireFrameFillMode;
  27810. },
  27811. set: function (value) {
  27812. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  27813. },
  27814. enumerable: true,
  27815. configurable: true
  27816. });
  27817. Object.defineProperty(Material.prototype, "pointsCloud", {
  27818. get: function () {
  27819. return this._fillMode === Material.PointFillMode;
  27820. },
  27821. set: function (value) {
  27822. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  27823. },
  27824. enumerable: true,
  27825. configurable: true
  27826. });
  27827. Object.defineProperty(Material.prototype, "fillMode", {
  27828. get: function () {
  27829. return this._fillMode;
  27830. },
  27831. set: function (value) {
  27832. if (this._fillMode === value) {
  27833. return;
  27834. }
  27835. this._fillMode = value;
  27836. this.markAsDirty(Material.MiscDirtyFlag);
  27837. },
  27838. enumerable: true,
  27839. configurable: true
  27840. });
  27841. /**
  27842. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27843. * subclasses should override adding information pertainent to themselves
  27844. */
  27845. Material.prototype.toString = function (fullDetails) {
  27846. var ret = "Name: " + this.name;
  27847. if (fullDetails) {
  27848. }
  27849. return ret;
  27850. };
  27851. /**
  27852. * Child classes can use it to update shaders
  27853. */
  27854. Material.prototype.getClassName = function () {
  27855. return "Material";
  27856. };
  27857. Object.defineProperty(Material.prototype, "isFrozen", {
  27858. get: function () {
  27859. return this.checkReadyOnlyOnce;
  27860. },
  27861. enumerable: true,
  27862. configurable: true
  27863. });
  27864. Material.prototype.freeze = function () {
  27865. this.checkReadyOnlyOnce = true;
  27866. };
  27867. Material.prototype.unfreeze = function () {
  27868. this.checkReadyOnlyOnce = false;
  27869. };
  27870. Material.prototype.isReady = function (mesh, useInstances) {
  27871. return true;
  27872. };
  27873. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  27874. return false;
  27875. };
  27876. Material.prototype.getEffect = function () {
  27877. return this._effect;
  27878. };
  27879. Material.prototype.getScene = function () {
  27880. return this._scene;
  27881. };
  27882. Material.prototype.needAlphaBlending = function () {
  27883. return (this.alpha < 1.0);
  27884. };
  27885. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  27886. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  27887. };
  27888. Material.prototype.needAlphaTesting = function () {
  27889. return false;
  27890. };
  27891. Material.prototype.getAlphaTestTexture = function () {
  27892. return null;
  27893. };
  27894. Material.prototype.markDirty = function () {
  27895. this._wasPreviouslyReady = false;
  27896. };
  27897. Material.prototype._preBind = function (effect, overrideOrientation) {
  27898. if (overrideOrientation === void 0) { overrideOrientation = null; }
  27899. var engine = this._scene.getEngine();
  27900. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  27901. var reverse = orientation === Material.ClockWiseSideOrientation;
  27902. engine.enableEffect(effect ? effect : this._effect);
  27903. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  27904. return reverse;
  27905. };
  27906. Material.prototype.bind = function (world, mesh) {
  27907. };
  27908. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  27909. };
  27910. Material.prototype.bindOnlyWorldMatrix = function (world) {
  27911. };
  27912. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  27913. sceneUbo.bindToEffect(effect, "Scene");
  27914. };
  27915. Material.prototype.bindView = function (effect) {
  27916. if (!this._useUBO) {
  27917. effect.setMatrix("view", this.getScene().getViewMatrix());
  27918. }
  27919. else {
  27920. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  27921. }
  27922. };
  27923. Material.prototype.bindViewProjection = function (effect) {
  27924. if (!this._useUBO) {
  27925. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  27926. }
  27927. else {
  27928. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  27929. }
  27930. };
  27931. Material.prototype._afterBind = function (mesh) {
  27932. this._scene._cachedMaterial = this;
  27933. if (mesh) {
  27934. this._scene._cachedVisibility = mesh.visibility;
  27935. }
  27936. else {
  27937. this._scene._cachedVisibility = 1;
  27938. }
  27939. if (mesh) {
  27940. this.onBindObservable.notifyObservers(mesh);
  27941. }
  27942. if (this.disableDepthWrite) {
  27943. var engine = this._scene.getEngine();
  27944. this._cachedDepthWriteState = engine.getDepthWrite();
  27945. engine.setDepthWrite(false);
  27946. }
  27947. };
  27948. Material.prototype.unbind = function () {
  27949. this.onUnBindObservable.notifyObservers(this);
  27950. if (this.disableDepthWrite) {
  27951. var engine = this._scene.getEngine();
  27952. engine.setDepthWrite(this._cachedDepthWriteState);
  27953. }
  27954. };
  27955. Material.prototype.getActiveTextures = function () {
  27956. return [];
  27957. };
  27958. Material.prototype.hasTexture = function (texture) {
  27959. return false;
  27960. };
  27961. Material.prototype.clone = function (name) {
  27962. return null;
  27963. };
  27964. Material.prototype.getBindedMeshes = function () {
  27965. var result = new Array();
  27966. for (var index = 0; index < this._scene.meshes.length; index++) {
  27967. var mesh = this._scene.meshes[index];
  27968. if (mesh.material === this) {
  27969. result.push(mesh);
  27970. }
  27971. }
  27972. return result;
  27973. };
  27974. /**
  27975. * Force shader compilation including textures ready check
  27976. */
  27977. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  27978. var _this = this;
  27979. var localOptions = __assign({ alphaTest: null, clipPlane: false }, options);
  27980. var subMesh = new BABYLON.BaseSubMesh();
  27981. var scene = this.getScene();
  27982. var engine = scene.getEngine();
  27983. var checkReady = function () {
  27984. if (!_this._scene || !_this._scene.getEngine()) {
  27985. return;
  27986. }
  27987. if (subMesh._materialDefines) {
  27988. subMesh._materialDefines._renderId = -1;
  27989. }
  27990. var alphaTestState = engine.getAlphaTesting();
  27991. var clipPlaneState = scene.clipPlane;
  27992. engine.setAlphaTesting(localOptions.alphaTest || (!_this.needAlphaBlendingForMesh(mesh) && _this.needAlphaTesting()));
  27993. if (localOptions.clipPlane) {
  27994. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  27995. }
  27996. if (_this.storeEffectOnSubMeshes) {
  27997. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  27998. if (onCompiled) {
  27999. onCompiled(_this);
  28000. }
  28001. }
  28002. else {
  28003. setTimeout(checkReady, 16);
  28004. }
  28005. }
  28006. else {
  28007. if (_this.isReady(mesh)) {
  28008. if (onCompiled) {
  28009. onCompiled(_this);
  28010. }
  28011. }
  28012. else {
  28013. setTimeout(checkReady, 16);
  28014. }
  28015. }
  28016. engine.setAlphaTesting(alphaTestState);
  28017. if (options && options.clipPlane) {
  28018. scene.clipPlane = clipPlaneState;
  28019. }
  28020. };
  28021. checkReady();
  28022. };
  28023. Material.prototype.markAsDirty = function (flag) {
  28024. if (flag & Material.TextureDirtyFlag) {
  28025. this._markAllSubMeshesAsTexturesDirty();
  28026. }
  28027. if (flag & Material.LightDirtyFlag) {
  28028. this._markAllSubMeshesAsLightsDirty();
  28029. }
  28030. if (flag & Material.FresnelDirtyFlag) {
  28031. this._markAllSubMeshesAsFresnelDirty();
  28032. }
  28033. if (flag & Material.AttributesDirtyFlag) {
  28034. this._markAllSubMeshesAsAttributesDirty();
  28035. }
  28036. if (flag & Material.MiscDirtyFlag) {
  28037. this._markAllSubMeshesAsMiscDirty();
  28038. }
  28039. this.getScene().resetCachedMaterial();
  28040. };
  28041. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  28042. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  28043. var mesh = _a[_i];
  28044. if (!mesh.subMeshes) {
  28045. continue;
  28046. }
  28047. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  28048. var subMesh = _c[_b];
  28049. if (subMesh.getMaterial() !== this) {
  28050. continue;
  28051. }
  28052. if (!subMesh._materialDefines) {
  28053. continue;
  28054. }
  28055. func(subMesh._materialDefines);
  28056. }
  28057. }
  28058. };
  28059. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  28060. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  28061. };
  28062. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  28063. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  28064. };
  28065. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  28066. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  28067. };
  28068. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  28069. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  28070. };
  28071. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  28072. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  28073. };
  28074. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  28075. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  28076. };
  28077. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  28078. // Animations
  28079. this.getScene().stopAnimation(this);
  28080. // Remove from scene
  28081. var index = this._scene.materials.indexOf(this);
  28082. if (index >= 0) {
  28083. this._scene.materials.splice(index, 1);
  28084. }
  28085. // Remove from meshes
  28086. for (index = 0; index < this._scene.meshes.length; index++) {
  28087. var mesh = this._scene.meshes[index];
  28088. if (mesh.material === this) {
  28089. mesh.material = null;
  28090. if (mesh.geometry) {
  28091. var geometry = (mesh.geometry);
  28092. if (this.storeEffectOnSubMeshes) {
  28093. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  28094. var subMesh = _a[_i];
  28095. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  28096. if (forceDisposeEffect && subMesh._materialEffect) {
  28097. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  28098. }
  28099. }
  28100. }
  28101. else {
  28102. geometry._releaseVertexArrayObject(this._effect);
  28103. }
  28104. }
  28105. }
  28106. }
  28107. this._uniformBuffer.dispose();
  28108. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  28109. if (forceDisposeEffect && this._effect) {
  28110. if (!this.storeEffectOnSubMeshes) {
  28111. this._scene.getEngine()._releaseEffect(this._effect);
  28112. }
  28113. this._effect = null;
  28114. }
  28115. // Callback
  28116. this.onDisposeObservable.notifyObservers(this);
  28117. this.onDisposeObservable.clear();
  28118. this.onBindObservable.clear();
  28119. this.onUnBindObservable.clear();
  28120. };
  28121. Material.prototype.serialize = function () {
  28122. return BABYLON.SerializationHelper.Serialize(this);
  28123. };
  28124. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  28125. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  28126. multiMaterial.id = parsedMultiMaterial.id;
  28127. if (BABYLON.Tags) {
  28128. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  28129. }
  28130. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  28131. var subMatId = parsedMultiMaterial.materials[matIndex];
  28132. if (subMatId) {
  28133. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  28134. }
  28135. else {
  28136. multiMaterial.subMaterials.push(null);
  28137. }
  28138. }
  28139. return multiMaterial;
  28140. };
  28141. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  28142. if (!parsedMaterial.customType) {
  28143. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  28144. }
  28145. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  28146. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  28147. if (!BABYLON.LegacyPBRMaterial) {
  28148. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  28149. return;
  28150. }
  28151. }
  28152. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  28153. return materialType.Parse(parsedMaterial, scene, rootUrl);
  28154. ;
  28155. };
  28156. Material._TriangleFillMode = 0;
  28157. Material._WireFrameFillMode = 1;
  28158. Material._PointFillMode = 2;
  28159. Material._ClockWiseSideOrientation = 0;
  28160. Material._CounterClockWiseSideOrientation = 1;
  28161. Material._TextureDirtyFlag = 1;
  28162. Material._LightDirtyFlag = 2;
  28163. Material._FresnelDirtyFlag = 4;
  28164. Material._AttributesDirtyFlag = 8;
  28165. Material._MiscDirtyFlag = 16;
  28166. __decorate([
  28167. BABYLON.serialize()
  28168. ], Material.prototype, "id", void 0);
  28169. __decorate([
  28170. BABYLON.serialize()
  28171. ], Material.prototype, "name", void 0);
  28172. __decorate([
  28173. BABYLON.serialize()
  28174. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  28175. __decorate([
  28176. BABYLON.serialize()
  28177. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  28178. __decorate([
  28179. BABYLON.serialize()
  28180. ], Material.prototype, "state", void 0);
  28181. __decorate([
  28182. BABYLON.serialize()
  28183. ], Material.prototype, "alpha", void 0);
  28184. __decorate([
  28185. BABYLON.serialize("backFaceCulling")
  28186. ], Material.prototype, "_backFaceCulling", void 0);
  28187. __decorate([
  28188. BABYLON.serialize()
  28189. ], Material.prototype, "sideOrientation", void 0);
  28190. __decorate([
  28191. BABYLON.serialize("alphaMode")
  28192. ], Material.prototype, "_alphaMode", void 0);
  28193. __decorate([
  28194. BABYLON.serialize()
  28195. ], Material.prototype, "_needDepthPrePass", void 0);
  28196. __decorate([
  28197. BABYLON.serialize()
  28198. ], Material.prototype, "disableDepthWrite", void 0);
  28199. __decorate([
  28200. BABYLON.serialize()
  28201. ], Material.prototype, "forceDepthWrite", void 0);
  28202. __decorate([
  28203. BABYLON.serialize()
  28204. ], Material.prototype, "separateCullingPass", void 0);
  28205. __decorate([
  28206. BABYLON.serialize("fogEnabled")
  28207. ], Material.prototype, "_fogEnabled", void 0);
  28208. __decorate([
  28209. BABYLON.serialize()
  28210. ], Material.prototype, "pointSize", void 0);
  28211. __decorate([
  28212. BABYLON.serialize()
  28213. ], Material.prototype, "zOffset", void 0);
  28214. __decorate([
  28215. BABYLON.serialize()
  28216. ], Material.prototype, "wireframe", null);
  28217. __decorate([
  28218. BABYLON.serialize()
  28219. ], Material.prototype, "pointsCloud", null);
  28220. __decorate([
  28221. BABYLON.serialize()
  28222. ], Material.prototype, "fillMode", null);
  28223. return Material;
  28224. }());
  28225. BABYLON.Material = Material;
  28226. })(BABYLON || (BABYLON = {}));
  28227. //# sourceMappingURL=babylon.material.js.map
  28228. var BABYLON;
  28229. (function (BABYLON) {
  28230. var UniformBuffer = /** @class */ (function () {
  28231. /**
  28232. * Uniform buffer objects.
  28233. *
  28234. * Handles blocks of uniform on the GPU.
  28235. *
  28236. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  28237. *
  28238. * For more information, please refer to :
  28239. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  28240. */
  28241. function UniformBuffer(engine, data, dynamic) {
  28242. this._engine = engine;
  28243. this._noUBO = !engine.supportsUniformBuffers;
  28244. this._dynamic = dynamic;
  28245. this._data = data || [];
  28246. this._uniformLocations = {};
  28247. this._uniformSizes = {};
  28248. this._uniformLocationPointer = 0;
  28249. this._needSync = false;
  28250. if (this._noUBO) {
  28251. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  28252. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  28253. this.updateFloat = this._updateFloatForEffect;
  28254. this.updateFloat2 = this._updateFloat2ForEffect;
  28255. this.updateFloat3 = this._updateFloat3ForEffect;
  28256. this.updateFloat4 = this._updateFloat4ForEffect;
  28257. this.updateMatrix = this._updateMatrixForEffect;
  28258. this.updateVector3 = this._updateVector3ForEffect;
  28259. this.updateVector4 = this._updateVector4ForEffect;
  28260. this.updateColor3 = this._updateColor3ForEffect;
  28261. this.updateColor4 = this._updateColor4ForEffect;
  28262. }
  28263. else {
  28264. this._engine._uniformBuffers.push(this);
  28265. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  28266. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  28267. this.updateFloat = this._updateFloatForUniform;
  28268. this.updateFloat2 = this._updateFloat2ForUniform;
  28269. this.updateFloat3 = this._updateFloat3ForUniform;
  28270. this.updateFloat4 = this._updateFloat4ForUniform;
  28271. this.updateMatrix = this._updateMatrixForUniform;
  28272. this.updateVector3 = this._updateVector3ForUniform;
  28273. this.updateVector4 = this._updateVector4ForUniform;
  28274. this.updateColor3 = this._updateColor3ForUniform;
  28275. this.updateColor4 = this._updateColor4ForUniform;
  28276. }
  28277. }
  28278. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  28279. // Properties
  28280. /**
  28281. * Indicates if the buffer is using the WebGL2 UBO implementation,
  28282. * or just falling back on setUniformXXX calls.
  28283. */
  28284. get: function () {
  28285. return !this._noUBO;
  28286. },
  28287. enumerable: true,
  28288. configurable: true
  28289. });
  28290. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  28291. /**
  28292. * Indicates if the WebGL underlying uniform buffer is in sync
  28293. * with the javascript cache data.
  28294. */
  28295. get: function () {
  28296. return !this._needSync;
  28297. },
  28298. enumerable: true,
  28299. configurable: true
  28300. });
  28301. /**
  28302. * Indicates if the WebGL underlying uniform buffer is dynamic.
  28303. * Also, a dynamic UniformBuffer will disable cache verification and always
  28304. * update the underlying WebGL uniform buffer to the GPU.
  28305. */
  28306. UniformBuffer.prototype.isDynamic = function () {
  28307. return this._dynamic !== undefined;
  28308. };
  28309. /**
  28310. * The data cache on JS side.
  28311. */
  28312. UniformBuffer.prototype.getData = function () {
  28313. return this._bufferData;
  28314. };
  28315. /**
  28316. * The underlying WebGL Uniform buffer.
  28317. */
  28318. UniformBuffer.prototype.getBuffer = function () {
  28319. return this._buffer;
  28320. };
  28321. /**
  28322. * std140 layout specifies how to align data within an UBO structure.
  28323. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  28324. * for specs.
  28325. */
  28326. UniformBuffer.prototype._fillAlignment = function (size) {
  28327. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  28328. // and 4x4 matrices
  28329. // TODO : change if other types are used
  28330. var alignment;
  28331. if (size <= 2) {
  28332. alignment = size;
  28333. }
  28334. else {
  28335. alignment = 4;
  28336. }
  28337. if ((this._uniformLocationPointer % alignment) !== 0) {
  28338. var oldPointer = this._uniformLocationPointer;
  28339. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  28340. var diff = this._uniformLocationPointer - oldPointer;
  28341. for (var i = 0; i < diff; i++) {
  28342. this._data.push(0);
  28343. }
  28344. }
  28345. };
  28346. /**
  28347. * Adds an uniform in the buffer.
  28348. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  28349. * for the layout to be correct !
  28350. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28351. * @param {number|number[]} size Data size, or data directly.
  28352. */
  28353. UniformBuffer.prototype.addUniform = function (name, size) {
  28354. if (this._noUBO) {
  28355. return;
  28356. }
  28357. if (this._uniformLocations[name] !== undefined) {
  28358. // Already existing uniform
  28359. return;
  28360. }
  28361. // This function must be called in the order of the shader layout !
  28362. // size can be the size of the uniform, or data directly
  28363. var data;
  28364. if (size instanceof Array) {
  28365. data = size;
  28366. size = data.length;
  28367. }
  28368. else {
  28369. size = size;
  28370. data = [];
  28371. // Fill with zeros
  28372. for (var i = 0; i < size; i++) {
  28373. data.push(0);
  28374. }
  28375. }
  28376. this._fillAlignment(size);
  28377. this._uniformSizes[name] = size;
  28378. this._uniformLocations[name] = this._uniformLocationPointer;
  28379. this._uniformLocationPointer += size;
  28380. for (var i = 0; i < size; i++) {
  28381. this._data.push(data[i]);
  28382. }
  28383. this._needSync = true;
  28384. };
  28385. /**
  28386. * Wrapper for addUniform.
  28387. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28388. * @param {Matrix} mat A 4x4 matrix.
  28389. */
  28390. UniformBuffer.prototype.addMatrix = function (name, mat) {
  28391. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  28392. };
  28393. /**
  28394. * Wrapper for addUniform.
  28395. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28396. * @param {number} x
  28397. * @param {number} y
  28398. */
  28399. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  28400. var temp = [x, y];
  28401. this.addUniform(name, temp);
  28402. };
  28403. /**
  28404. * Wrapper for addUniform.
  28405. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28406. * @param {number} x
  28407. * @param {number} y
  28408. * @param {number} z
  28409. */
  28410. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  28411. var temp = [x, y, z];
  28412. this.addUniform(name, temp);
  28413. };
  28414. /**
  28415. * Wrapper for addUniform.
  28416. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28417. * @param {Color3} color
  28418. */
  28419. UniformBuffer.prototype.addColor3 = function (name, color) {
  28420. var temp = new Array();
  28421. color.toArray(temp);
  28422. this.addUniform(name, temp);
  28423. };
  28424. /**
  28425. * Wrapper for addUniform.
  28426. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28427. * @param {Color3} color
  28428. * @param {number} alpha
  28429. */
  28430. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  28431. var temp = new Array();
  28432. color.toArray(temp);
  28433. temp.push(alpha);
  28434. this.addUniform(name, temp);
  28435. };
  28436. /**
  28437. * Wrapper for addUniform.
  28438. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28439. * @param {Vector3} vector
  28440. */
  28441. UniformBuffer.prototype.addVector3 = function (name, vector) {
  28442. var temp = new Array();
  28443. vector.toArray(temp);
  28444. this.addUniform(name, temp);
  28445. };
  28446. /**
  28447. * Wrapper for addUniform.
  28448. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28449. */
  28450. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  28451. this.addUniform(name, 12);
  28452. };
  28453. /**
  28454. * Wrapper for addUniform.
  28455. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28456. */
  28457. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  28458. this.addUniform(name, 8);
  28459. };
  28460. /**
  28461. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  28462. */
  28463. UniformBuffer.prototype.create = function () {
  28464. if (this._noUBO) {
  28465. return;
  28466. }
  28467. if (this._buffer) {
  28468. return; // nothing to do
  28469. }
  28470. // See spec, alignment must be filled as a vec4
  28471. this._fillAlignment(4);
  28472. this._bufferData = new Float32Array(this._data);
  28473. this._rebuild();
  28474. this._needSync = true;
  28475. };
  28476. UniformBuffer.prototype._rebuild = function () {
  28477. if (this._noUBO) {
  28478. return;
  28479. }
  28480. if (this._dynamic) {
  28481. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  28482. }
  28483. else {
  28484. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  28485. }
  28486. };
  28487. /**
  28488. * Updates the WebGL Uniform Buffer on the GPU.
  28489. * If the `dynamic` flag is set to true, no cache comparison is done.
  28490. * Otherwise, the buffer will be updated only if the cache differs.
  28491. */
  28492. UniformBuffer.prototype.update = function () {
  28493. if (!this._buffer) {
  28494. this.create();
  28495. return;
  28496. }
  28497. if (!this._dynamic && !this._needSync) {
  28498. return;
  28499. }
  28500. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  28501. this._needSync = false;
  28502. };
  28503. /**
  28504. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  28505. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  28506. * @param {number[]|Float32Array} data Flattened data
  28507. * @param {number} size Size of the data.
  28508. */
  28509. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  28510. var location = this._uniformLocations[uniformName];
  28511. if (location === undefined) {
  28512. if (this._buffer) {
  28513. // Cannot add an uniform if the buffer is already created
  28514. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  28515. return;
  28516. }
  28517. this.addUniform(uniformName, size);
  28518. location = this._uniformLocations[uniformName];
  28519. }
  28520. if (!this._buffer) {
  28521. this.create();
  28522. }
  28523. if (!this._dynamic) {
  28524. // Cache for static uniform buffers
  28525. var changed = false;
  28526. for (var i = 0; i < size; i++) {
  28527. if (this._bufferData[location + i] !== data[i]) {
  28528. changed = true;
  28529. this._bufferData[location + i] = data[i];
  28530. }
  28531. }
  28532. this._needSync = this._needSync || changed;
  28533. }
  28534. else {
  28535. // No cache for dynamic
  28536. for (var i = 0; i < size; i++) {
  28537. this._bufferData[location + i] = data[i];
  28538. }
  28539. }
  28540. };
  28541. // Update methods
  28542. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  28543. // To match std140, matrix must be realigned
  28544. for (var i = 0; i < 3; i++) {
  28545. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  28546. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  28547. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  28548. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  28549. }
  28550. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  28551. };
  28552. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  28553. this._currentEffect.setMatrix3x3(name, matrix);
  28554. };
  28555. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  28556. this._currentEffect.setMatrix2x2(name, matrix);
  28557. };
  28558. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  28559. // To match std140, matrix must be realigned
  28560. for (var i = 0; i < 2; i++) {
  28561. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  28562. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  28563. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  28564. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  28565. }
  28566. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  28567. };
  28568. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  28569. this._currentEffect.setFloat(name, x);
  28570. };
  28571. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  28572. UniformBuffer._tempBuffer[0] = x;
  28573. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  28574. };
  28575. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  28576. if (suffix === void 0) { suffix = ""; }
  28577. this._currentEffect.setFloat2(name + suffix, x, y);
  28578. };
  28579. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  28580. if (suffix === void 0) { suffix = ""; }
  28581. UniformBuffer._tempBuffer[0] = x;
  28582. UniformBuffer._tempBuffer[1] = y;
  28583. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  28584. };
  28585. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  28586. if (suffix === void 0) { suffix = ""; }
  28587. this._currentEffect.setFloat3(name + suffix, x, y, z);
  28588. };
  28589. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  28590. if (suffix === void 0) { suffix = ""; }
  28591. UniformBuffer._tempBuffer[0] = x;
  28592. UniformBuffer._tempBuffer[1] = y;
  28593. UniformBuffer._tempBuffer[2] = z;
  28594. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28595. };
  28596. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  28597. if (suffix === void 0) { suffix = ""; }
  28598. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  28599. };
  28600. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  28601. if (suffix === void 0) { suffix = ""; }
  28602. UniformBuffer._tempBuffer[0] = x;
  28603. UniformBuffer._tempBuffer[1] = y;
  28604. UniformBuffer._tempBuffer[2] = z;
  28605. UniformBuffer._tempBuffer[3] = w;
  28606. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28607. };
  28608. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  28609. this._currentEffect.setMatrix(name, mat);
  28610. };
  28611. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  28612. this.updateUniform(name, mat.toArray(), 16);
  28613. };
  28614. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  28615. this._currentEffect.setVector3(name, vector);
  28616. };
  28617. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  28618. vector.toArray(UniformBuffer._tempBuffer);
  28619. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28620. };
  28621. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  28622. this._currentEffect.setVector4(name, vector);
  28623. };
  28624. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  28625. vector.toArray(UniformBuffer._tempBuffer);
  28626. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28627. };
  28628. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  28629. if (suffix === void 0) { suffix = ""; }
  28630. this._currentEffect.setColor3(name + suffix, color);
  28631. };
  28632. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  28633. if (suffix === void 0) { suffix = ""; }
  28634. color.toArray(UniformBuffer._tempBuffer);
  28635. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28636. };
  28637. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  28638. if (suffix === void 0) { suffix = ""; }
  28639. this._currentEffect.setColor4(name + suffix, color, alpha);
  28640. };
  28641. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  28642. if (suffix === void 0) { suffix = ""; }
  28643. color.toArray(UniformBuffer._tempBuffer);
  28644. UniformBuffer._tempBuffer[3] = alpha;
  28645. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28646. };
  28647. /**
  28648. * Sets a sampler uniform on the effect.
  28649. * @param {string} name Name of the sampler.
  28650. * @param {Texture} texture
  28651. */
  28652. UniformBuffer.prototype.setTexture = function (name, texture) {
  28653. this._currentEffect.setTexture(name, texture);
  28654. };
  28655. /**
  28656. * Directly updates the value of the uniform in the cache AND on the GPU.
  28657. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  28658. * @param {number[]|Float32Array} data Flattened data
  28659. */
  28660. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  28661. this.updateUniform(uniformName, data, data.length);
  28662. this.update();
  28663. };
  28664. /**
  28665. * Binds this uniform buffer to an effect.
  28666. * @param {Effect} effect
  28667. * @param {string} name Name of the uniform block in the shader.
  28668. */
  28669. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  28670. this._currentEffect = effect;
  28671. if (this._noUBO || !this._buffer) {
  28672. return;
  28673. }
  28674. effect.bindUniformBuffer(this._buffer, name);
  28675. };
  28676. /**
  28677. * Disposes the uniform buffer.
  28678. */
  28679. UniformBuffer.prototype.dispose = function () {
  28680. if (this._noUBO) {
  28681. return;
  28682. }
  28683. var index = this._engine._uniformBuffers.indexOf(this);
  28684. if (index !== -1) {
  28685. this._engine._uniformBuffers.splice(index, 1);
  28686. }
  28687. if (!this._buffer) {
  28688. return;
  28689. }
  28690. if (this._engine._releaseBuffer(this._buffer)) {
  28691. this._buffer = null;
  28692. }
  28693. };
  28694. // Pool for avoiding memory leaks
  28695. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  28696. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  28697. return UniformBuffer;
  28698. }());
  28699. BABYLON.UniformBuffer = UniformBuffer;
  28700. })(BABYLON || (BABYLON = {}));
  28701. //# sourceMappingURL=babylon.uniformBuffer.js.map
  28702. var BABYLON;
  28703. (function (BABYLON) {
  28704. var PushMaterial = /** @class */ (function (_super) {
  28705. __extends(PushMaterial, _super);
  28706. function PushMaterial(name, scene) {
  28707. var _this = _super.call(this, name, scene) || this;
  28708. _this.storeEffectOnSubMeshes = true;
  28709. return _this;
  28710. }
  28711. PushMaterial.prototype.getEffect = function () {
  28712. return this._activeEffect;
  28713. };
  28714. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  28715. if (!mesh) {
  28716. return false;
  28717. }
  28718. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  28719. return true;
  28720. }
  28721. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  28722. };
  28723. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  28724. this._activeEffect.setMatrix("world", world);
  28725. };
  28726. PushMaterial.prototype.bind = function (world, mesh) {
  28727. if (!mesh) {
  28728. return;
  28729. }
  28730. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  28731. };
  28732. PushMaterial.prototype._afterBind = function (mesh, effect) {
  28733. if (effect === void 0) { effect = null; }
  28734. _super.prototype._afterBind.call(this, mesh);
  28735. this.getScene()._cachedEffect = effect;
  28736. };
  28737. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  28738. if (visibility === void 0) { visibility = 1; }
  28739. return scene.isCachedMaterialInvalid(this, effect, visibility);
  28740. };
  28741. return PushMaterial;
  28742. }(BABYLON.Material));
  28743. BABYLON.PushMaterial = PushMaterial;
  28744. })(BABYLON || (BABYLON = {}));
  28745. //# sourceMappingURL=babylon.pushMaterial.js.map
  28746. var BABYLON;
  28747. (function (BABYLON) {
  28748. var VertexData = /** @class */ (function () {
  28749. function VertexData() {
  28750. }
  28751. VertexData.prototype.set = function (data, kind) {
  28752. switch (kind) {
  28753. case BABYLON.VertexBuffer.PositionKind:
  28754. this.positions = data;
  28755. break;
  28756. case BABYLON.VertexBuffer.NormalKind:
  28757. this.normals = data;
  28758. break;
  28759. case BABYLON.VertexBuffer.TangentKind:
  28760. this.tangents = data;
  28761. break;
  28762. case BABYLON.VertexBuffer.UVKind:
  28763. this.uvs = data;
  28764. break;
  28765. case BABYLON.VertexBuffer.UV2Kind:
  28766. this.uvs2 = data;
  28767. break;
  28768. case BABYLON.VertexBuffer.UV3Kind:
  28769. this.uvs3 = data;
  28770. break;
  28771. case BABYLON.VertexBuffer.UV4Kind:
  28772. this.uvs4 = data;
  28773. break;
  28774. case BABYLON.VertexBuffer.UV5Kind:
  28775. this.uvs5 = data;
  28776. break;
  28777. case BABYLON.VertexBuffer.UV6Kind:
  28778. this.uvs6 = data;
  28779. break;
  28780. case BABYLON.VertexBuffer.ColorKind:
  28781. this.colors = data;
  28782. break;
  28783. case BABYLON.VertexBuffer.MatricesIndicesKind:
  28784. this.matricesIndices = data;
  28785. break;
  28786. case BABYLON.VertexBuffer.MatricesWeightsKind:
  28787. this.matricesWeights = data;
  28788. break;
  28789. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  28790. this.matricesIndicesExtra = data;
  28791. break;
  28792. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  28793. this.matricesWeightsExtra = data;
  28794. break;
  28795. }
  28796. };
  28797. /**
  28798. * Associates the vertexData to the passed Mesh.
  28799. * Sets it as updatable or not (default `false`).
  28800. * Returns the VertexData.
  28801. */
  28802. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  28803. this._applyTo(mesh, updatable);
  28804. return this;
  28805. };
  28806. /**
  28807. * Associates the vertexData to the passed Geometry.
  28808. * Sets it as updatable or not (default `false`).
  28809. * Returns the VertexData.
  28810. */
  28811. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  28812. this._applyTo(geometry, updatable);
  28813. return this;
  28814. };
  28815. /**
  28816. * Updates the associated mesh.
  28817. * Returns the VertexData.
  28818. */
  28819. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  28820. this._update(mesh);
  28821. return this;
  28822. };
  28823. /**
  28824. * Updates the associated geometry.
  28825. * Returns the VertexData.
  28826. */
  28827. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  28828. this._update(geometry);
  28829. return this;
  28830. };
  28831. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  28832. if (updatable === void 0) { updatable = false; }
  28833. if (this.positions) {
  28834. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  28835. }
  28836. if (this.normals) {
  28837. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  28838. }
  28839. if (this.tangents) {
  28840. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  28841. }
  28842. if (this.uvs) {
  28843. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  28844. }
  28845. if (this.uvs2) {
  28846. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  28847. }
  28848. if (this.uvs3) {
  28849. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  28850. }
  28851. if (this.uvs4) {
  28852. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  28853. }
  28854. if (this.uvs5) {
  28855. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  28856. }
  28857. if (this.uvs6) {
  28858. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  28859. }
  28860. if (this.colors) {
  28861. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  28862. }
  28863. if (this.matricesIndices) {
  28864. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  28865. }
  28866. if (this.matricesWeights) {
  28867. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  28868. }
  28869. if (this.matricesIndicesExtra) {
  28870. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  28871. }
  28872. if (this.matricesWeightsExtra) {
  28873. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  28874. }
  28875. if (this.indices) {
  28876. meshOrGeometry.setIndices(this.indices, null, updatable);
  28877. }
  28878. return this;
  28879. };
  28880. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  28881. if (this.positions) {
  28882. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  28883. }
  28884. if (this.normals) {
  28885. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  28886. }
  28887. if (this.tangents) {
  28888. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  28889. }
  28890. if (this.uvs) {
  28891. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  28892. }
  28893. if (this.uvs2) {
  28894. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  28895. }
  28896. if (this.uvs3) {
  28897. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  28898. }
  28899. if (this.uvs4) {
  28900. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  28901. }
  28902. if (this.uvs5) {
  28903. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  28904. }
  28905. if (this.uvs6) {
  28906. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  28907. }
  28908. if (this.colors) {
  28909. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  28910. }
  28911. if (this.matricesIndices) {
  28912. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  28913. }
  28914. if (this.matricesWeights) {
  28915. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  28916. }
  28917. if (this.matricesIndicesExtra) {
  28918. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  28919. }
  28920. if (this.matricesWeightsExtra) {
  28921. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  28922. }
  28923. if (this.indices) {
  28924. meshOrGeometry.setIndices(this.indices, null);
  28925. }
  28926. return this;
  28927. };
  28928. /**
  28929. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  28930. * Returns the VertexData.
  28931. */
  28932. VertexData.prototype.transform = function (matrix) {
  28933. var transformed = BABYLON.Vector3.Zero();
  28934. var index;
  28935. if (this.positions) {
  28936. var position = BABYLON.Vector3.Zero();
  28937. for (index = 0; index < this.positions.length; index += 3) {
  28938. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  28939. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  28940. this.positions[index] = transformed.x;
  28941. this.positions[index + 1] = transformed.y;
  28942. this.positions[index + 2] = transformed.z;
  28943. }
  28944. }
  28945. if (this.normals) {
  28946. var normal = BABYLON.Vector3.Zero();
  28947. for (index = 0; index < this.normals.length; index += 3) {
  28948. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  28949. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  28950. this.normals[index] = transformed.x;
  28951. this.normals[index + 1] = transformed.y;
  28952. this.normals[index + 2] = transformed.z;
  28953. }
  28954. }
  28955. if (this.tangents) {
  28956. var tangent = BABYLON.Vector4.Zero();
  28957. var tangentTransformed = BABYLON.Vector4.Zero();
  28958. for (index = 0; index < this.tangents.length; index += 4) {
  28959. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  28960. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  28961. this.tangents[index] = tangentTransformed.x;
  28962. this.tangents[index + 1] = tangentTransformed.y;
  28963. this.tangents[index + 2] = tangentTransformed.z;
  28964. this.tangents[index + 3] = tangentTransformed.w;
  28965. }
  28966. }
  28967. return this;
  28968. };
  28969. /**
  28970. * Merges the passed VertexData into the current one.
  28971. * Returns the modified VertexData.
  28972. */
  28973. VertexData.prototype.merge = function (other, options) {
  28974. options = options || {};
  28975. if (other.indices) {
  28976. if (!this.indices) {
  28977. this.indices = [];
  28978. }
  28979. var offset = this.positions ? this.positions.length / 3 : 0;
  28980. for (var index = 0; index < other.indices.length; index++) {
  28981. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  28982. this.indices.push(other.indices[index] + offset);
  28983. }
  28984. }
  28985. this.positions = this._mergeElement(this.positions, other.positions);
  28986. if (!this.positions) {
  28987. return this;
  28988. }
  28989. var count = this.positions.length / 3;
  28990. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  28991. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  28992. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  28993. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  28994. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  28995. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  28996. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  28997. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  28998. this.colors = this._mergeElement(this.colors, other.colors, count * 4, 1);
  28999. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  29000. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  29001. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  29002. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  29003. return this;
  29004. };
  29005. VertexData.prototype._mergeElement = function (source, other, length, defaultValue) {
  29006. if (length === void 0) { length = 0; }
  29007. if (defaultValue === void 0) { defaultValue = 0; }
  29008. if (!other && !source) {
  29009. return null;
  29010. }
  29011. if (!other) {
  29012. var padding = new Float32Array(source.length);
  29013. padding.fill(defaultValue);
  29014. return this._mergeElement(source, padding, length);
  29015. }
  29016. if (!source) {
  29017. if (length === 0 || length === other.length) {
  29018. return other;
  29019. }
  29020. var padding = new Float32Array(length - other.length);
  29021. padding.fill(defaultValue);
  29022. return this._mergeElement(padding, other, length);
  29023. }
  29024. var len = other.length + source.length;
  29025. var isSrcTypedArray = source instanceof Float32Array;
  29026. var isOthTypedArray = other instanceof Float32Array;
  29027. // use non-loop method when the source is Float32Array
  29028. if (isSrcTypedArray) {
  29029. var ret32 = new Float32Array(len);
  29030. ret32.set(source);
  29031. ret32.set(other, source.length);
  29032. return ret32;
  29033. // source is number[], when other is also use concat
  29034. }
  29035. else if (!isOthTypedArray) {
  29036. return source.concat(other);
  29037. // source is a number[], but other is a Float32Array, loop required
  29038. }
  29039. else {
  29040. var ret = source.slice(0); // copy source to a separate array
  29041. for (var i = 0, len = other.length; i < len; i++) {
  29042. ret.push(other[i]);
  29043. }
  29044. return ret;
  29045. }
  29046. };
  29047. /**
  29048. * Serializes the VertexData.
  29049. * Returns a serialized object.
  29050. */
  29051. VertexData.prototype.serialize = function () {
  29052. var serializationObject = this.serialize();
  29053. if (this.positions) {
  29054. serializationObject.positions = this.positions;
  29055. }
  29056. if (this.normals) {
  29057. serializationObject.normals = this.normals;
  29058. }
  29059. if (this.tangents) {
  29060. serializationObject.tangents = this.tangents;
  29061. }
  29062. if (this.uvs) {
  29063. serializationObject.uvs = this.uvs;
  29064. }
  29065. if (this.uvs2) {
  29066. serializationObject.uvs2 = this.uvs2;
  29067. }
  29068. if (this.uvs3) {
  29069. serializationObject.uvs3 = this.uvs3;
  29070. }
  29071. if (this.uvs4) {
  29072. serializationObject.uvs4 = this.uvs4;
  29073. }
  29074. if (this.uvs5) {
  29075. serializationObject.uvs5 = this.uvs5;
  29076. }
  29077. if (this.uvs6) {
  29078. serializationObject.uvs6 = this.uvs6;
  29079. }
  29080. if (this.colors) {
  29081. serializationObject.colors = this.colors;
  29082. }
  29083. if (this.matricesIndices) {
  29084. serializationObject.matricesIndices = this.matricesIndices;
  29085. serializationObject.matricesIndices._isExpanded = true;
  29086. }
  29087. if (this.matricesWeights) {
  29088. serializationObject.matricesWeights = this.matricesWeights;
  29089. }
  29090. if (this.matricesIndicesExtra) {
  29091. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  29092. serializationObject.matricesIndicesExtra._isExpanded = true;
  29093. }
  29094. if (this.matricesWeightsExtra) {
  29095. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  29096. }
  29097. serializationObject.indices = this.indices;
  29098. return serializationObject;
  29099. };
  29100. // Statics
  29101. /**
  29102. * Returns the object VertexData associated to the passed mesh.
  29103. */
  29104. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  29105. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  29106. };
  29107. /**
  29108. * Returns the object VertexData associated to the passed geometry.
  29109. */
  29110. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  29111. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  29112. };
  29113. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  29114. var result = new VertexData();
  29115. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29116. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  29117. }
  29118. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29119. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  29120. }
  29121. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  29122. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  29123. }
  29124. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29125. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  29126. }
  29127. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29128. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  29129. }
  29130. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29131. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  29132. }
  29133. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29134. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  29135. }
  29136. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29137. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  29138. }
  29139. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29140. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  29141. }
  29142. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29143. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  29144. }
  29145. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29146. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  29147. }
  29148. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29149. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  29150. }
  29151. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  29152. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  29153. }
  29154. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  29155. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  29156. }
  29157. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  29158. return result;
  29159. };
  29160. /**
  29161. * Creates the vertexData of the Ribbon.
  29162. */
  29163. VertexData.CreateRibbon = function (options) {
  29164. var pathArray = options.pathArray;
  29165. var closeArray = options.closeArray || false;
  29166. var closePath = options.closePath || false;
  29167. var invertUV = options.invertUV || false;
  29168. var defaultOffset = Math.floor(pathArray[0].length / 2);
  29169. var offset = options.offset || defaultOffset;
  29170. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  29171. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29172. var customUV = options.uvs;
  29173. var customColors = options.colors;
  29174. var positions = [];
  29175. var indices = [];
  29176. var normals = [];
  29177. var uvs = [];
  29178. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  29179. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  29180. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  29181. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  29182. var minlg; // minimal length among all paths from pathArray
  29183. var lg = []; // array of path lengths : nb of vertex per path
  29184. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  29185. var p; // path iterator
  29186. var i; // point iterator
  29187. var j; // point iterator
  29188. // if single path in pathArray
  29189. if (pathArray.length < 2) {
  29190. var ar1 = [];
  29191. var ar2 = [];
  29192. for (i = 0; i < pathArray[0].length - offset; i++) {
  29193. ar1.push(pathArray[0][i]);
  29194. ar2.push(pathArray[0][i + offset]);
  29195. }
  29196. pathArray = [ar1, ar2];
  29197. }
  29198. // positions and horizontal distances (u)
  29199. var idc = 0;
  29200. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  29201. var path;
  29202. var l;
  29203. minlg = pathArray[0].length;
  29204. var vectlg;
  29205. var dist;
  29206. for (p = 0; p < pathArray.length; p++) {
  29207. uTotalDistance[p] = 0;
  29208. us[p] = [0];
  29209. path = pathArray[p];
  29210. l = path.length;
  29211. minlg = (minlg < l) ? minlg : l;
  29212. j = 0;
  29213. while (j < l) {
  29214. positions.push(path[j].x, path[j].y, path[j].z);
  29215. if (j > 0) {
  29216. vectlg = path[j].subtract(path[j - 1]).length();
  29217. dist = vectlg + uTotalDistance[p];
  29218. us[p].push(dist);
  29219. uTotalDistance[p] = dist;
  29220. }
  29221. j++;
  29222. }
  29223. if (closePath) {
  29224. j--;
  29225. positions.push(path[0].x, path[0].y, path[0].z);
  29226. vectlg = path[j].subtract(path[0]).length();
  29227. dist = vectlg + uTotalDistance[p];
  29228. us[p].push(dist);
  29229. uTotalDistance[p] = dist;
  29230. }
  29231. lg[p] = l + closePathCorr;
  29232. idx[p] = idc;
  29233. idc += (l + closePathCorr);
  29234. }
  29235. // vertical distances (v)
  29236. var path1;
  29237. var path2;
  29238. var vertex1 = null;
  29239. var vertex2 = null;
  29240. for (i = 0; i < minlg + closePathCorr; i++) {
  29241. vTotalDistance[i] = 0;
  29242. vs[i] = [0];
  29243. for (p = 0; p < pathArray.length - 1; p++) {
  29244. path1 = pathArray[p];
  29245. path2 = pathArray[p + 1];
  29246. if (i === minlg) {
  29247. vertex1 = path1[0];
  29248. vertex2 = path2[0];
  29249. }
  29250. else {
  29251. vertex1 = path1[i];
  29252. vertex2 = path2[i];
  29253. }
  29254. vectlg = vertex2.subtract(vertex1).length();
  29255. dist = vectlg + vTotalDistance[i];
  29256. vs[i].push(dist);
  29257. vTotalDistance[i] = dist;
  29258. }
  29259. if (closeArray && vertex2 && vertex1) {
  29260. path1 = pathArray[p];
  29261. path2 = pathArray[0];
  29262. if (i === minlg) {
  29263. vertex2 = path2[0];
  29264. }
  29265. vectlg = vertex2.subtract(vertex1).length();
  29266. dist = vectlg + vTotalDistance[i];
  29267. vTotalDistance[i] = dist;
  29268. }
  29269. }
  29270. // uvs
  29271. var u;
  29272. var v;
  29273. if (customUV) {
  29274. for (p = 0; p < customUV.length; p++) {
  29275. uvs.push(customUV[p].x, customUV[p].y);
  29276. }
  29277. }
  29278. else {
  29279. for (p = 0; p < pathArray.length; p++) {
  29280. for (i = 0; i < minlg + closePathCorr; i++) {
  29281. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  29282. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  29283. if (invertUV) {
  29284. uvs.push(v, u);
  29285. }
  29286. else {
  29287. uvs.push(u, v);
  29288. }
  29289. }
  29290. }
  29291. }
  29292. // indices
  29293. p = 0; // path index
  29294. var pi = 0; // positions array index
  29295. var l1 = lg[p] - 1; // path1 length
  29296. var l2 = lg[p + 1] - 1; // path2 length
  29297. var min = (l1 < l2) ? l1 : l2; // current path stop index
  29298. var shft = idx[1] - idx[0]; // shift
  29299. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  29300. while (pi <= min && p < path1nb) {
  29301. // 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
  29302. indices.push(pi, pi + shft, pi + 1);
  29303. indices.push(pi + shft + 1, pi + 1, pi + shft);
  29304. pi += 1;
  29305. if (pi === min) {
  29306. p++;
  29307. if (p === lg.length - 1) {
  29308. shft = idx[0] - idx[p];
  29309. l1 = lg[p] - 1;
  29310. l2 = lg[0] - 1;
  29311. }
  29312. else {
  29313. shft = idx[p + 1] - idx[p];
  29314. l1 = lg[p] - 1;
  29315. l2 = lg[p + 1] - 1;
  29316. }
  29317. pi = idx[p];
  29318. min = (l1 < l2) ? l1 + pi : l2 + pi;
  29319. }
  29320. }
  29321. // normals
  29322. VertexData.ComputeNormals(positions, indices, normals);
  29323. if (closePath) {
  29324. var indexFirst = 0;
  29325. var indexLast = 0;
  29326. for (p = 0; p < pathArray.length; p++) {
  29327. indexFirst = idx[p] * 3;
  29328. if (p + 1 < pathArray.length) {
  29329. indexLast = (idx[p + 1] - 1) * 3;
  29330. }
  29331. else {
  29332. indexLast = normals.length - 3;
  29333. }
  29334. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  29335. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  29336. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  29337. normals[indexLast] = normals[indexFirst];
  29338. normals[indexLast + 1] = normals[indexFirst + 1];
  29339. normals[indexLast + 2] = normals[indexFirst + 2];
  29340. }
  29341. }
  29342. // sides
  29343. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29344. // Colors
  29345. var colors = null;
  29346. if (customColors) {
  29347. colors = new Float32Array(customColors.length * 4);
  29348. for (var c = 0; c < customColors.length; c++) {
  29349. colors[c * 4] = customColors[c].r;
  29350. colors[c * 4 + 1] = customColors[c].g;
  29351. colors[c * 4 + 2] = customColors[c].b;
  29352. colors[c * 4 + 3] = customColors[c].a;
  29353. }
  29354. }
  29355. // Result
  29356. var vertexData = new VertexData();
  29357. var positions32 = new Float32Array(positions);
  29358. var normals32 = new Float32Array(normals);
  29359. var uvs32 = new Float32Array(uvs);
  29360. vertexData.indices = indices;
  29361. vertexData.positions = positions32;
  29362. vertexData.normals = normals32;
  29363. vertexData.uvs = uvs32;
  29364. if (colors) {
  29365. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  29366. }
  29367. if (closePath) {
  29368. vertexData._idx = idx;
  29369. }
  29370. return vertexData;
  29371. };
  29372. /**
  29373. * Creates the VertexData of the Box.
  29374. */
  29375. VertexData.CreateBox = function (options) {
  29376. var normalsSource = [
  29377. new BABYLON.Vector3(0, 0, 1),
  29378. new BABYLON.Vector3(0, 0, -1),
  29379. new BABYLON.Vector3(1, 0, 0),
  29380. new BABYLON.Vector3(-1, 0, 0),
  29381. new BABYLON.Vector3(0, 1, 0),
  29382. new BABYLON.Vector3(0, -1, 0)
  29383. ];
  29384. var indices = [];
  29385. var positions = [];
  29386. var normals = [];
  29387. var uvs = [];
  29388. var width = options.width || options.size || 1;
  29389. var height = options.height || options.size || 1;
  29390. var depth = options.depth || options.size || 1;
  29391. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29392. var faceUV = options.faceUV || new Array(6);
  29393. var faceColors = options.faceColors;
  29394. var colors = [];
  29395. // default face colors and UV if undefined
  29396. for (var f = 0; f < 6; f++) {
  29397. if (faceUV[f] === undefined) {
  29398. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29399. }
  29400. if (faceColors && faceColors[f] === undefined) {
  29401. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29402. }
  29403. }
  29404. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  29405. // Create each face in turn.
  29406. for (var index = 0; index < normalsSource.length; index++) {
  29407. var normal = normalsSource[index];
  29408. // Get two vectors perpendicular to the face normal and to each other.
  29409. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  29410. var side2 = BABYLON.Vector3.Cross(normal, side1);
  29411. // Six indices (two triangles) per face.
  29412. var verticesLength = positions.length / 3;
  29413. indices.push(verticesLength);
  29414. indices.push(verticesLength + 1);
  29415. indices.push(verticesLength + 2);
  29416. indices.push(verticesLength);
  29417. indices.push(verticesLength + 2);
  29418. indices.push(verticesLength + 3);
  29419. // Four vertices per face.
  29420. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  29421. positions.push(vertex.x, vertex.y, vertex.z);
  29422. normals.push(normal.x, normal.y, normal.z);
  29423. uvs.push(faceUV[index].z, faceUV[index].w);
  29424. if (faceColors) {
  29425. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29426. }
  29427. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  29428. positions.push(vertex.x, vertex.y, vertex.z);
  29429. normals.push(normal.x, normal.y, normal.z);
  29430. uvs.push(faceUV[index].x, faceUV[index].w);
  29431. if (faceColors) {
  29432. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29433. }
  29434. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  29435. positions.push(vertex.x, vertex.y, vertex.z);
  29436. normals.push(normal.x, normal.y, normal.z);
  29437. uvs.push(faceUV[index].x, faceUV[index].y);
  29438. if (faceColors) {
  29439. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29440. }
  29441. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  29442. positions.push(vertex.x, vertex.y, vertex.z);
  29443. normals.push(normal.x, normal.y, normal.z);
  29444. uvs.push(faceUV[index].z, faceUV[index].y);
  29445. if (faceColors) {
  29446. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29447. }
  29448. }
  29449. // sides
  29450. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29451. // Result
  29452. var vertexData = new VertexData();
  29453. vertexData.indices = indices;
  29454. vertexData.positions = positions;
  29455. vertexData.normals = normals;
  29456. vertexData.uvs = uvs;
  29457. if (faceColors) {
  29458. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  29459. vertexData.colors = totalColors;
  29460. }
  29461. return vertexData;
  29462. };
  29463. /**
  29464. * Creates the VertexData of the Sphere.
  29465. */
  29466. VertexData.CreateSphere = function (options) {
  29467. var segments = options.segments || 32;
  29468. var diameterX = options.diameterX || options.diameter || 1;
  29469. var diameterY = options.diameterY || options.diameter || 1;
  29470. var diameterZ = options.diameterZ || options.diameter || 1;
  29471. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29472. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  29473. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29474. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  29475. var totalZRotationSteps = 2 + segments;
  29476. var totalYRotationSteps = 2 * totalZRotationSteps;
  29477. var indices = [];
  29478. var positions = [];
  29479. var normals = [];
  29480. var uvs = [];
  29481. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  29482. var normalizedZ = zRotationStep / totalZRotationSteps;
  29483. var angleZ = normalizedZ * Math.PI * slice;
  29484. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  29485. var normalizedY = yRotationStep / totalYRotationSteps;
  29486. var angleY = normalizedY * Math.PI * 2 * arc;
  29487. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  29488. var rotationY = BABYLON.Matrix.RotationY(angleY);
  29489. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  29490. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  29491. var vertex = complete.multiply(radius);
  29492. var normal = complete.divide(radius).normalize();
  29493. positions.push(vertex.x, vertex.y, vertex.z);
  29494. normals.push(normal.x, normal.y, normal.z);
  29495. uvs.push(normalizedY, normalizedZ);
  29496. }
  29497. if (zRotationStep > 0) {
  29498. var verticesCount = positions.length / 3;
  29499. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  29500. indices.push((firstIndex));
  29501. indices.push((firstIndex + 1));
  29502. indices.push(firstIndex + totalYRotationSteps + 1);
  29503. indices.push((firstIndex + totalYRotationSteps + 1));
  29504. indices.push((firstIndex + 1));
  29505. indices.push((firstIndex + totalYRotationSteps + 2));
  29506. }
  29507. }
  29508. }
  29509. // Sides
  29510. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29511. // Result
  29512. var vertexData = new VertexData();
  29513. vertexData.indices = indices;
  29514. vertexData.positions = positions;
  29515. vertexData.normals = normals;
  29516. vertexData.uvs = uvs;
  29517. return vertexData;
  29518. };
  29519. /**
  29520. * Creates the VertexData of the Cylinder or Cone.
  29521. */
  29522. VertexData.CreateCylinder = function (options) {
  29523. var height = options.height || 2;
  29524. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  29525. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  29526. var tessellation = options.tessellation || 24;
  29527. var subdivisions = options.subdivisions || 1;
  29528. var hasRings = options.hasRings ? true : false;
  29529. var enclose = options.enclose ? true : false;
  29530. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29531. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29532. var faceUV = options.faceUV || new Array(3);
  29533. var faceColors = options.faceColors;
  29534. // default face colors and UV if undefined
  29535. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  29536. var ringNb = (hasRings) ? subdivisions : 1;
  29537. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  29538. var f;
  29539. for (f = 0; f < surfaceNb; f++) {
  29540. if (faceColors && faceColors[f] === undefined) {
  29541. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29542. }
  29543. }
  29544. for (f = 0; f < surfaceNb; f++) {
  29545. if (faceUV && faceUV[f] === undefined) {
  29546. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29547. }
  29548. }
  29549. var indices = new Array();
  29550. var positions = new Array();
  29551. var normals = new Array();
  29552. var uvs = new Array();
  29553. var colors = new Array();
  29554. var angle_step = Math.PI * 2 * arc / tessellation;
  29555. var angle;
  29556. var h;
  29557. var radius;
  29558. var tan = (diameterBottom - diameterTop) / 2 / height;
  29559. var ringVertex = BABYLON.Vector3.Zero();
  29560. var ringNormal = BABYLON.Vector3.Zero();
  29561. var ringFirstVertex = BABYLON.Vector3.Zero();
  29562. var ringFirstNormal = BABYLON.Vector3.Zero();
  29563. var quadNormal = BABYLON.Vector3.Zero();
  29564. var Y = BABYLON.Axis.Y;
  29565. // positions, normals, uvs
  29566. var i;
  29567. var j;
  29568. var r;
  29569. var ringIdx = 1;
  29570. var s = 1; // surface index
  29571. var cs = 0;
  29572. var v = 0;
  29573. for (i = 0; i <= subdivisions; i++) {
  29574. h = i / subdivisions;
  29575. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  29576. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  29577. for (r = 0; r < ringIdx; r++) {
  29578. if (hasRings) {
  29579. s += r;
  29580. }
  29581. if (enclose) {
  29582. s += 2 * r;
  29583. }
  29584. for (j = 0; j <= tessellation; j++) {
  29585. angle = j * angle_step;
  29586. // position
  29587. ringVertex.x = Math.cos(-angle) * radius;
  29588. ringVertex.y = -height / 2 + h * height;
  29589. ringVertex.z = Math.sin(-angle) * radius;
  29590. // normal
  29591. if (diameterTop === 0 && i === subdivisions) {
  29592. // if no top cap, reuse former normals
  29593. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  29594. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  29595. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  29596. }
  29597. else {
  29598. ringNormal.x = ringVertex.x;
  29599. ringNormal.z = ringVertex.z;
  29600. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  29601. ringNormal.normalize();
  29602. }
  29603. // keep first ring vertex values for enclose
  29604. if (j === 0) {
  29605. ringFirstVertex.copyFrom(ringVertex);
  29606. ringFirstNormal.copyFrom(ringNormal);
  29607. }
  29608. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29609. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  29610. if (hasRings) {
  29611. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  29612. }
  29613. else {
  29614. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  29615. }
  29616. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  29617. if (faceColors) {
  29618. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  29619. }
  29620. }
  29621. // if enclose, add four vertices and their dedicated normals
  29622. if (arc !== 1 && enclose) {
  29623. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29624. positions.push(0, ringVertex.y, 0);
  29625. positions.push(0, ringVertex.y, 0);
  29626. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  29627. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  29628. quadNormal.normalize();
  29629. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29630. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  29631. quadNormal.normalize();
  29632. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29633. if (hasRings) {
  29634. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  29635. }
  29636. else {
  29637. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  29638. }
  29639. uvs.push(faceUV[s + 1].x, v);
  29640. uvs.push(faceUV[s + 1].z, v);
  29641. if (hasRings) {
  29642. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  29643. }
  29644. else {
  29645. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  29646. }
  29647. uvs.push(faceUV[s + 2].x, v);
  29648. uvs.push(faceUV[s + 2].z, v);
  29649. if (faceColors) {
  29650. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29651. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29652. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29653. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29654. }
  29655. }
  29656. if (cs !== s) {
  29657. cs = s;
  29658. }
  29659. }
  29660. }
  29661. // indices
  29662. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  29663. var s;
  29664. i = 0;
  29665. for (s = 0; s < subdivisions; s++) {
  29666. var i0 = 0;
  29667. var i1 = 0;
  29668. var i2 = 0;
  29669. var i3 = 0;
  29670. for (j = 0; j < tessellation; j++) {
  29671. i0 = i * (e + 1) + j;
  29672. i1 = (i + 1) * (e + 1) + j;
  29673. i2 = i * (e + 1) + (j + 1);
  29674. i3 = (i + 1) * (e + 1) + (j + 1);
  29675. indices.push(i0, i1, i2);
  29676. indices.push(i3, i2, i1);
  29677. }
  29678. if (arc !== 1 && enclose) {
  29679. indices.push(i0 + 2, i1 + 2, i2 + 2);
  29680. indices.push(i3 + 2, i2 + 2, i1 + 2);
  29681. indices.push(i0 + 4, i1 + 4, i2 + 4);
  29682. indices.push(i3 + 4, i2 + 4, i1 + 4);
  29683. }
  29684. i = (hasRings) ? (i + 2) : (i + 1);
  29685. }
  29686. // Caps
  29687. var createCylinderCap = function (isTop) {
  29688. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  29689. if (radius === 0) {
  29690. return;
  29691. }
  29692. // Cap positions, normals & uvs
  29693. var angle;
  29694. var circleVector;
  29695. var i;
  29696. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  29697. var c = null;
  29698. if (faceColors) {
  29699. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  29700. }
  29701. // cap center
  29702. var vbase = positions.length / 3;
  29703. var offset = isTop ? height / 2 : -height / 2;
  29704. var center = new BABYLON.Vector3(0, offset, 0);
  29705. positions.push(center.x, center.y, center.z);
  29706. normals.push(0, isTop ? 1 : -1, 0);
  29707. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  29708. if (c) {
  29709. colors.push(c.r, c.g, c.b, c.a);
  29710. }
  29711. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  29712. for (i = 0; i <= tessellation; i++) {
  29713. angle = Math.PI * 2 * i * arc / tessellation;
  29714. var cos = Math.cos(-angle);
  29715. var sin = Math.sin(-angle);
  29716. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  29717. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  29718. positions.push(circleVector.x, circleVector.y, circleVector.z);
  29719. normals.push(0, isTop ? 1 : -1, 0);
  29720. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  29721. if (c) {
  29722. colors.push(c.r, c.g, c.b, c.a);
  29723. }
  29724. }
  29725. // Cap indices
  29726. for (i = 0; i < tessellation; i++) {
  29727. if (!isTop) {
  29728. indices.push(vbase);
  29729. indices.push(vbase + (i + 1));
  29730. indices.push(vbase + (i + 2));
  29731. }
  29732. else {
  29733. indices.push(vbase);
  29734. indices.push(vbase + (i + 2));
  29735. indices.push(vbase + (i + 1));
  29736. }
  29737. }
  29738. };
  29739. // add caps to geometry
  29740. createCylinderCap(false);
  29741. createCylinderCap(true);
  29742. // Sides
  29743. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29744. var vertexData = new VertexData();
  29745. vertexData.indices = indices;
  29746. vertexData.positions = positions;
  29747. vertexData.normals = normals;
  29748. vertexData.uvs = uvs;
  29749. if (faceColors) {
  29750. vertexData.colors = colors;
  29751. }
  29752. return vertexData;
  29753. };
  29754. /**
  29755. * Creates the VertexData of the Torus.
  29756. */
  29757. VertexData.CreateTorus = function (options) {
  29758. var indices = [];
  29759. var positions = [];
  29760. var normals = [];
  29761. var uvs = [];
  29762. var diameter = options.diameter || 1;
  29763. var thickness = options.thickness || 0.5;
  29764. var tessellation = options.tessellation || 16;
  29765. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29766. var stride = tessellation + 1;
  29767. for (var i = 0; i <= tessellation; i++) {
  29768. var u = i / tessellation;
  29769. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  29770. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  29771. for (var j = 0; j <= tessellation; j++) {
  29772. var v = 1 - j / tessellation;
  29773. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  29774. var dx = Math.cos(innerAngle);
  29775. var dy = Math.sin(innerAngle);
  29776. // Create a vertex.
  29777. var normal = new BABYLON.Vector3(dx, dy, 0);
  29778. var position = normal.scale(thickness / 2);
  29779. var textureCoordinate = new BABYLON.Vector2(u, v);
  29780. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  29781. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  29782. positions.push(position.x, position.y, position.z);
  29783. normals.push(normal.x, normal.y, normal.z);
  29784. uvs.push(textureCoordinate.x, textureCoordinate.y);
  29785. // And create indices for two triangles.
  29786. var nextI = (i + 1) % stride;
  29787. var nextJ = (j + 1) % stride;
  29788. indices.push(i * stride + j);
  29789. indices.push(i * stride + nextJ);
  29790. indices.push(nextI * stride + j);
  29791. indices.push(i * stride + nextJ);
  29792. indices.push(nextI * stride + nextJ);
  29793. indices.push(nextI * stride + j);
  29794. }
  29795. }
  29796. // Sides
  29797. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29798. // Result
  29799. var vertexData = new VertexData();
  29800. vertexData.indices = indices;
  29801. vertexData.positions = positions;
  29802. vertexData.normals = normals;
  29803. vertexData.uvs = uvs;
  29804. return vertexData;
  29805. };
  29806. /**
  29807. * Creates the VertexData of the LineSystem.
  29808. */
  29809. VertexData.CreateLineSystem = function (options) {
  29810. var indices = [];
  29811. var positions = [];
  29812. var lines = options.lines;
  29813. var colors = options.colors;
  29814. var vertexColors = [];
  29815. var idx = 0;
  29816. for (var l = 0; l < lines.length; l++) {
  29817. var points = lines[l];
  29818. for (var index = 0; index < points.length; index++) {
  29819. positions.push(points[index].x, points[index].y, points[index].z);
  29820. if (colors) {
  29821. var color = colors[l];
  29822. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  29823. }
  29824. if (index > 0) {
  29825. indices.push(idx - 1);
  29826. indices.push(idx);
  29827. }
  29828. idx++;
  29829. }
  29830. }
  29831. var vertexData = new VertexData();
  29832. vertexData.indices = indices;
  29833. vertexData.positions = positions;
  29834. if (colors) {
  29835. vertexData.colors = vertexColors;
  29836. }
  29837. return vertexData;
  29838. };
  29839. /**
  29840. * Create the VertexData of the DashedLines.
  29841. */
  29842. VertexData.CreateDashedLines = function (options) {
  29843. var dashSize = options.dashSize || 3;
  29844. var gapSize = options.gapSize || 1;
  29845. var dashNb = options.dashNb || 200;
  29846. var points = options.points;
  29847. var positions = new Array();
  29848. var indices = new Array();
  29849. var curvect = BABYLON.Vector3.Zero();
  29850. var lg = 0;
  29851. var nb = 0;
  29852. var shft = 0;
  29853. var dashshft = 0;
  29854. var curshft = 0;
  29855. var idx = 0;
  29856. var i = 0;
  29857. for (i = 0; i < points.length - 1; i++) {
  29858. points[i + 1].subtractToRef(points[i], curvect);
  29859. lg += curvect.length();
  29860. }
  29861. shft = lg / dashNb;
  29862. dashshft = dashSize * shft / (dashSize + gapSize);
  29863. for (i = 0; i < points.length - 1; i++) {
  29864. points[i + 1].subtractToRef(points[i], curvect);
  29865. nb = Math.floor(curvect.length() / shft);
  29866. curvect.normalize();
  29867. for (var j = 0; j < nb; j++) {
  29868. curshft = shft * j;
  29869. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  29870. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  29871. indices.push(idx, idx + 1);
  29872. idx += 2;
  29873. }
  29874. }
  29875. // Result
  29876. var vertexData = new VertexData();
  29877. vertexData.positions = positions;
  29878. vertexData.indices = indices;
  29879. return vertexData;
  29880. };
  29881. /**
  29882. * Creates the VertexData of the Ground.
  29883. */
  29884. VertexData.CreateGround = function (options) {
  29885. var indices = [];
  29886. var positions = [];
  29887. var normals = [];
  29888. var uvs = [];
  29889. var row, col;
  29890. var width = options.width || 1;
  29891. var height = options.height || 1;
  29892. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  29893. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  29894. for (row = 0; row <= subdivisionsY; row++) {
  29895. for (col = 0; col <= subdivisionsX; col++) {
  29896. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  29897. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29898. positions.push(position.x, position.y, position.z);
  29899. normals.push(normal.x, normal.y, normal.z);
  29900. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  29901. }
  29902. }
  29903. for (row = 0; row < subdivisionsY; row++) {
  29904. for (col = 0; col < subdivisionsX; col++) {
  29905. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  29906. indices.push(col + 1 + row * (subdivisionsX + 1));
  29907. indices.push(col + row * (subdivisionsX + 1));
  29908. indices.push(col + (row + 1) * (subdivisionsX + 1));
  29909. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  29910. indices.push(col + row * (subdivisionsX + 1));
  29911. }
  29912. }
  29913. // Result
  29914. var vertexData = new VertexData();
  29915. vertexData.indices = indices;
  29916. vertexData.positions = positions;
  29917. vertexData.normals = normals;
  29918. vertexData.uvs = uvs;
  29919. return vertexData;
  29920. };
  29921. /**
  29922. * Creates the VertexData of the TiledGround.
  29923. */
  29924. VertexData.CreateTiledGround = function (options) {
  29925. var xmin = options.xmin || -1.0;
  29926. var zmin = options.zmin || -1.0;
  29927. var xmax = options.xmax || 1.0;
  29928. var zmax = options.zmax || 1.0;
  29929. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  29930. var precision = options.precision || { w: 1, h: 1 };
  29931. var indices = new Array();
  29932. var positions = new Array();
  29933. var normals = new Array();
  29934. var uvs = new Array();
  29935. var row, col, tileRow, tileCol;
  29936. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  29937. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  29938. precision.w = (precision.w < 1) ? 1 : precision.w;
  29939. precision.h = (precision.h < 1) ? 1 : precision.h;
  29940. var tileSize = {
  29941. 'w': (xmax - xmin) / subdivisions.w,
  29942. 'h': (zmax - zmin) / subdivisions.h
  29943. };
  29944. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  29945. // Indices
  29946. var base = positions.length / 3;
  29947. var rowLength = precision.w + 1;
  29948. for (row = 0; row < precision.h; row++) {
  29949. for (col = 0; col < precision.w; col++) {
  29950. var square = [
  29951. base + col + row * rowLength,
  29952. base + (col + 1) + row * rowLength,
  29953. base + (col + 1) + (row + 1) * rowLength,
  29954. base + col + (row + 1) * rowLength
  29955. ];
  29956. indices.push(square[1]);
  29957. indices.push(square[2]);
  29958. indices.push(square[3]);
  29959. indices.push(square[0]);
  29960. indices.push(square[1]);
  29961. indices.push(square[3]);
  29962. }
  29963. }
  29964. // Position, normals and uvs
  29965. var position = BABYLON.Vector3.Zero();
  29966. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29967. for (row = 0; row <= precision.h; row++) {
  29968. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  29969. for (col = 0; col <= precision.w; col++) {
  29970. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  29971. position.y = 0;
  29972. positions.push(position.x, position.y, position.z);
  29973. normals.push(normal.x, normal.y, normal.z);
  29974. uvs.push(col / precision.w, row / precision.h);
  29975. }
  29976. }
  29977. }
  29978. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  29979. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  29980. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  29981. }
  29982. }
  29983. // Result
  29984. var vertexData = new VertexData();
  29985. vertexData.indices = indices;
  29986. vertexData.positions = positions;
  29987. vertexData.normals = normals;
  29988. vertexData.uvs = uvs;
  29989. return vertexData;
  29990. };
  29991. /**
  29992. * Creates the VertexData of the Ground designed from a heightmap.
  29993. */
  29994. VertexData.CreateGroundFromHeightMap = function (options) {
  29995. var indices = [];
  29996. var positions = [];
  29997. var normals = [];
  29998. var uvs = [];
  29999. var row, col;
  30000. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  30001. // Vertices
  30002. for (row = 0; row <= options.subdivisions; row++) {
  30003. for (col = 0; col <= options.subdivisions; col++) {
  30004. 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));
  30005. // Compute height
  30006. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  30007. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  30008. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  30009. var r = options.buffer[pos] / 255.0;
  30010. var g = options.buffer[pos + 1] / 255.0;
  30011. var b = options.buffer[pos + 2] / 255.0;
  30012. var gradient = r * filter.r + g * filter.g + b * filter.b;
  30013. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  30014. // Add vertex
  30015. positions.push(position.x, position.y, position.z);
  30016. normals.push(0, 0, 0);
  30017. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  30018. }
  30019. }
  30020. // Indices
  30021. for (row = 0; row < options.subdivisions; row++) {
  30022. for (col = 0; col < options.subdivisions; col++) {
  30023. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30024. indices.push(col + 1 + row * (options.subdivisions + 1));
  30025. indices.push(col + row * (options.subdivisions + 1));
  30026. indices.push(col + (row + 1) * (options.subdivisions + 1));
  30027. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30028. indices.push(col + row * (options.subdivisions + 1));
  30029. }
  30030. }
  30031. // Normals
  30032. VertexData.ComputeNormals(positions, indices, normals);
  30033. // Result
  30034. var vertexData = new VertexData();
  30035. vertexData.indices = indices;
  30036. vertexData.positions = positions;
  30037. vertexData.normals = normals;
  30038. vertexData.uvs = uvs;
  30039. return vertexData;
  30040. };
  30041. /**
  30042. * Creates the VertexData of the Plane.
  30043. */
  30044. VertexData.CreatePlane = function (options) {
  30045. var indices = [];
  30046. var positions = [];
  30047. var normals = [];
  30048. var uvs = [];
  30049. var width = options.width || options.size || 1;
  30050. var height = options.height || options.size || 1;
  30051. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30052. // Vertices
  30053. var halfWidth = width / 2.0;
  30054. var halfHeight = height / 2.0;
  30055. positions.push(-halfWidth, -halfHeight, 0);
  30056. normals.push(0, 0, -1.0);
  30057. uvs.push(0.0, 0.0);
  30058. positions.push(halfWidth, -halfHeight, 0);
  30059. normals.push(0, 0, -1.0);
  30060. uvs.push(1.0, 0.0);
  30061. positions.push(halfWidth, halfHeight, 0);
  30062. normals.push(0, 0, -1.0);
  30063. uvs.push(1.0, 1.0);
  30064. positions.push(-halfWidth, halfHeight, 0);
  30065. normals.push(0, 0, -1.0);
  30066. uvs.push(0.0, 1.0);
  30067. // Indices
  30068. indices.push(0);
  30069. indices.push(1);
  30070. indices.push(2);
  30071. indices.push(0);
  30072. indices.push(2);
  30073. indices.push(3);
  30074. // Sides
  30075. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30076. // Result
  30077. var vertexData = new VertexData();
  30078. vertexData.indices = indices;
  30079. vertexData.positions = positions;
  30080. vertexData.normals = normals;
  30081. vertexData.uvs = uvs;
  30082. return vertexData;
  30083. };
  30084. /**
  30085. * Creates the VertexData of the Disc or regular Polygon.
  30086. */
  30087. VertexData.CreateDisc = function (options) {
  30088. var positions = new Array();
  30089. var indices = new Array();
  30090. var normals = new Array();
  30091. var uvs = new Array();
  30092. var radius = options.radius || 0.5;
  30093. var tessellation = options.tessellation || 64;
  30094. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30095. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30096. // positions and uvs
  30097. positions.push(0, 0, 0); // disc center first
  30098. uvs.push(0.5, 0.5);
  30099. var theta = Math.PI * 2 * arc;
  30100. var step = theta / tessellation;
  30101. for (var a = 0; a < theta; a += step) {
  30102. var x = Math.cos(a);
  30103. var y = Math.sin(a);
  30104. var u = (x + 1) / 2;
  30105. var v = (1 - y) / 2;
  30106. positions.push(radius * x, radius * y, 0);
  30107. uvs.push(u, v);
  30108. }
  30109. if (arc === 1) {
  30110. positions.push(positions[3], positions[4], positions[5]); // close the circle
  30111. uvs.push(uvs[2], uvs[3]);
  30112. }
  30113. //indices
  30114. var vertexNb = positions.length / 3;
  30115. for (var i = 1; i < vertexNb - 1; i++) {
  30116. indices.push(i + 1, 0, i);
  30117. }
  30118. // result
  30119. VertexData.ComputeNormals(positions, indices, normals);
  30120. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30121. var vertexData = new VertexData();
  30122. vertexData.indices = indices;
  30123. vertexData.positions = positions;
  30124. vertexData.normals = normals;
  30125. vertexData.uvs = uvs;
  30126. return vertexData;
  30127. };
  30128. /**
  30129. * Re-creates the VertexData of the Polygon for sideOrientation.
  30130. */
  30131. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  30132. var faceUV = fUV || new Array(3);
  30133. var faceColors = fColors;
  30134. var colors = [];
  30135. // default face colors and UV if undefined
  30136. for (var f = 0; f < 3; f++) {
  30137. if (faceUV[f] === undefined) {
  30138. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30139. }
  30140. if (faceColors && faceColors[f] === undefined) {
  30141. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30142. }
  30143. }
  30144. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30145. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30146. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30147. var indices = polygon.getIndices();
  30148. // set face colours and textures
  30149. var idx = 0;
  30150. var face = 0;
  30151. for (var index = 0; index < normals.length; index += 3) {
  30152. //Edge Face no. 1
  30153. if (Math.abs(normals[index + 1]) < 0.001) {
  30154. face = 1;
  30155. }
  30156. //Top Face no. 0
  30157. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  30158. face = 0;
  30159. }
  30160. //Bottom Face no. 2
  30161. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  30162. face = 2;
  30163. }
  30164. idx = index / 3;
  30165. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  30166. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  30167. if (faceColors) {
  30168. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  30169. }
  30170. }
  30171. // sides
  30172. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  30173. // Result
  30174. var vertexData = new VertexData();
  30175. vertexData.indices = indices;
  30176. vertexData.positions = positions;
  30177. vertexData.normals = normals;
  30178. vertexData.uvs = uvs;
  30179. if (faceColors) {
  30180. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30181. vertexData.colors = totalColors;
  30182. }
  30183. return vertexData;
  30184. };
  30185. /**
  30186. * Creates the VertexData of the IcoSphere.
  30187. */
  30188. VertexData.CreateIcoSphere = function (options) {
  30189. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30190. var radius = options.radius || 1;
  30191. var flat = (options.flat === undefined) ? true : options.flat;
  30192. var subdivisions = options.subdivisions || 4;
  30193. var radiusX = options.radiusX || radius;
  30194. var radiusY = options.radiusY || radius;
  30195. var radiusZ = options.radiusZ || radius;
  30196. var t = (1 + Math.sqrt(5)) / 2;
  30197. // 12 vertex x,y,z
  30198. var ico_vertices = [
  30199. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  30200. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  30201. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  30202. ];
  30203. // index of 3 vertex makes a face of icopshere
  30204. var ico_indices = [
  30205. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  30206. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  30207. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  30208. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  30209. ];
  30210. // vertex for uv have aliased position, not for UV
  30211. var vertices_unalias_id = [
  30212. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  30213. // vertex alias
  30214. 0,
  30215. 2,
  30216. 3,
  30217. 3,
  30218. 3,
  30219. 4,
  30220. 7,
  30221. 8,
  30222. 9,
  30223. 9,
  30224. 10,
  30225. 11 // 23: B + 12
  30226. ];
  30227. // uv as integer step (not pixels !)
  30228. var ico_vertexuv = [
  30229. 5, 1, 3, 1, 6, 4, 0, 0,
  30230. 5, 3, 4, 2, 2, 2, 4, 0,
  30231. 2, 0, 1, 1, 6, 0, 6, 2,
  30232. // vertex alias (for same vertex on different faces)
  30233. 0, 4,
  30234. 3, 3,
  30235. 4, 4,
  30236. 3, 1,
  30237. 4, 2,
  30238. 4, 4,
  30239. 0, 2,
  30240. 1, 1,
  30241. 2, 2,
  30242. 3, 3,
  30243. 1, 3,
  30244. 2, 4 // 23: B + 12
  30245. ];
  30246. // Vertices[0, 1, ...9, A, B] : position on UV plane
  30247. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  30248. // First island of uv mapping
  30249. // v = 4h 3+ 2
  30250. // v = 3h 9+ 4
  30251. // v = 2h 9+ 5 B
  30252. // v = 1h 9 1 0
  30253. // v = 0h 3 8 7 A
  30254. // u = 0 1 2 3 4 5 6 *a
  30255. // Second island of uv mapping
  30256. // v = 4h 0+ B+ 4+
  30257. // v = 3h A+ 2+
  30258. // v = 2h 7+ 6 3+
  30259. // v = 1h 8+ 3+
  30260. // v = 0h
  30261. // u = 0 1 2 3 4 5 6 *a
  30262. // Face layout on texture UV mapping
  30263. // ============
  30264. // \ 4 /\ 16 / ======
  30265. // \ / \ / /\ 11 /
  30266. // \/ 7 \/ / \ /
  30267. // ======= / 10 \/
  30268. // /\ 17 /\ =======
  30269. // / \ / \ \ 15 /\
  30270. // / 8 \/ 12 \ \ / \
  30271. // ============ \/ 6 \
  30272. // \ 18 /\ ============
  30273. // \ / \ \ 5 /\ 0 /
  30274. // \/ 13 \ \ / \ /
  30275. // ======= \/ 1 \/
  30276. // =============
  30277. // /\ 19 /\ 2 /\
  30278. // / \ / \ / \
  30279. // / 14 \/ 9 \/ 3 \
  30280. // ===================
  30281. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  30282. var ustep = 138 / 1024;
  30283. var vstep = 239 / 1024;
  30284. var uoffset = 60 / 1024;
  30285. var voffset = 26 / 1024;
  30286. // Second island should have margin, not to touch the first island
  30287. // avoid any borderline artefact in pixel rounding
  30288. var island_u_offset = -40 / 1024;
  30289. var island_v_offset = +20 / 1024;
  30290. // face is either island 0 or 1 :
  30291. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  30292. var island = [
  30293. 0, 0, 0, 0, 1,
  30294. 0, 0, 1, 1, 0,
  30295. 0, 0, 1, 1, 0,
  30296. 0, 1, 1, 1, 0 // 15 - 19
  30297. ];
  30298. var indices = new Array();
  30299. var positions = new Array();
  30300. var normals = new Array();
  30301. var uvs = new Array();
  30302. var current_indice = 0;
  30303. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  30304. var face_vertex_pos = new Array(3);
  30305. var face_vertex_uv = new Array(3);
  30306. var v012;
  30307. for (v012 = 0; v012 < 3; v012++) {
  30308. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  30309. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  30310. }
  30311. // create all with normals
  30312. for (var face = 0; face < 20; face++) {
  30313. // 3 vertex per face
  30314. for (v012 = 0; v012 < 3; v012++) {
  30315. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  30316. var v_id = ico_indices[3 * face + v012];
  30317. // vertex have 3D position (x,y,z)
  30318. 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]);
  30319. // Normalize to get normal, then scale to radius
  30320. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  30321. // uv Coordinates from vertex ID
  30322. 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);
  30323. }
  30324. // Subdivide the face (interpolate pos, norm, uv)
  30325. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  30326. // - norm is linear interpolation of vertex corner normal
  30327. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  30328. // - uv is linear interpolation
  30329. //
  30330. // Topology is as below for sub-divide by 2
  30331. // vertex shown as v0,v1,v2
  30332. // interp index is i1 to progress in range [v0,v1[
  30333. // interp index is i2 to progress in range [v0,v2[
  30334. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  30335. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30336. //
  30337. //
  30338. // i2 v2
  30339. // ^ ^
  30340. // / / \
  30341. // / / \
  30342. // / / \
  30343. // / / (0,1) \
  30344. // / #---------\
  30345. // / / \ (0,0)'/ \
  30346. // / / \ / \
  30347. // / / \ / \
  30348. // / / (0,0) \ / (1,0) \
  30349. // / #---------#---------\
  30350. // v0 v1
  30351. //
  30352. // --------------------> i1
  30353. //
  30354. // interp of (i1,i2):
  30355. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  30356. // along i1 : lerp(x0,x1, i1/(S-i2))
  30357. //
  30358. // centroid of triangle is needed to get help normal computation
  30359. // (c1,c2) are used for centroid location
  30360. var interp_vertex = function (i1, i2, c1, c2) {
  30361. // vertex is interpolated from
  30362. // - face_vertex_pos[0..2]
  30363. // - face_vertex_uv[0..2]
  30364. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  30365. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  30366. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  30367. pos_interp.normalize();
  30368. var vertex_normal;
  30369. if (flat) {
  30370. // in flat mode, recalculate normal as face centroid normal
  30371. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  30372. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  30373. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  30374. }
  30375. else {
  30376. // in smooth mode, recalculate normal from each single vertex position
  30377. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  30378. }
  30379. // Vertex normal need correction due to X,Y,Z radius scaling
  30380. vertex_normal.x /= radiusX;
  30381. vertex_normal.y /= radiusY;
  30382. vertex_normal.z /= radiusZ;
  30383. vertex_normal.normalize();
  30384. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  30385. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  30386. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  30387. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  30388. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  30389. uvs.push(uv_interp.x, uv_interp.y);
  30390. // push each vertex has member of a face
  30391. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  30392. indices.push(current_indice);
  30393. current_indice++;
  30394. };
  30395. for (var i2 = 0; i2 < subdivisions; i2++) {
  30396. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  30397. // face : (i1,i2) for /\ :
  30398. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  30399. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30400. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30401. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30402. if (i1 + i2 + 1 < subdivisions) {
  30403. // face : (i1,i2)' for \/ :
  30404. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30405. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30406. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30407. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30408. }
  30409. }
  30410. }
  30411. }
  30412. // Sides
  30413. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30414. // Result
  30415. var vertexData = new VertexData();
  30416. vertexData.indices = indices;
  30417. vertexData.positions = positions;
  30418. vertexData.normals = normals;
  30419. vertexData.uvs = uvs;
  30420. return vertexData;
  30421. };
  30422. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  30423. /**
  30424. * Creates the VertexData of the Polyhedron.
  30425. */
  30426. VertexData.CreatePolyhedron = function (options) {
  30427. // provided polyhedron types :
  30428. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  30429. // 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)
  30430. var polyhedra = [];
  30431. 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]] };
  30432. 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]] };
  30433. polyhedra[2] = {
  30434. 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]],
  30435. 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]]
  30436. };
  30437. polyhedra[3] = {
  30438. 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]],
  30439. 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]]
  30440. };
  30441. polyhedra[4] = {
  30442. 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]],
  30443. 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]]
  30444. };
  30445. 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]] };
  30446. 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]] };
  30447. 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]] };
  30448. 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]] };
  30449. 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]] };
  30450. 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]] };
  30451. 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]] };
  30452. 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]] };
  30453. 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]] };
  30454. polyhedra[14] = {
  30455. 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]],
  30456. 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]]
  30457. };
  30458. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  30459. var size = options.size;
  30460. var sizeX = options.sizeX || size || 1;
  30461. var sizeY = options.sizeY || size || 1;
  30462. var sizeZ = options.sizeZ || size || 1;
  30463. var data = options.custom || polyhedra[type];
  30464. var nbfaces = data.face.length;
  30465. var faceUV = options.faceUV || new Array(nbfaces);
  30466. var faceColors = options.faceColors;
  30467. var flat = (options.flat === undefined) ? true : options.flat;
  30468. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30469. var positions = new Array();
  30470. var indices = new Array();
  30471. var normals = new Array();
  30472. var uvs = new Array();
  30473. var colors = new Array();
  30474. var index = 0;
  30475. var faceIdx = 0; // face cursor in the array "indexes"
  30476. var indexes = new Array();
  30477. var i = 0;
  30478. var f = 0;
  30479. var u, v, ang, x, y, tmp;
  30480. // default face colors and UV if undefined
  30481. if (flat) {
  30482. for (f = 0; f < nbfaces; f++) {
  30483. if (faceColors && faceColors[f] === undefined) {
  30484. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30485. }
  30486. if (faceUV && faceUV[f] === undefined) {
  30487. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30488. }
  30489. }
  30490. }
  30491. if (!flat) {
  30492. for (i = 0; i < data.vertex.length; i++) {
  30493. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  30494. uvs.push(0, 0);
  30495. }
  30496. for (f = 0; f < nbfaces; f++) {
  30497. for (i = 0; i < data.face[f].length - 2; i++) {
  30498. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  30499. }
  30500. }
  30501. }
  30502. else {
  30503. for (f = 0; f < nbfaces; f++) {
  30504. var fl = data.face[f].length; // number of vertices of the current face
  30505. ang = 2 * Math.PI / fl;
  30506. x = 0.5 * Math.tan(ang / 2);
  30507. y = 0.5;
  30508. // positions, uvs, colors
  30509. for (i = 0; i < fl; i++) {
  30510. // positions
  30511. 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);
  30512. indexes.push(index);
  30513. index++;
  30514. // uvs
  30515. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  30516. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  30517. uvs.push(u, v);
  30518. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  30519. y = x * Math.sin(ang) + y * Math.cos(ang);
  30520. x = tmp;
  30521. // colors
  30522. if (faceColors) {
  30523. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  30524. }
  30525. }
  30526. // indices from indexes
  30527. for (i = 0; i < fl - 2; i++) {
  30528. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  30529. }
  30530. faceIdx += fl;
  30531. }
  30532. }
  30533. VertexData.ComputeNormals(positions, indices, normals);
  30534. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30535. var vertexData = new VertexData();
  30536. vertexData.positions = positions;
  30537. vertexData.indices = indices;
  30538. vertexData.normals = normals;
  30539. vertexData.uvs = uvs;
  30540. if (faceColors && flat) {
  30541. vertexData.colors = colors;
  30542. }
  30543. return vertexData;
  30544. };
  30545. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  30546. /**
  30547. * Creates the VertexData of the Torus Knot.
  30548. */
  30549. VertexData.CreateTorusKnot = function (options) {
  30550. var indices = new Array();
  30551. var positions = new Array();
  30552. var normals = new Array();
  30553. var uvs = new Array();
  30554. var radius = options.radius || 2;
  30555. var tube = options.tube || 0.5;
  30556. var radialSegments = options.radialSegments || 32;
  30557. var tubularSegments = options.tubularSegments || 32;
  30558. var p = options.p || 2;
  30559. var q = options.q || 3;
  30560. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30561. // Helper
  30562. var getPos = function (angle) {
  30563. var cu = Math.cos(angle);
  30564. var su = Math.sin(angle);
  30565. var quOverP = q / p * angle;
  30566. var cs = Math.cos(quOverP);
  30567. var tx = radius * (2 + cs) * 0.5 * cu;
  30568. var ty = radius * (2 + cs) * su * 0.5;
  30569. var tz = radius * Math.sin(quOverP) * 0.5;
  30570. return new BABYLON.Vector3(tx, ty, tz);
  30571. };
  30572. // Vertices
  30573. var i;
  30574. var j;
  30575. for (i = 0; i <= radialSegments; i++) {
  30576. var modI = i % radialSegments;
  30577. var u = modI / radialSegments * 2 * p * Math.PI;
  30578. var p1 = getPos(u);
  30579. var p2 = getPos(u + 0.01);
  30580. var tang = p2.subtract(p1);
  30581. var n = p2.add(p1);
  30582. var bitan = BABYLON.Vector3.Cross(tang, n);
  30583. n = BABYLON.Vector3.Cross(bitan, tang);
  30584. bitan.normalize();
  30585. n.normalize();
  30586. for (j = 0; j < tubularSegments; j++) {
  30587. var modJ = j % tubularSegments;
  30588. var v = modJ / tubularSegments * 2 * Math.PI;
  30589. var cx = -tube * Math.cos(v);
  30590. var cy = tube * Math.sin(v);
  30591. positions.push(p1.x + cx * n.x + cy * bitan.x);
  30592. positions.push(p1.y + cx * n.y + cy * bitan.y);
  30593. positions.push(p1.z + cx * n.z + cy * bitan.z);
  30594. uvs.push(i / radialSegments);
  30595. uvs.push(j / tubularSegments);
  30596. }
  30597. }
  30598. for (i = 0; i < radialSegments; i++) {
  30599. for (j = 0; j < tubularSegments; j++) {
  30600. var jNext = (j + 1) % tubularSegments;
  30601. var a = i * tubularSegments + j;
  30602. var b = (i + 1) * tubularSegments + j;
  30603. var c = (i + 1) * tubularSegments + jNext;
  30604. var d = i * tubularSegments + jNext;
  30605. indices.push(d);
  30606. indices.push(b);
  30607. indices.push(a);
  30608. indices.push(d);
  30609. indices.push(c);
  30610. indices.push(b);
  30611. }
  30612. }
  30613. // Normals
  30614. VertexData.ComputeNormals(positions, indices, normals);
  30615. // Sides
  30616. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30617. // Result
  30618. var vertexData = new VertexData();
  30619. vertexData.indices = indices;
  30620. vertexData.positions = positions;
  30621. vertexData.normals = normals;
  30622. vertexData.uvs = uvs;
  30623. return vertexData;
  30624. };
  30625. // Tools
  30626. /**
  30627. * @param {any} - positions (number[] or Float32Array)
  30628. * @param {any} - indices (number[] or Uint16Array)
  30629. * @param {any} - normals (number[] or Float32Array)
  30630. * options (optional) :
  30631. * facetPositions : optional array of facet positions (vector3)
  30632. * facetNormals : optional array of facet normals (vector3)
  30633. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  30634. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  30635. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  30636. * bbSize : optional bounding box size data, required for facetPartitioning computation
  30637. * bInfo : optional bounding info, required for facetPartitioning computation
  30638. * useRightHandedSystem: optional boolean to for right handed system computation
  30639. * depthSort : optional boolean to enable the facet depth sort computation
  30640. * distanceTo : optional Vector3 to compute the facet depth from this location
  30641. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  30642. */
  30643. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  30644. // temporary scalar variables
  30645. var index = 0; // facet index
  30646. var p1p2x = 0.0; // p1p2 vector x coordinate
  30647. var p1p2y = 0.0; // p1p2 vector y coordinate
  30648. var p1p2z = 0.0; // p1p2 vector z coordinate
  30649. var p3p2x = 0.0; // p3p2 vector x coordinate
  30650. var p3p2y = 0.0; // p3p2 vector y coordinate
  30651. var p3p2z = 0.0; // p3p2 vector z coordinate
  30652. var faceNormalx = 0.0; // facet normal x coordinate
  30653. var faceNormaly = 0.0; // facet normal y coordinate
  30654. var faceNormalz = 0.0; // facet normal z coordinate
  30655. var length = 0.0; // facet normal length before normalization
  30656. var v1x = 0; // vector1 x index in the positions array
  30657. var v1y = 0; // vector1 y index in the positions array
  30658. var v1z = 0; // vector1 z index in the positions array
  30659. var v2x = 0; // vector2 x index in the positions array
  30660. var v2y = 0; // vector2 y index in the positions array
  30661. var v2z = 0; // vector2 z index in the positions array
  30662. var v3x = 0; // vector3 x index in the positions array
  30663. var v3y = 0; // vector3 y index in the positions array
  30664. var v3z = 0; // vector3 z index in the positions array
  30665. var computeFacetNormals = false;
  30666. var computeFacetPositions = false;
  30667. var computeFacetPartitioning = false;
  30668. var computeDepthSort = false;
  30669. var faceNormalSign = 1;
  30670. var ratio = 0;
  30671. var distanceTo = null;
  30672. if (options) {
  30673. computeFacetNormals = (options.facetNormals) ? true : false;
  30674. computeFacetPositions = (options.facetPositions) ? true : false;
  30675. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  30676. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  30677. ratio = options.ratio || 0;
  30678. computeDepthSort = (options.depthSort) ? true : false;
  30679. distanceTo = (options.distanceTo);
  30680. if (computeDepthSort) {
  30681. if (distanceTo === undefined) {
  30682. distanceTo = BABYLON.Vector3.Zero();
  30683. }
  30684. var depthSortedFacets = options.depthSortedFacets;
  30685. }
  30686. }
  30687. // facetPartitioning reinit if needed
  30688. var xSubRatio = 0;
  30689. var ySubRatio = 0;
  30690. var zSubRatio = 0;
  30691. var subSq = 0;
  30692. if (computeFacetPartitioning && options && options.bbSize) {
  30693. var ox = 0; // X partitioning index for facet position
  30694. var oy = 0; // Y partinioning index for facet position
  30695. var oz = 0; // Z partinioning index for facet position
  30696. var b1x = 0; // X partitioning index for facet v1 vertex
  30697. var b1y = 0; // Y partitioning index for facet v1 vertex
  30698. var b1z = 0; // z partitioning index for facet v1 vertex
  30699. var b2x = 0; // X partitioning index for facet v2 vertex
  30700. var b2y = 0; // Y partitioning index for facet v2 vertex
  30701. var b2z = 0; // Z partitioning index for facet v2 vertex
  30702. var b3x = 0; // X partitioning index for facet v3 vertex
  30703. var b3y = 0; // Y partitioning index for facet v3 vertex
  30704. var b3z = 0; // Z partitioning index for facet v3 vertex
  30705. var block_idx_o = 0; // facet barycenter block index
  30706. var block_idx_v1 = 0; // v1 vertex block index
  30707. var block_idx_v2 = 0; // v2 vertex block index
  30708. var block_idx_v3 = 0; // v3 vertex block index
  30709. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  30710. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  30711. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  30712. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  30713. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  30714. subSq = options.subDiv.max * options.subDiv.max;
  30715. options.facetPartitioning.length = 0;
  30716. }
  30717. // reset the normals
  30718. for (index = 0; index < positions.length; index++) {
  30719. normals[index] = 0.0;
  30720. }
  30721. // Loop : 1 indice triplet = 1 facet
  30722. var nbFaces = (indices.length / 3) | 0;
  30723. for (index = 0; index < nbFaces; index++) {
  30724. // get the indexes of the coordinates of each vertex of the facet
  30725. v1x = indices[index * 3] * 3;
  30726. v1y = v1x + 1;
  30727. v1z = v1x + 2;
  30728. v2x = indices[index * 3 + 1] * 3;
  30729. v2y = v2x + 1;
  30730. v2z = v2x + 2;
  30731. v3x = indices[index * 3 + 2] * 3;
  30732. v3y = v3x + 1;
  30733. v3z = v3x + 2;
  30734. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  30735. p1p2y = positions[v1y] - positions[v2y];
  30736. p1p2z = positions[v1z] - positions[v2z];
  30737. p3p2x = positions[v3x] - positions[v2x];
  30738. p3p2y = positions[v3y] - positions[v2y];
  30739. p3p2z = positions[v3z] - positions[v2z];
  30740. // compute the face normal with the cross product
  30741. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  30742. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  30743. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  30744. // normalize this normal and store it in the array facetData
  30745. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30746. length = (length === 0) ? 1.0 : length;
  30747. faceNormalx /= length;
  30748. faceNormaly /= length;
  30749. faceNormalz /= length;
  30750. if (computeFacetNormals && options) {
  30751. options.facetNormals[index].x = faceNormalx;
  30752. options.facetNormals[index].y = faceNormaly;
  30753. options.facetNormals[index].z = faceNormalz;
  30754. }
  30755. if (computeFacetPositions && options) {
  30756. // compute and the facet barycenter coordinates in the array facetPositions
  30757. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  30758. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  30759. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  30760. }
  30761. if (computeFacetPartitioning && options) {
  30762. // store the facet indexes in arrays in the main facetPartitioning array :
  30763. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  30764. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  30765. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  30766. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  30767. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30768. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30769. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30770. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30771. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30772. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30773. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30774. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30775. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30776. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  30777. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  30778. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  30779. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  30780. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  30781. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  30782. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  30783. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  30784. // push each facet index in each block containing the vertex
  30785. options.facetPartitioning[block_idx_v1].push(index);
  30786. if (block_idx_v2 != block_idx_v1) {
  30787. options.facetPartitioning[block_idx_v2].push(index);
  30788. }
  30789. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  30790. options.facetPartitioning[block_idx_v3].push(index);
  30791. }
  30792. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  30793. options.facetPartitioning[block_idx_o].push(index);
  30794. }
  30795. }
  30796. if (computeDepthSort && options && options.facetPositions) {
  30797. var dsf = depthSortedFacets[index];
  30798. dsf.ind = index * 3;
  30799. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  30800. }
  30801. // compute the normals anyway
  30802. normals[v1x] += faceNormalx; // accumulate all the normals per face
  30803. normals[v1y] += faceNormaly;
  30804. normals[v1z] += faceNormalz;
  30805. normals[v2x] += faceNormalx;
  30806. normals[v2y] += faceNormaly;
  30807. normals[v2z] += faceNormalz;
  30808. normals[v3x] += faceNormalx;
  30809. normals[v3y] += faceNormaly;
  30810. normals[v3z] += faceNormalz;
  30811. }
  30812. // last normalization of each normal
  30813. for (index = 0; index < normals.length / 3; index++) {
  30814. faceNormalx = normals[index * 3];
  30815. faceNormaly = normals[index * 3 + 1];
  30816. faceNormalz = normals[index * 3 + 2];
  30817. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30818. length = (length === 0) ? 1.0 : length;
  30819. faceNormalx /= length;
  30820. faceNormaly /= length;
  30821. faceNormalz /= length;
  30822. normals[index * 3] = faceNormalx;
  30823. normals[index * 3 + 1] = faceNormaly;
  30824. normals[index * 3 + 2] = faceNormalz;
  30825. }
  30826. };
  30827. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  30828. var li = indices.length;
  30829. var ln = normals.length;
  30830. var i;
  30831. var n;
  30832. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30833. switch (sideOrientation) {
  30834. case BABYLON.Mesh.FRONTSIDE:
  30835. // nothing changed
  30836. break;
  30837. case BABYLON.Mesh.BACKSIDE:
  30838. var tmp;
  30839. // indices
  30840. for (i = 0; i < li; i += 3) {
  30841. tmp = indices[i];
  30842. indices[i] = indices[i + 2];
  30843. indices[i + 2] = tmp;
  30844. }
  30845. // normals
  30846. for (n = 0; n < ln; n++) {
  30847. normals[n] = -normals[n];
  30848. }
  30849. break;
  30850. case BABYLON.Mesh.DOUBLESIDE:
  30851. // positions
  30852. var lp = positions.length;
  30853. var l = lp / 3;
  30854. for (var p = 0; p < lp; p++) {
  30855. positions[lp + p] = positions[p];
  30856. }
  30857. // indices
  30858. for (i = 0; i < li; i += 3) {
  30859. indices[i + li] = indices[i + 2] + l;
  30860. indices[i + 1 + li] = indices[i + 1] + l;
  30861. indices[i + 2 + li] = indices[i] + l;
  30862. }
  30863. // normals
  30864. for (n = 0; n < ln; n++) {
  30865. normals[ln + n] = -normals[n];
  30866. }
  30867. // uvs
  30868. var lu = uvs.length;
  30869. var u = 0;
  30870. for (u = 0; u < lu; u++) {
  30871. uvs[u + lu] = uvs[u];
  30872. }
  30873. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  30874. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  30875. u = 0;
  30876. for (i = 0; i < lu / 2; i++) {
  30877. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  30878. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  30879. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  30880. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  30881. u += 2;
  30882. }
  30883. break;
  30884. }
  30885. };
  30886. /**
  30887. * Creates a new VertexData from the imported parameters.
  30888. */
  30889. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  30890. var vertexData = new VertexData();
  30891. // positions
  30892. var positions = parsedVertexData.positions;
  30893. if (positions) {
  30894. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  30895. }
  30896. // normals
  30897. var normals = parsedVertexData.normals;
  30898. if (normals) {
  30899. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  30900. }
  30901. // tangents
  30902. var tangents = parsedVertexData.tangents;
  30903. if (tangents) {
  30904. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  30905. }
  30906. // uvs
  30907. var uvs = parsedVertexData.uvs;
  30908. if (uvs) {
  30909. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  30910. }
  30911. // uv2s
  30912. var uv2s = parsedVertexData.uv2s;
  30913. if (uv2s) {
  30914. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  30915. }
  30916. // uv3s
  30917. var uv3s = parsedVertexData.uv3s;
  30918. if (uv3s) {
  30919. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  30920. }
  30921. // uv4s
  30922. var uv4s = parsedVertexData.uv4s;
  30923. if (uv4s) {
  30924. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  30925. }
  30926. // uv5s
  30927. var uv5s = parsedVertexData.uv5s;
  30928. if (uv5s) {
  30929. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  30930. }
  30931. // uv6s
  30932. var uv6s = parsedVertexData.uv6s;
  30933. if (uv6s) {
  30934. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  30935. }
  30936. // colors
  30937. var colors = parsedVertexData.colors;
  30938. if (colors) {
  30939. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  30940. }
  30941. // matricesIndices
  30942. var matricesIndices = parsedVertexData.matricesIndices;
  30943. if (matricesIndices) {
  30944. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  30945. }
  30946. // matricesWeights
  30947. var matricesWeights = parsedVertexData.matricesWeights;
  30948. if (matricesWeights) {
  30949. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  30950. }
  30951. // indices
  30952. var indices = parsedVertexData.indices;
  30953. if (indices) {
  30954. vertexData.indices = indices;
  30955. }
  30956. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  30957. };
  30958. return VertexData;
  30959. }());
  30960. BABYLON.VertexData = VertexData;
  30961. })(BABYLON || (BABYLON = {}));
  30962. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  30963. var BABYLON;
  30964. (function (BABYLON) {
  30965. var Geometry = /** @class */ (function () {
  30966. function Geometry(id, scene, vertexData, updatable, mesh) {
  30967. if (updatable === void 0) { updatable = false; }
  30968. if (mesh === void 0) { mesh = null; }
  30969. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30970. this._totalVertices = 0;
  30971. this._isDisposed = false;
  30972. this._indexBufferIsUpdatable = false;
  30973. this.id = id;
  30974. this._engine = scene.getEngine();
  30975. this._meshes = [];
  30976. this._scene = scene;
  30977. //Init vertex buffer cache
  30978. this._vertexBuffers = {};
  30979. this._indices = [];
  30980. this._updatable = updatable;
  30981. // vertexData
  30982. if (vertexData) {
  30983. this.setAllVerticesData(vertexData, updatable);
  30984. }
  30985. else {
  30986. this._totalVertices = 0;
  30987. this._indices = [];
  30988. }
  30989. if (this._engine.getCaps().vertexArrayObject) {
  30990. this._vertexArrayObjects = {};
  30991. }
  30992. // applyToMesh
  30993. if (mesh) {
  30994. if (mesh.getClassName() === "LinesMesh") {
  30995. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  30996. this.updateExtend();
  30997. }
  30998. this.applyToMesh(mesh);
  30999. mesh.computeWorldMatrix(true);
  31000. }
  31001. }
  31002. Object.defineProperty(Geometry.prototype, "boundingBias", {
  31003. /**
  31004. * 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
  31005. * @returns The Bias Vector
  31006. */
  31007. get: function () {
  31008. return this._boundingBias;
  31009. },
  31010. set: function (value) {
  31011. if (this._boundingBias && this._boundingBias.equals(value)) {
  31012. return;
  31013. }
  31014. this._boundingBias = value.clone();
  31015. this.updateBoundingInfo(true, null);
  31016. },
  31017. enumerable: true,
  31018. configurable: true
  31019. });
  31020. Geometry.CreateGeometryForMesh = function (mesh) {
  31021. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  31022. geometry.applyToMesh(mesh);
  31023. return geometry;
  31024. };
  31025. Object.defineProperty(Geometry.prototype, "extend", {
  31026. get: function () {
  31027. return this._extend;
  31028. },
  31029. enumerable: true,
  31030. configurable: true
  31031. });
  31032. Geometry.prototype.getScene = function () {
  31033. return this._scene;
  31034. };
  31035. Geometry.prototype.getEngine = function () {
  31036. return this._engine;
  31037. };
  31038. Geometry.prototype.isReady = function () {
  31039. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  31040. };
  31041. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  31042. get: function () {
  31043. for (var index = 0; index < this._meshes.length; index++) {
  31044. if (!this._meshes[index].doNotSerialize) {
  31045. return false;
  31046. }
  31047. }
  31048. return true;
  31049. },
  31050. enumerable: true,
  31051. configurable: true
  31052. });
  31053. Geometry.prototype._rebuild = function () {
  31054. if (this._vertexArrayObjects) {
  31055. this._vertexArrayObjects = {};
  31056. }
  31057. // Index buffer
  31058. if (this._meshes.length !== 0 && this._indices) {
  31059. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31060. }
  31061. // Vertex buffers
  31062. for (var key in this._vertexBuffers) {
  31063. var vertexBuffer = this._vertexBuffers[key];
  31064. vertexBuffer._rebuild();
  31065. }
  31066. };
  31067. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  31068. vertexData.applyToGeometry(this, updatable);
  31069. this.notifyUpdate();
  31070. };
  31071. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31072. if (updatable === void 0) { updatable = false; }
  31073. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  31074. this.setVerticesBuffer(buffer);
  31075. };
  31076. Geometry.prototype.removeVerticesData = function (kind) {
  31077. if (this._vertexBuffers[kind]) {
  31078. this._vertexBuffers[kind].dispose();
  31079. delete this._vertexBuffers[kind];
  31080. }
  31081. };
  31082. Geometry.prototype.setVerticesBuffer = function (buffer) {
  31083. var kind = buffer.getKind();
  31084. if (this._vertexBuffers[kind]) {
  31085. this._vertexBuffers[kind].dispose();
  31086. }
  31087. this._vertexBuffers[kind] = buffer;
  31088. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31089. var data = buffer.getData();
  31090. var stride = buffer.getStrideSize();
  31091. this._totalVertices = data.length / stride;
  31092. this.updateExtend(data, stride);
  31093. this._resetPointsArrayCache();
  31094. var meshes = this._meshes;
  31095. var numOfMeshes = meshes.length;
  31096. for (var index = 0; index < numOfMeshes; index++) {
  31097. var mesh = meshes[index];
  31098. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31099. mesh._createGlobalSubMesh(false);
  31100. mesh.computeWorldMatrix(true);
  31101. }
  31102. }
  31103. this.notifyUpdate(kind);
  31104. if (this._vertexArrayObjects) {
  31105. this._disposeVertexArrayObjects();
  31106. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  31107. }
  31108. };
  31109. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  31110. var vertexBuffer = this.getVertexBuffer(kind);
  31111. if (!vertexBuffer) {
  31112. return;
  31113. }
  31114. vertexBuffer.updateDirectly(data, offset);
  31115. this.notifyUpdate(kind);
  31116. };
  31117. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  31118. if (updateExtends === void 0) { updateExtends = false; }
  31119. var vertexBuffer = this.getVertexBuffer(kind);
  31120. if (!vertexBuffer) {
  31121. return;
  31122. }
  31123. vertexBuffer.update(data);
  31124. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31125. var stride = vertexBuffer.getStrideSize();
  31126. this._totalVertices = data.length / stride;
  31127. this.updateBoundingInfo(updateExtends, data);
  31128. }
  31129. this.notifyUpdate(kind);
  31130. };
  31131. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  31132. if (updateExtends) {
  31133. this.updateExtend(data);
  31134. }
  31135. var meshes = this._meshes;
  31136. var numOfMeshes = meshes.length;
  31137. this._resetPointsArrayCache();
  31138. for (var index = 0; index < numOfMeshes; index++) {
  31139. var mesh = meshes[index];
  31140. if (updateExtends) {
  31141. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31142. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  31143. var subMesh = mesh.subMeshes[subIndex];
  31144. subMesh.refreshBoundingInfo();
  31145. }
  31146. }
  31147. }
  31148. };
  31149. Geometry.prototype._bind = function (effect, indexToBind) {
  31150. if (!effect) {
  31151. return;
  31152. }
  31153. if (indexToBind === undefined) {
  31154. indexToBind = this._indexBuffer;
  31155. }
  31156. var vbs = this.getVertexBuffers();
  31157. if (!vbs) {
  31158. return;
  31159. }
  31160. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  31161. this._engine.bindBuffers(vbs, indexToBind, effect);
  31162. return;
  31163. }
  31164. // Using VAO
  31165. if (!this._vertexArrayObjects[effect.key]) {
  31166. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  31167. }
  31168. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  31169. };
  31170. Geometry.prototype.getTotalVertices = function () {
  31171. if (!this.isReady()) {
  31172. return 0;
  31173. }
  31174. return this._totalVertices;
  31175. };
  31176. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31177. var vertexBuffer = this.getVertexBuffer(kind);
  31178. if (!vertexBuffer) {
  31179. return null;
  31180. }
  31181. var orig = vertexBuffer.getData();
  31182. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  31183. return orig;
  31184. }
  31185. else {
  31186. var len = orig.length;
  31187. var copy = [];
  31188. for (var i = 0; i < len; i++) {
  31189. copy.push(orig[i]);
  31190. }
  31191. return copy;
  31192. }
  31193. };
  31194. /**
  31195. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31196. * Possible `kind` values :
  31197. * - BABYLON.VertexBuffer.PositionKind
  31198. * - BABYLON.VertexBuffer.UVKind
  31199. * - BABYLON.VertexBuffer.UV2Kind
  31200. * - BABYLON.VertexBuffer.UV3Kind
  31201. * - BABYLON.VertexBuffer.UV4Kind
  31202. * - BABYLON.VertexBuffer.UV5Kind
  31203. * - BABYLON.VertexBuffer.UV6Kind
  31204. * - BABYLON.VertexBuffer.ColorKind
  31205. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31206. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31207. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31208. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31209. */
  31210. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  31211. var vb = this._vertexBuffers[kind];
  31212. if (!vb) {
  31213. return false;
  31214. }
  31215. return vb.isUpdatable();
  31216. };
  31217. Geometry.prototype.getVertexBuffer = function (kind) {
  31218. if (!this.isReady()) {
  31219. return null;
  31220. }
  31221. return this._vertexBuffers[kind];
  31222. };
  31223. Geometry.prototype.getVertexBuffers = function () {
  31224. if (!this.isReady()) {
  31225. return null;
  31226. }
  31227. return this._vertexBuffers;
  31228. };
  31229. Geometry.prototype.isVerticesDataPresent = function (kind) {
  31230. if (!this._vertexBuffers) {
  31231. if (this._delayInfo) {
  31232. return this._delayInfo.indexOf(kind) !== -1;
  31233. }
  31234. return false;
  31235. }
  31236. return this._vertexBuffers[kind] !== undefined;
  31237. };
  31238. Geometry.prototype.getVerticesDataKinds = function () {
  31239. var result = [];
  31240. var kind;
  31241. if (!this._vertexBuffers && this._delayInfo) {
  31242. for (kind in this._delayInfo) {
  31243. result.push(kind);
  31244. }
  31245. }
  31246. else {
  31247. for (kind in this._vertexBuffers) {
  31248. result.push(kind);
  31249. }
  31250. }
  31251. return result;
  31252. };
  31253. Geometry.prototype.updateIndices = function (indices, offset) {
  31254. if (!this._indexBuffer) {
  31255. return;
  31256. }
  31257. if (!this._indexBufferIsUpdatable) {
  31258. this.setIndices(indices, null, true);
  31259. }
  31260. else {
  31261. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  31262. }
  31263. };
  31264. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  31265. if (totalVertices === void 0) { totalVertices = null; }
  31266. if (updatable === void 0) { updatable = false; }
  31267. if (this._indexBuffer) {
  31268. this._engine._releaseBuffer(this._indexBuffer);
  31269. }
  31270. this._disposeVertexArrayObjects();
  31271. this._indices = indices;
  31272. this._indexBufferIsUpdatable = updatable;
  31273. if (this._meshes.length !== 0 && this._indices) {
  31274. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  31275. }
  31276. if (totalVertices != undefined) {
  31277. this._totalVertices = totalVertices;
  31278. }
  31279. var meshes = this._meshes;
  31280. var numOfMeshes = meshes.length;
  31281. for (var index = 0; index < numOfMeshes; index++) {
  31282. meshes[index]._createGlobalSubMesh(true);
  31283. }
  31284. this.notifyUpdate();
  31285. };
  31286. Geometry.prototype.getTotalIndices = function () {
  31287. if (!this.isReady()) {
  31288. return 0;
  31289. }
  31290. return this._indices.length;
  31291. };
  31292. Geometry.prototype.getIndices = function (copyWhenShared) {
  31293. if (!this.isReady()) {
  31294. return null;
  31295. }
  31296. var orig = this._indices;
  31297. if (!copyWhenShared || this._meshes.length === 1) {
  31298. return orig;
  31299. }
  31300. else {
  31301. var len = orig.length;
  31302. var copy = [];
  31303. for (var i = 0; i < len; i++) {
  31304. copy.push(orig[i]);
  31305. }
  31306. return copy;
  31307. }
  31308. };
  31309. Geometry.prototype.getIndexBuffer = function () {
  31310. if (!this.isReady()) {
  31311. return null;
  31312. }
  31313. return this._indexBuffer;
  31314. };
  31315. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  31316. if (effect === void 0) { effect = null; }
  31317. if (!effect || !this._vertexArrayObjects) {
  31318. return;
  31319. }
  31320. if (this._vertexArrayObjects[effect.key]) {
  31321. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  31322. delete this._vertexArrayObjects[effect.key];
  31323. }
  31324. };
  31325. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  31326. var meshes = this._meshes;
  31327. var index = meshes.indexOf(mesh);
  31328. if (index === -1) {
  31329. return;
  31330. }
  31331. meshes.splice(index, 1);
  31332. mesh._geometry = null;
  31333. if (meshes.length === 0 && shouldDispose) {
  31334. this.dispose();
  31335. }
  31336. };
  31337. Geometry.prototype.applyToMesh = function (mesh) {
  31338. if (mesh._geometry === this) {
  31339. return;
  31340. }
  31341. var previousGeometry = mesh._geometry;
  31342. if (previousGeometry) {
  31343. previousGeometry.releaseForMesh(mesh);
  31344. }
  31345. var meshes = this._meshes;
  31346. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  31347. mesh._geometry = this;
  31348. this._scene.pushGeometry(this);
  31349. meshes.push(mesh);
  31350. if (this.isReady()) {
  31351. this._applyToMesh(mesh);
  31352. }
  31353. else {
  31354. mesh._boundingInfo = this._boundingInfo;
  31355. }
  31356. };
  31357. Geometry.prototype.updateExtend = function (data, stride) {
  31358. if (data === void 0) { data = null; }
  31359. if (!data) {
  31360. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  31361. }
  31362. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  31363. };
  31364. Geometry.prototype._applyToMesh = function (mesh) {
  31365. var numOfMeshes = this._meshes.length;
  31366. // vertexBuffers
  31367. for (var kind in this._vertexBuffers) {
  31368. if (numOfMeshes === 1) {
  31369. this._vertexBuffers[kind].create();
  31370. }
  31371. var buffer = this._vertexBuffers[kind].getBuffer();
  31372. if (buffer)
  31373. buffer.references = numOfMeshes;
  31374. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31375. if (!this._extend) {
  31376. this.updateExtend(this._vertexBuffers[kind].getData());
  31377. }
  31378. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31379. mesh._createGlobalSubMesh(false);
  31380. //bounding info was just created again, world matrix should be applied again.
  31381. mesh._updateBoundingInfo();
  31382. }
  31383. }
  31384. // indexBuffer
  31385. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  31386. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31387. }
  31388. if (this._indexBuffer) {
  31389. this._indexBuffer.references = numOfMeshes;
  31390. }
  31391. };
  31392. Geometry.prototype.notifyUpdate = function (kind) {
  31393. if (this.onGeometryUpdated) {
  31394. this.onGeometryUpdated(this, kind);
  31395. }
  31396. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  31397. var mesh = _a[_i];
  31398. mesh._markSubMeshesAsAttributesDirty();
  31399. }
  31400. };
  31401. Geometry.prototype.load = function (scene, onLoaded) {
  31402. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31403. return;
  31404. }
  31405. if (this.isReady()) {
  31406. if (onLoaded) {
  31407. onLoaded();
  31408. }
  31409. return;
  31410. }
  31411. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31412. this._queueLoad(scene, onLoaded);
  31413. };
  31414. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  31415. var _this = this;
  31416. if (!this.delayLoadingFile) {
  31417. return;
  31418. }
  31419. scene._addPendingData(this);
  31420. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  31421. if (!_this._delayLoadingFunction) {
  31422. return;
  31423. }
  31424. _this._delayLoadingFunction(JSON.parse(data), _this);
  31425. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31426. _this._delayInfo = [];
  31427. scene._removePendingData(_this);
  31428. var meshes = _this._meshes;
  31429. var numOfMeshes = meshes.length;
  31430. for (var index = 0; index < numOfMeshes; index++) {
  31431. _this._applyToMesh(meshes[index]);
  31432. }
  31433. if (onLoaded) {
  31434. onLoaded();
  31435. }
  31436. }, function () { }, scene.database);
  31437. };
  31438. /**
  31439. * Invert the geometry to move from a right handed system to a left handed one.
  31440. */
  31441. Geometry.prototype.toLeftHanded = function () {
  31442. // Flip faces
  31443. var tIndices = this.getIndices(false);
  31444. if (tIndices != null && tIndices.length > 0) {
  31445. for (var i = 0; i < tIndices.length; i += 3) {
  31446. var tTemp = tIndices[i + 0];
  31447. tIndices[i + 0] = tIndices[i + 2];
  31448. tIndices[i + 2] = tTemp;
  31449. }
  31450. this.setIndices(tIndices);
  31451. }
  31452. // Negate position.z
  31453. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  31454. if (tPositions != null && tPositions.length > 0) {
  31455. for (var i = 0; i < tPositions.length; i += 3) {
  31456. tPositions[i + 2] = -tPositions[i + 2];
  31457. }
  31458. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  31459. }
  31460. // Negate normal.z
  31461. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  31462. if (tNormals != null && tNormals.length > 0) {
  31463. for (var i = 0; i < tNormals.length; i += 3) {
  31464. tNormals[i + 2] = -tNormals[i + 2];
  31465. }
  31466. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  31467. }
  31468. };
  31469. // Cache
  31470. Geometry.prototype._resetPointsArrayCache = function () {
  31471. this._positions = null;
  31472. };
  31473. Geometry.prototype._generatePointsArray = function () {
  31474. if (this._positions)
  31475. return true;
  31476. this._positions = [];
  31477. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31478. if (!data) {
  31479. return false;
  31480. }
  31481. for (var index = 0; index < data.length; index += 3) {
  31482. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  31483. }
  31484. return true;
  31485. };
  31486. Geometry.prototype.isDisposed = function () {
  31487. return this._isDisposed;
  31488. };
  31489. Geometry.prototype._disposeVertexArrayObjects = function () {
  31490. if (this._vertexArrayObjects) {
  31491. for (var kind in this._vertexArrayObjects) {
  31492. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  31493. }
  31494. this._vertexArrayObjects = {};
  31495. }
  31496. };
  31497. Geometry.prototype.dispose = function () {
  31498. var meshes = this._meshes;
  31499. var numOfMeshes = meshes.length;
  31500. var index;
  31501. for (index = 0; index < numOfMeshes; index++) {
  31502. this.releaseForMesh(meshes[index]);
  31503. }
  31504. this._meshes = [];
  31505. this._disposeVertexArrayObjects();
  31506. for (var kind in this._vertexBuffers) {
  31507. this._vertexBuffers[kind].dispose();
  31508. }
  31509. this._vertexBuffers = {};
  31510. this._totalVertices = 0;
  31511. if (this._indexBuffer) {
  31512. this._engine._releaseBuffer(this._indexBuffer);
  31513. }
  31514. this._indexBuffer = null;
  31515. this._indices = [];
  31516. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31517. this.delayLoadingFile = null;
  31518. this._delayLoadingFunction = null;
  31519. this._delayInfo = [];
  31520. this._boundingInfo = null;
  31521. this._scene.removeGeometry(this);
  31522. this._isDisposed = true;
  31523. };
  31524. Geometry.prototype.copy = function (id) {
  31525. var vertexData = new BABYLON.VertexData();
  31526. vertexData.indices = [];
  31527. var indices = this.getIndices();
  31528. if (indices) {
  31529. for (var index = 0; index < indices.length; index++) {
  31530. vertexData.indices.push(indices[index]);
  31531. }
  31532. }
  31533. var updatable = false;
  31534. var stopChecking = false;
  31535. var kind;
  31536. for (kind in this._vertexBuffers) {
  31537. // using slice() to make a copy of the array and not just reference it
  31538. var data = this.getVerticesData(kind);
  31539. if (data instanceof Float32Array) {
  31540. vertexData.set(new Float32Array(data), kind);
  31541. }
  31542. else {
  31543. vertexData.set(data.slice(0), kind);
  31544. }
  31545. if (!stopChecking) {
  31546. var vb = this.getVertexBuffer(kind);
  31547. if (vb) {
  31548. updatable = vb.isUpdatable();
  31549. stopChecking = !updatable;
  31550. }
  31551. }
  31552. }
  31553. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  31554. geometry.delayLoadState = this.delayLoadState;
  31555. geometry.delayLoadingFile = this.delayLoadingFile;
  31556. geometry._delayLoadingFunction = this._delayLoadingFunction;
  31557. for (kind in this._delayInfo) {
  31558. geometry._delayInfo = geometry._delayInfo || [];
  31559. geometry._delayInfo.push(kind);
  31560. }
  31561. // Bounding info
  31562. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31563. return geometry;
  31564. };
  31565. Geometry.prototype.serialize = function () {
  31566. var serializationObject = {};
  31567. serializationObject.id = this.id;
  31568. serializationObject.updatable = this._updatable;
  31569. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  31570. serializationObject.tags = BABYLON.Tags.GetTags(this);
  31571. }
  31572. return serializationObject;
  31573. };
  31574. Geometry.prototype.toNumberArray = function (origin) {
  31575. if (Array.isArray(origin)) {
  31576. return origin;
  31577. }
  31578. else {
  31579. return Array.prototype.slice.call(origin);
  31580. }
  31581. };
  31582. Geometry.prototype.serializeVerticeData = function () {
  31583. var serializationObject = this.serialize();
  31584. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31585. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  31586. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  31587. serializationObject.positions._updatable = true;
  31588. }
  31589. }
  31590. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31591. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  31592. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  31593. serializationObject.normals._updatable = true;
  31594. }
  31595. }
  31596. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31597. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  31598. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  31599. serializationObject.uvs._updatable = true;
  31600. }
  31601. }
  31602. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31603. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  31604. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  31605. serializationObject.uv2s._updatable = true;
  31606. }
  31607. }
  31608. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  31609. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  31610. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  31611. serializationObject.uv3s._updatable = true;
  31612. }
  31613. }
  31614. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  31615. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  31616. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  31617. serializationObject.uv4s._updatable = true;
  31618. }
  31619. }
  31620. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  31621. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  31622. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  31623. serializationObject.uv5s._updatable = true;
  31624. }
  31625. }
  31626. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  31627. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  31628. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  31629. serializationObject.uv6s._updatable = true;
  31630. }
  31631. }
  31632. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  31633. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  31634. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  31635. serializationObject.colors._updatable = true;
  31636. }
  31637. }
  31638. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31639. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  31640. serializationObject.matricesIndices._isExpanded = true;
  31641. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31642. serializationObject.matricesIndices._updatable = true;
  31643. }
  31644. }
  31645. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31646. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  31647. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31648. serializationObject.matricesWeights._updatable = true;
  31649. }
  31650. }
  31651. serializationObject.indices = this.toNumberArray(this.getIndices());
  31652. return serializationObject;
  31653. };
  31654. // Statics
  31655. Geometry.ExtractFromMesh = function (mesh, id) {
  31656. var geometry = mesh._geometry;
  31657. if (!geometry) {
  31658. return null;
  31659. }
  31660. return geometry.copy(id);
  31661. };
  31662. /**
  31663. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  31664. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  31665. * Be aware Math.random() could cause collisions, but:
  31666. * "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"
  31667. */
  31668. Geometry.RandomId = function () {
  31669. return BABYLON.Tools.RandomId();
  31670. };
  31671. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  31672. var scene = mesh.getScene();
  31673. // Geometry
  31674. var geometryId = parsedGeometry.geometryId;
  31675. if (geometryId) {
  31676. var geometry = scene.getGeometryByID(geometryId);
  31677. if (geometry) {
  31678. geometry.applyToMesh(mesh);
  31679. }
  31680. }
  31681. else if (parsedGeometry instanceof ArrayBuffer) {
  31682. var binaryInfo = mesh._binaryInfo;
  31683. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  31684. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  31685. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  31686. }
  31687. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  31688. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  31689. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  31690. }
  31691. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  31692. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  31693. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  31694. }
  31695. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  31696. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  31697. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  31698. }
  31699. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  31700. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  31701. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  31702. }
  31703. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  31704. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  31705. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  31706. }
  31707. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  31708. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  31709. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  31710. }
  31711. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  31712. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  31713. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  31714. }
  31715. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  31716. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  31717. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  31718. }
  31719. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  31720. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  31721. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  31722. }
  31723. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  31724. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  31725. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  31726. }
  31727. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  31728. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  31729. mesh.setIndices(indicesData, null);
  31730. }
  31731. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  31732. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  31733. mesh.subMeshes = [];
  31734. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  31735. var materialIndex = subMeshesData[(i * 5) + 0];
  31736. var verticesStart = subMeshesData[(i * 5) + 1];
  31737. var verticesCount = subMeshesData[(i * 5) + 2];
  31738. var indexStart = subMeshesData[(i * 5) + 3];
  31739. var indexCount = subMeshesData[(i * 5) + 4];
  31740. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  31741. }
  31742. }
  31743. }
  31744. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  31745. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  31746. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  31747. if (parsedGeometry.uvs) {
  31748. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  31749. }
  31750. if (parsedGeometry.uvs2) {
  31751. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  31752. }
  31753. if (parsedGeometry.uvs3) {
  31754. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  31755. }
  31756. if (parsedGeometry.uvs4) {
  31757. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  31758. }
  31759. if (parsedGeometry.uvs5) {
  31760. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  31761. }
  31762. if (parsedGeometry.uvs6) {
  31763. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  31764. }
  31765. if (parsedGeometry.colors) {
  31766. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  31767. }
  31768. if (parsedGeometry.matricesIndices) {
  31769. if (!parsedGeometry.matricesIndices._isExpanded) {
  31770. var floatIndices = [];
  31771. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  31772. var matricesIndex = parsedGeometry.matricesIndices[i];
  31773. floatIndices.push(matricesIndex & 0x000000FF);
  31774. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31775. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31776. floatIndices.push(matricesIndex >> 24);
  31777. }
  31778. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  31779. }
  31780. else {
  31781. delete parsedGeometry.matricesIndices._isExpanded;
  31782. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  31783. }
  31784. }
  31785. if (parsedGeometry.matricesIndicesExtra) {
  31786. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  31787. var floatIndices = [];
  31788. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  31789. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  31790. floatIndices.push(matricesIndex & 0x000000FF);
  31791. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31792. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31793. floatIndices.push(matricesIndex >> 24);
  31794. }
  31795. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  31796. }
  31797. else {
  31798. delete parsedGeometry.matricesIndices._isExpanded;
  31799. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  31800. }
  31801. }
  31802. if (parsedGeometry.matricesWeights) {
  31803. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  31804. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  31805. }
  31806. if (parsedGeometry.matricesWeightsExtra) {
  31807. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  31808. }
  31809. mesh.setIndices(parsedGeometry.indices, null);
  31810. }
  31811. // SubMeshes
  31812. if (parsedGeometry.subMeshes) {
  31813. mesh.subMeshes = [];
  31814. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  31815. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  31816. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  31817. }
  31818. }
  31819. // Flat shading
  31820. if (mesh._shouldGenerateFlatShading) {
  31821. mesh.convertToFlatShadedMesh();
  31822. delete mesh._shouldGenerateFlatShading;
  31823. }
  31824. // Update
  31825. mesh.computeWorldMatrix(true);
  31826. // Octree
  31827. if (scene['_selectionOctree']) {
  31828. scene['_selectionOctree'].addMesh(mesh);
  31829. }
  31830. };
  31831. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  31832. var epsilon = 1e-3;
  31833. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  31834. return;
  31835. }
  31836. var noInfluenceBoneIndex = 0.0;
  31837. if (parsedGeometry.skeletonId > -1) {
  31838. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  31839. if (!skeleton) {
  31840. return;
  31841. }
  31842. noInfluenceBoneIndex = skeleton.bones.length;
  31843. }
  31844. else {
  31845. return;
  31846. }
  31847. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31848. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  31849. var matricesWeights = parsedGeometry.matricesWeights;
  31850. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  31851. var influencers = parsedGeometry.numBoneInfluencer;
  31852. var size = matricesWeights.length;
  31853. for (var i = 0; i < size; i += 4) {
  31854. var weight = 0.0;
  31855. var firstZeroWeight = -1;
  31856. for (var j = 0; j < 4; j++) {
  31857. var w = matricesWeights[i + j];
  31858. weight += w;
  31859. if (w < epsilon && firstZeroWeight < 0) {
  31860. firstZeroWeight = j;
  31861. }
  31862. }
  31863. if (matricesWeightsExtra) {
  31864. for (var j = 0; j < 4; j++) {
  31865. var w = matricesWeightsExtra[i + j];
  31866. weight += w;
  31867. if (w < epsilon && firstZeroWeight < 0) {
  31868. firstZeroWeight = j + 4;
  31869. }
  31870. }
  31871. }
  31872. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  31873. firstZeroWeight = influencers - 1;
  31874. }
  31875. if (weight > epsilon) {
  31876. var mweight = 1.0 / weight;
  31877. for (var j = 0; j < 4; j++) {
  31878. matricesWeights[i + j] *= mweight;
  31879. }
  31880. if (matricesWeightsExtra) {
  31881. for (var j = 0; j < 4; j++) {
  31882. matricesWeightsExtra[i + j] *= mweight;
  31883. }
  31884. }
  31885. }
  31886. else {
  31887. if (firstZeroWeight >= 4) {
  31888. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  31889. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  31890. }
  31891. else {
  31892. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  31893. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  31894. }
  31895. }
  31896. }
  31897. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  31898. if (parsedGeometry.matricesWeightsExtra) {
  31899. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  31900. }
  31901. };
  31902. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  31903. if (scene.getGeometryByID(parsedVertexData.id)) {
  31904. return null; // null since geometry could be something else than a box...
  31905. }
  31906. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  31907. if (BABYLON.Tags) {
  31908. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  31909. }
  31910. if (parsedVertexData.delayLoadingFile) {
  31911. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31912. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  31913. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  31914. geometry._delayInfo = [];
  31915. if (parsedVertexData.hasUVs) {
  31916. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  31917. }
  31918. if (parsedVertexData.hasUVs2) {
  31919. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  31920. }
  31921. if (parsedVertexData.hasUVs3) {
  31922. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  31923. }
  31924. if (parsedVertexData.hasUVs4) {
  31925. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  31926. }
  31927. if (parsedVertexData.hasUVs5) {
  31928. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  31929. }
  31930. if (parsedVertexData.hasUVs6) {
  31931. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  31932. }
  31933. if (parsedVertexData.hasColors) {
  31934. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  31935. }
  31936. if (parsedVertexData.hasMatricesIndices) {
  31937. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31938. }
  31939. if (parsedVertexData.hasMatricesWeights) {
  31940. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31941. }
  31942. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  31943. }
  31944. else {
  31945. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  31946. }
  31947. scene.pushGeometry(geometry, true);
  31948. return geometry;
  31949. };
  31950. return Geometry;
  31951. }());
  31952. BABYLON.Geometry = Geometry;
  31953. /////// Primitives //////////////////////////////////////////////
  31954. (function (Geometry) {
  31955. var Primitives;
  31956. (function (Primitives) {
  31957. /// Abstract class
  31958. var _Primitive = /** @class */ (function (_super) {
  31959. __extends(_Primitive, _super);
  31960. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  31961. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  31962. if (mesh === void 0) { mesh = null; }
  31963. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  31964. _this._canBeRegenerated = _canBeRegenerated;
  31965. _this._beingRegenerated = true;
  31966. _this.regenerate();
  31967. _this._beingRegenerated = false;
  31968. return _this;
  31969. }
  31970. _Primitive.prototype.canBeRegenerated = function () {
  31971. return this._canBeRegenerated;
  31972. };
  31973. _Primitive.prototype.regenerate = function () {
  31974. if (!this._canBeRegenerated) {
  31975. return;
  31976. }
  31977. this._beingRegenerated = true;
  31978. this.setAllVerticesData(this._regenerateVertexData(), false);
  31979. this._beingRegenerated = false;
  31980. };
  31981. _Primitive.prototype.asNewGeometry = function (id) {
  31982. return _super.prototype.copy.call(this, id);
  31983. };
  31984. // overrides
  31985. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  31986. if (!this._beingRegenerated) {
  31987. return;
  31988. }
  31989. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  31990. };
  31991. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  31992. if (!this._beingRegenerated) {
  31993. return;
  31994. }
  31995. _super.prototype.setVerticesData.call(this, kind, data, false);
  31996. };
  31997. // to override
  31998. // protected
  31999. _Primitive.prototype._regenerateVertexData = function () {
  32000. throw new Error("Abstract method");
  32001. };
  32002. _Primitive.prototype.copy = function (id) {
  32003. throw new Error("Must be overriden in sub-classes.");
  32004. };
  32005. _Primitive.prototype.serialize = function () {
  32006. var serializationObject = _super.prototype.serialize.call(this);
  32007. serializationObject.canBeRegenerated = this.canBeRegenerated();
  32008. return serializationObject;
  32009. };
  32010. return _Primitive;
  32011. }(Geometry));
  32012. Primitives._Primitive = _Primitive;
  32013. var Ribbon = /** @class */ (function (_super) {
  32014. __extends(Ribbon, _super);
  32015. // Members
  32016. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  32017. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32018. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32019. _this.pathArray = pathArray;
  32020. _this.closeArray = closeArray;
  32021. _this.closePath = closePath;
  32022. _this.offset = offset;
  32023. _this.side = side;
  32024. return _this;
  32025. }
  32026. Ribbon.prototype._regenerateVertexData = function () {
  32027. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  32028. };
  32029. Ribbon.prototype.copy = function (id) {
  32030. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  32031. };
  32032. return Ribbon;
  32033. }(_Primitive));
  32034. Primitives.Ribbon = Ribbon;
  32035. var Box = /** @class */ (function (_super) {
  32036. __extends(Box, _super);
  32037. // Members
  32038. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  32039. if (mesh === void 0) { mesh = null; }
  32040. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32041. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32042. _this.size = size;
  32043. _this.side = side;
  32044. return _this;
  32045. }
  32046. Box.prototype._regenerateVertexData = function () {
  32047. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  32048. };
  32049. Box.prototype.copy = function (id) {
  32050. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  32051. };
  32052. Box.prototype.serialize = function () {
  32053. var serializationObject = _super.prototype.serialize.call(this);
  32054. serializationObject.size = this.size;
  32055. return serializationObject;
  32056. };
  32057. Box.Parse = function (parsedBox, scene) {
  32058. if (scene.getGeometryByID(parsedBox.id)) {
  32059. return null; // null since geometry could be something else than a box...
  32060. }
  32061. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  32062. if (BABYLON.Tags) {
  32063. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  32064. }
  32065. scene.pushGeometry(box, true);
  32066. return box;
  32067. };
  32068. return Box;
  32069. }(_Primitive));
  32070. Primitives.Box = Box;
  32071. var Sphere = /** @class */ (function (_super) {
  32072. __extends(Sphere, _super);
  32073. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  32074. if (mesh === void 0) { mesh = null; }
  32075. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32076. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32077. _this.segments = segments;
  32078. _this.diameter = diameter;
  32079. _this.side = side;
  32080. return _this;
  32081. }
  32082. Sphere.prototype._regenerateVertexData = function () {
  32083. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  32084. };
  32085. Sphere.prototype.copy = function (id) {
  32086. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  32087. };
  32088. Sphere.prototype.serialize = function () {
  32089. var serializationObject = _super.prototype.serialize.call(this);
  32090. serializationObject.segments = this.segments;
  32091. serializationObject.diameter = this.diameter;
  32092. return serializationObject;
  32093. };
  32094. Sphere.Parse = function (parsedSphere, scene) {
  32095. if (scene.getGeometryByID(parsedSphere.id)) {
  32096. return null; // null since geometry could be something else than a sphere...
  32097. }
  32098. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  32099. if (BABYLON.Tags) {
  32100. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  32101. }
  32102. scene.pushGeometry(sphere, true);
  32103. return sphere;
  32104. };
  32105. return Sphere;
  32106. }(_Primitive));
  32107. Primitives.Sphere = Sphere;
  32108. var Disc = /** @class */ (function (_super) {
  32109. __extends(Disc, _super);
  32110. // Members
  32111. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  32112. if (mesh === void 0) { mesh = null; }
  32113. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32114. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32115. _this.radius = radius;
  32116. _this.tessellation = tessellation;
  32117. _this.side = side;
  32118. return _this;
  32119. }
  32120. Disc.prototype._regenerateVertexData = function () {
  32121. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  32122. };
  32123. Disc.prototype.copy = function (id) {
  32124. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  32125. };
  32126. return Disc;
  32127. }(_Primitive));
  32128. Primitives.Disc = Disc;
  32129. var Cylinder = /** @class */ (function (_super) {
  32130. __extends(Cylinder, _super);
  32131. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  32132. if (subdivisions === void 0) { subdivisions = 1; }
  32133. if (mesh === void 0) { mesh = null; }
  32134. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32135. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32136. _this.height = height;
  32137. _this.diameterTop = diameterTop;
  32138. _this.diameterBottom = diameterBottom;
  32139. _this.tessellation = tessellation;
  32140. _this.subdivisions = subdivisions;
  32141. _this.side = side;
  32142. return _this;
  32143. }
  32144. Cylinder.prototype._regenerateVertexData = function () {
  32145. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  32146. };
  32147. Cylinder.prototype.copy = function (id) {
  32148. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  32149. };
  32150. Cylinder.prototype.serialize = function () {
  32151. var serializationObject = _super.prototype.serialize.call(this);
  32152. serializationObject.height = this.height;
  32153. serializationObject.diameterTop = this.diameterTop;
  32154. serializationObject.diameterBottom = this.diameterBottom;
  32155. serializationObject.tessellation = this.tessellation;
  32156. return serializationObject;
  32157. };
  32158. Cylinder.Parse = function (parsedCylinder, scene) {
  32159. if (scene.getGeometryByID(parsedCylinder.id)) {
  32160. return null; // null since geometry could be something else than a cylinder...
  32161. }
  32162. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  32163. if (BABYLON.Tags) {
  32164. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  32165. }
  32166. scene.pushGeometry(cylinder, true);
  32167. return cylinder;
  32168. };
  32169. return Cylinder;
  32170. }(_Primitive));
  32171. Primitives.Cylinder = Cylinder;
  32172. var Torus = /** @class */ (function (_super) {
  32173. __extends(Torus, _super);
  32174. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  32175. if (mesh === void 0) { mesh = null; }
  32176. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32177. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32178. _this.diameter = diameter;
  32179. _this.thickness = thickness;
  32180. _this.tessellation = tessellation;
  32181. _this.side = side;
  32182. return _this;
  32183. }
  32184. Torus.prototype._regenerateVertexData = function () {
  32185. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  32186. };
  32187. Torus.prototype.copy = function (id) {
  32188. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  32189. };
  32190. Torus.prototype.serialize = function () {
  32191. var serializationObject = _super.prototype.serialize.call(this);
  32192. serializationObject.diameter = this.diameter;
  32193. serializationObject.thickness = this.thickness;
  32194. serializationObject.tessellation = this.tessellation;
  32195. return serializationObject;
  32196. };
  32197. Torus.Parse = function (parsedTorus, scene) {
  32198. if (scene.getGeometryByID(parsedTorus.id)) {
  32199. return null; // null since geometry could be something else than a torus...
  32200. }
  32201. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  32202. if (BABYLON.Tags) {
  32203. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  32204. }
  32205. scene.pushGeometry(torus, true);
  32206. return torus;
  32207. };
  32208. return Torus;
  32209. }(_Primitive));
  32210. Primitives.Torus = Torus;
  32211. var Ground = /** @class */ (function (_super) {
  32212. __extends(Ground, _super);
  32213. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  32214. if (mesh === void 0) { mesh = null; }
  32215. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32216. _this.width = width;
  32217. _this.height = height;
  32218. _this.subdivisions = subdivisions;
  32219. return _this;
  32220. }
  32221. Ground.prototype._regenerateVertexData = function () {
  32222. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  32223. };
  32224. Ground.prototype.copy = function (id) {
  32225. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  32226. };
  32227. Ground.prototype.serialize = function () {
  32228. var serializationObject = _super.prototype.serialize.call(this);
  32229. serializationObject.width = this.width;
  32230. serializationObject.height = this.height;
  32231. serializationObject.subdivisions = this.subdivisions;
  32232. return serializationObject;
  32233. };
  32234. Ground.Parse = function (parsedGround, scene) {
  32235. if (scene.getGeometryByID(parsedGround.id)) {
  32236. return null; // null since geometry could be something else than a ground...
  32237. }
  32238. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  32239. if (BABYLON.Tags) {
  32240. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  32241. }
  32242. scene.pushGeometry(ground, true);
  32243. return ground;
  32244. };
  32245. return Ground;
  32246. }(_Primitive));
  32247. Primitives.Ground = Ground;
  32248. var TiledGround = /** @class */ (function (_super) {
  32249. __extends(TiledGround, _super);
  32250. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  32251. if (mesh === void 0) { mesh = null; }
  32252. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32253. _this.xmin = xmin;
  32254. _this.zmin = zmin;
  32255. _this.xmax = xmax;
  32256. _this.zmax = zmax;
  32257. _this.subdivisions = subdivisions;
  32258. _this.precision = precision;
  32259. return _this;
  32260. }
  32261. TiledGround.prototype._regenerateVertexData = function () {
  32262. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  32263. };
  32264. TiledGround.prototype.copy = function (id) {
  32265. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  32266. };
  32267. return TiledGround;
  32268. }(_Primitive));
  32269. Primitives.TiledGround = TiledGround;
  32270. var Plane = /** @class */ (function (_super) {
  32271. __extends(Plane, _super);
  32272. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  32273. if (mesh === void 0) { mesh = null; }
  32274. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32275. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32276. _this.size = size;
  32277. _this.side = side;
  32278. return _this;
  32279. }
  32280. Plane.prototype._regenerateVertexData = function () {
  32281. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  32282. };
  32283. Plane.prototype.copy = function (id) {
  32284. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  32285. };
  32286. Plane.prototype.serialize = function () {
  32287. var serializationObject = _super.prototype.serialize.call(this);
  32288. serializationObject.size = this.size;
  32289. return serializationObject;
  32290. };
  32291. Plane.Parse = function (parsedPlane, scene) {
  32292. if (scene.getGeometryByID(parsedPlane.id)) {
  32293. return null; // null since geometry could be something else than a ground...
  32294. }
  32295. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  32296. if (BABYLON.Tags) {
  32297. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  32298. }
  32299. scene.pushGeometry(plane, true);
  32300. return plane;
  32301. };
  32302. return Plane;
  32303. }(_Primitive));
  32304. Primitives.Plane = Plane;
  32305. var TorusKnot = /** @class */ (function (_super) {
  32306. __extends(TorusKnot, _super);
  32307. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  32308. if (mesh === void 0) { mesh = null; }
  32309. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32310. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32311. _this.radius = radius;
  32312. _this.tube = tube;
  32313. _this.radialSegments = radialSegments;
  32314. _this.tubularSegments = tubularSegments;
  32315. _this.p = p;
  32316. _this.q = q;
  32317. _this.side = side;
  32318. return _this;
  32319. }
  32320. TorusKnot.prototype._regenerateVertexData = function () {
  32321. 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 });
  32322. };
  32323. TorusKnot.prototype.copy = function (id) {
  32324. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  32325. };
  32326. TorusKnot.prototype.serialize = function () {
  32327. var serializationObject = _super.prototype.serialize.call(this);
  32328. serializationObject.radius = this.radius;
  32329. serializationObject.tube = this.tube;
  32330. serializationObject.radialSegments = this.radialSegments;
  32331. serializationObject.tubularSegments = this.tubularSegments;
  32332. serializationObject.p = this.p;
  32333. serializationObject.q = this.q;
  32334. return serializationObject;
  32335. };
  32336. ;
  32337. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  32338. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  32339. return null; // null since geometry could be something else than a ground...
  32340. }
  32341. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  32342. if (BABYLON.Tags) {
  32343. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  32344. }
  32345. scene.pushGeometry(torusKnot, true);
  32346. return torusKnot;
  32347. };
  32348. return TorusKnot;
  32349. }(_Primitive));
  32350. Primitives.TorusKnot = TorusKnot;
  32351. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  32352. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  32353. })(BABYLON || (BABYLON = {}));
  32354. //# sourceMappingURL=babylon.geometry.js.map
  32355. var BABYLON;
  32356. (function (BABYLON) {
  32357. var PostProcessManager = /** @class */ (function () {
  32358. function PostProcessManager(scene) {
  32359. this._vertexBuffers = {};
  32360. this._scene = scene;
  32361. }
  32362. PostProcessManager.prototype._prepareBuffers = function () {
  32363. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  32364. return;
  32365. }
  32366. // VBO
  32367. var vertices = [];
  32368. vertices.push(1, 1);
  32369. vertices.push(-1, 1);
  32370. vertices.push(-1, -1);
  32371. vertices.push(1, -1);
  32372. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  32373. this._buildIndexBuffer();
  32374. };
  32375. PostProcessManager.prototype._buildIndexBuffer = function () {
  32376. // Indices
  32377. var indices = [];
  32378. indices.push(0);
  32379. indices.push(1);
  32380. indices.push(2);
  32381. indices.push(0);
  32382. indices.push(2);
  32383. indices.push(3);
  32384. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  32385. };
  32386. PostProcessManager.prototype._rebuild = function () {
  32387. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32388. if (!vb) {
  32389. return;
  32390. }
  32391. vb._rebuild();
  32392. this._buildIndexBuffer();
  32393. };
  32394. // Methods
  32395. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  32396. if (sourceTexture === void 0) { sourceTexture = null; }
  32397. if (postProcesses === void 0) { postProcesses = null; }
  32398. var camera = this._scene.activeCamera;
  32399. if (!camera) {
  32400. return false;
  32401. }
  32402. var postProcesses = postProcesses || camera._postProcesses;
  32403. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32404. return false;
  32405. }
  32406. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  32407. return true;
  32408. };
  32409. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  32410. if (targetTexture === void 0) { targetTexture = null; }
  32411. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  32412. if (!this._scene.activeCamera) {
  32413. return;
  32414. }
  32415. var engine = this._scene.getEngine();
  32416. for (var index = 0; index < postProcesses.length; index++) {
  32417. if (index < postProcesses.length - 1) {
  32418. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  32419. }
  32420. else {
  32421. if (targetTexture) {
  32422. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  32423. }
  32424. else {
  32425. engine.restoreDefaultFramebuffer();
  32426. }
  32427. }
  32428. var pp = postProcesses[index];
  32429. var effect = pp.apply();
  32430. if (effect) {
  32431. pp.onBeforeRenderObservable.notifyObservers(effect);
  32432. // VBOs
  32433. this._prepareBuffers();
  32434. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32435. // Draw order
  32436. engine.draw(true, 0, 6);
  32437. pp.onAfterRenderObservable.notifyObservers(effect);
  32438. }
  32439. }
  32440. // Restore depth buffer
  32441. engine.setDepthBuffer(true);
  32442. engine.setDepthWrite(true);
  32443. };
  32444. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  32445. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  32446. var camera = this._scene.activeCamera;
  32447. if (!camera) {
  32448. return;
  32449. }
  32450. postProcesses = postProcesses || camera._postProcesses;
  32451. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32452. return;
  32453. }
  32454. var engine = this._scene.getEngine();
  32455. for (var index = 0, len = postProcesses.length; index < len; index++) {
  32456. if (index < len - 1) {
  32457. postProcesses[index + 1].activate(camera, targetTexture);
  32458. }
  32459. else {
  32460. if (targetTexture) {
  32461. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  32462. }
  32463. else {
  32464. engine.restoreDefaultFramebuffer();
  32465. }
  32466. }
  32467. if (doNotPresent) {
  32468. break;
  32469. }
  32470. var pp = postProcesses[index];
  32471. var effect = pp.apply();
  32472. if (effect) {
  32473. pp.onBeforeRenderObservable.notifyObservers(effect);
  32474. // VBOs
  32475. this._prepareBuffers();
  32476. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32477. // Draw order
  32478. engine.draw(true, 0, 6);
  32479. pp.onAfterRenderObservable.notifyObservers(effect);
  32480. }
  32481. }
  32482. // Restore states
  32483. engine.setDepthBuffer(true);
  32484. engine.setDepthWrite(true);
  32485. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32486. };
  32487. PostProcessManager.prototype.dispose = function () {
  32488. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32489. if (buffer) {
  32490. buffer.dispose();
  32491. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  32492. }
  32493. if (this._indexBuffer) {
  32494. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32495. this._indexBuffer = null;
  32496. }
  32497. };
  32498. return PostProcessManager;
  32499. }());
  32500. BABYLON.PostProcessManager = PostProcessManager;
  32501. })(BABYLON || (BABYLON = {}));
  32502. //# sourceMappingURL=babylon.postProcessManager.js.map
  32503. var BABYLON;
  32504. (function (BABYLON) {
  32505. /**
  32506. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  32507. */
  32508. var PerformanceMonitor = /** @class */ (function () {
  32509. /**
  32510. * constructor
  32511. * @param frameSampleSize The number of samples required to saturate the sliding window
  32512. */
  32513. function PerformanceMonitor(frameSampleSize) {
  32514. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  32515. this._enabled = true;
  32516. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  32517. }
  32518. /**
  32519. * Samples current frame
  32520. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  32521. */
  32522. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  32523. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  32524. if (!this._enabled)
  32525. return;
  32526. if (this._lastFrameTimeMs != null) {
  32527. var dt = timeMs - this._lastFrameTimeMs;
  32528. this._rollingFrameTime.add(dt);
  32529. }
  32530. this._lastFrameTimeMs = timeMs;
  32531. };
  32532. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  32533. /**
  32534. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  32535. * @return Average frame time in milliseconds
  32536. */
  32537. get: function () {
  32538. return this._rollingFrameTime.average;
  32539. },
  32540. enumerable: true,
  32541. configurable: true
  32542. });
  32543. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  32544. /**
  32545. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  32546. * @return Frame time variance in milliseconds squared
  32547. */
  32548. get: function () {
  32549. return this._rollingFrameTime.variance;
  32550. },
  32551. enumerable: true,
  32552. configurable: true
  32553. });
  32554. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  32555. /**
  32556. * Returns the frame time of the most recent frame
  32557. * @return Frame time in milliseconds
  32558. */
  32559. get: function () {
  32560. return this._rollingFrameTime.history(0);
  32561. },
  32562. enumerable: true,
  32563. configurable: true
  32564. });
  32565. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  32566. /**
  32567. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  32568. * @return Framerate in frames per second
  32569. */
  32570. get: function () {
  32571. return 1000.0 / this._rollingFrameTime.average;
  32572. },
  32573. enumerable: true,
  32574. configurable: true
  32575. });
  32576. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  32577. /**
  32578. * Returns the average framerate in frames per second using the most recent frame time
  32579. * @return Framerate in frames per second
  32580. */
  32581. get: function () {
  32582. var history = this._rollingFrameTime.history(0);
  32583. if (history === 0) {
  32584. return 0;
  32585. }
  32586. return 1000.0 / history;
  32587. },
  32588. enumerable: true,
  32589. configurable: true
  32590. });
  32591. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  32592. /**
  32593. * Returns true if enough samples have been taken to completely fill the sliding window
  32594. * @return true if saturated
  32595. */
  32596. get: function () {
  32597. return this._rollingFrameTime.isSaturated();
  32598. },
  32599. enumerable: true,
  32600. configurable: true
  32601. });
  32602. /**
  32603. * Enables contributions to the sliding window sample set
  32604. */
  32605. PerformanceMonitor.prototype.enable = function () {
  32606. this._enabled = true;
  32607. };
  32608. /**
  32609. * Disables contributions to the sliding window sample set
  32610. * Samples will not be interpolated over the disabled period
  32611. */
  32612. PerformanceMonitor.prototype.disable = function () {
  32613. this._enabled = false;
  32614. //clear last sample to avoid interpolating over the disabled period when next enabled
  32615. this._lastFrameTimeMs = null;
  32616. };
  32617. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  32618. /**
  32619. * Returns true if sampling is enabled
  32620. * @return true if enabled
  32621. */
  32622. get: function () {
  32623. return this._enabled;
  32624. },
  32625. enumerable: true,
  32626. configurable: true
  32627. });
  32628. /**
  32629. * Resets performance monitor
  32630. */
  32631. PerformanceMonitor.prototype.reset = function () {
  32632. //clear last sample to avoid interpolating over the disabled period when next enabled
  32633. this._lastFrameTimeMs = null;
  32634. //wipe record
  32635. this._rollingFrameTime.reset();
  32636. };
  32637. return PerformanceMonitor;
  32638. }());
  32639. BABYLON.PerformanceMonitor = PerformanceMonitor;
  32640. /**
  32641. * RollingAverage
  32642. *
  32643. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  32644. */
  32645. var RollingAverage = /** @class */ (function () {
  32646. /**
  32647. * constructor
  32648. * @param length The number of samples required to saturate the sliding window
  32649. */
  32650. function RollingAverage(length) {
  32651. this._samples = new Array(length);
  32652. this.reset();
  32653. }
  32654. /**
  32655. * Adds a sample to the sample set
  32656. * @param v The sample value
  32657. */
  32658. RollingAverage.prototype.add = function (v) {
  32659. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  32660. var delta;
  32661. //we need to check if we've already wrapped round
  32662. if (this.isSaturated()) {
  32663. //remove bottom of stack from mean
  32664. var bottomValue = this._samples[this._pos];
  32665. delta = bottomValue - this.average;
  32666. this.average -= delta / (this._sampleCount - 1);
  32667. this._m2 -= delta * (bottomValue - this.average);
  32668. }
  32669. else {
  32670. this._sampleCount++;
  32671. }
  32672. //add new value to mean
  32673. delta = v - this.average;
  32674. this.average += delta / (this._sampleCount);
  32675. this._m2 += delta * (v - this.average);
  32676. //set the new variance
  32677. this.variance = this._m2 / (this._sampleCount - 1);
  32678. this._samples[this._pos] = v;
  32679. this._pos++;
  32680. this._pos %= this._samples.length; //positive wrap around
  32681. };
  32682. /**
  32683. * Returns previously added values or null if outside of history or outside the sliding window domain
  32684. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  32685. * @return Value previously recorded with add() or null if outside of range
  32686. */
  32687. RollingAverage.prototype.history = function (i) {
  32688. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  32689. return 0;
  32690. }
  32691. var i0 = this._wrapPosition(this._pos - 1.0);
  32692. return this._samples[this._wrapPosition(i0 - i)];
  32693. };
  32694. /**
  32695. * Returns true if enough samples have been taken to completely fill the sliding window
  32696. * @return true if sample-set saturated
  32697. */
  32698. RollingAverage.prototype.isSaturated = function () {
  32699. return this._sampleCount >= this._samples.length;
  32700. };
  32701. /**
  32702. * Resets the rolling average (equivalent to 0 samples taken so far)
  32703. */
  32704. RollingAverage.prototype.reset = function () {
  32705. this.average = 0;
  32706. this.variance = 0;
  32707. this._sampleCount = 0;
  32708. this._pos = 0;
  32709. this._m2 = 0;
  32710. };
  32711. /**
  32712. * Wraps a value around the sample range boundaries
  32713. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  32714. * @return Wrapped position in sample range
  32715. */
  32716. RollingAverage.prototype._wrapPosition = function (i) {
  32717. var max = this._samples.length;
  32718. return ((i % max) + max) % max;
  32719. };
  32720. return RollingAverage;
  32721. }());
  32722. BABYLON.RollingAverage = RollingAverage;
  32723. })(BABYLON || (BABYLON = {}));
  32724. //# sourceMappingURL=babylon.performanceMonitor.js.map
  32725. var BABYLON;
  32726. (function (BABYLON) {
  32727. /**
  32728. * This groups together the common properties used for image processing either in direct forward pass
  32729. * or through post processing effect depending on the use of the image processing pipeline in your scene
  32730. * or not.
  32731. */
  32732. var ImageProcessingConfiguration = /** @class */ (function () {
  32733. function ImageProcessingConfiguration() {
  32734. /**
  32735. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  32736. */
  32737. this.colorCurves = new BABYLON.ColorCurves();
  32738. this._colorCurvesEnabled = false;
  32739. this._colorGradingEnabled = false;
  32740. this._colorGradingWithGreenDepth = true;
  32741. this._colorGradingBGR = true;
  32742. this._exposure = 1.0;
  32743. this._toneMappingEnabled = false;
  32744. this._contrast = 1.0;
  32745. /**
  32746. * Vignette stretch size.
  32747. */
  32748. this.vignetteStretch = 0;
  32749. /**
  32750. * Vignette centre X Offset.
  32751. */
  32752. this.vignetteCentreX = 0;
  32753. /**
  32754. * Vignette centre Y Offset.
  32755. */
  32756. this.vignetteCentreY = 0;
  32757. /**
  32758. * Vignette weight or intensity of the vignette effect.
  32759. */
  32760. this.vignetteWeight = 1.5;
  32761. /**
  32762. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  32763. * if vignetteEnabled is set to true.
  32764. */
  32765. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  32766. /**
  32767. * Camera field of view used by the Vignette effect.
  32768. */
  32769. this.vignetteCameraFov = 0.5;
  32770. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  32771. this._vignetteEnabled = false;
  32772. this._applyByPostProcess = false;
  32773. this._isEnabled = true;
  32774. /**
  32775. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  32776. * @type {BABYLON.Observable}
  32777. */
  32778. this.onUpdateParameters = new BABYLON.Observable();
  32779. }
  32780. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  32781. /**
  32782. * Gets wether the color curves effect is enabled.
  32783. */
  32784. get: function () {
  32785. return this._colorCurvesEnabled;
  32786. },
  32787. /**
  32788. * Sets wether the color curves effect is enabled.
  32789. */
  32790. set: function (value) {
  32791. if (this._colorCurvesEnabled === value) {
  32792. return;
  32793. }
  32794. this._colorCurvesEnabled = value;
  32795. this._updateParameters();
  32796. },
  32797. enumerable: true,
  32798. configurable: true
  32799. });
  32800. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  32801. /**
  32802. * Gets wether the color grading effect is enabled.
  32803. */
  32804. get: function () {
  32805. return this._colorGradingEnabled;
  32806. },
  32807. /**
  32808. * Sets wether the color grading effect is enabled.
  32809. */
  32810. set: function (value) {
  32811. if (this._colorGradingEnabled === value) {
  32812. return;
  32813. }
  32814. this._colorGradingEnabled = value;
  32815. this._updateParameters();
  32816. },
  32817. enumerable: true,
  32818. configurable: true
  32819. });
  32820. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  32821. /**
  32822. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  32823. */
  32824. get: function () {
  32825. return this._colorGradingWithGreenDepth;
  32826. },
  32827. /**
  32828. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  32829. */
  32830. set: function (value) {
  32831. if (this._colorGradingWithGreenDepth === value) {
  32832. return;
  32833. }
  32834. this._colorGradingWithGreenDepth = value;
  32835. this._updateParameters();
  32836. },
  32837. enumerable: true,
  32838. configurable: true
  32839. });
  32840. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  32841. /**
  32842. * Gets wether the color grading texture contains BGR values.
  32843. */
  32844. get: function () {
  32845. return this._colorGradingBGR;
  32846. },
  32847. /**
  32848. * Sets wether the color grading texture contains BGR values.
  32849. */
  32850. set: function (value) {
  32851. if (this._colorGradingBGR === value) {
  32852. return;
  32853. }
  32854. this._colorGradingBGR = value;
  32855. this._updateParameters();
  32856. },
  32857. enumerable: true,
  32858. configurable: true
  32859. });
  32860. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  32861. /**
  32862. * Gets the Exposure used in the effect.
  32863. */
  32864. get: function () {
  32865. return this._exposure;
  32866. },
  32867. /**
  32868. * Sets the Exposure used in the effect.
  32869. */
  32870. set: function (value) {
  32871. if (this._exposure === value) {
  32872. return;
  32873. }
  32874. this._exposure = value;
  32875. this._updateParameters();
  32876. },
  32877. enumerable: true,
  32878. configurable: true
  32879. });
  32880. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  32881. /**
  32882. * Gets wether the tone mapping effect is enabled.
  32883. */
  32884. get: function () {
  32885. return this._toneMappingEnabled;
  32886. },
  32887. /**
  32888. * Sets wether the tone mapping effect is enabled.
  32889. */
  32890. set: function (value) {
  32891. if (this._toneMappingEnabled === value) {
  32892. return;
  32893. }
  32894. this._toneMappingEnabled = value;
  32895. this._updateParameters();
  32896. },
  32897. enumerable: true,
  32898. configurable: true
  32899. });
  32900. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  32901. /**
  32902. * Gets the contrast used in the effect.
  32903. */
  32904. get: function () {
  32905. return this._contrast;
  32906. },
  32907. /**
  32908. * Sets the contrast used in the effect.
  32909. */
  32910. set: function (value) {
  32911. if (this._contrast === value) {
  32912. return;
  32913. }
  32914. this._contrast = value;
  32915. this._updateParameters();
  32916. },
  32917. enumerable: true,
  32918. configurable: true
  32919. });
  32920. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  32921. /**
  32922. * Gets the vignette blend mode allowing different kind of effect.
  32923. */
  32924. get: function () {
  32925. return this._vignetteBlendMode;
  32926. },
  32927. /**
  32928. * Sets the vignette blend mode allowing different kind of effect.
  32929. */
  32930. set: function (value) {
  32931. if (this._vignetteBlendMode === value) {
  32932. return;
  32933. }
  32934. this._vignetteBlendMode = value;
  32935. this._updateParameters();
  32936. },
  32937. enumerable: true,
  32938. configurable: true
  32939. });
  32940. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  32941. /**
  32942. * Gets wether the vignette effect is enabled.
  32943. */
  32944. get: function () {
  32945. return this._vignetteEnabled;
  32946. },
  32947. /**
  32948. * Sets wether the vignette effect is enabled.
  32949. */
  32950. set: function (value) {
  32951. if (this._vignetteEnabled === value) {
  32952. return;
  32953. }
  32954. this._vignetteEnabled = value;
  32955. this._updateParameters();
  32956. },
  32957. enumerable: true,
  32958. configurable: true
  32959. });
  32960. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  32961. /**
  32962. * Gets wether the image processing is applied through a post process or not.
  32963. */
  32964. get: function () {
  32965. return this._applyByPostProcess;
  32966. },
  32967. /**
  32968. * Sets wether the image processing is applied through a post process or not.
  32969. */
  32970. set: function (value) {
  32971. if (this._applyByPostProcess === value) {
  32972. return;
  32973. }
  32974. this._applyByPostProcess = value;
  32975. this._updateParameters();
  32976. },
  32977. enumerable: true,
  32978. configurable: true
  32979. });
  32980. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  32981. /**
  32982. * Gets wether the image processing is enabled or not.
  32983. */
  32984. get: function () {
  32985. return this._isEnabled;
  32986. },
  32987. /**
  32988. * Sets wether the image processing is enabled or not.
  32989. */
  32990. set: function (value) {
  32991. if (this._isEnabled === value) {
  32992. return;
  32993. }
  32994. this._isEnabled = value;
  32995. this._updateParameters();
  32996. },
  32997. enumerable: true,
  32998. configurable: true
  32999. });
  33000. /**
  33001. * Method called each time the image processing information changes requires to recompile the effect.
  33002. */
  33003. ImageProcessingConfiguration.prototype._updateParameters = function () {
  33004. this.onUpdateParameters.notifyObservers(this);
  33005. };
  33006. ImageProcessingConfiguration.prototype.getClassName = function () {
  33007. return "ImageProcessingConfiguration";
  33008. };
  33009. /**
  33010. * Prepare the list of uniforms associated with the Image Processing effects.
  33011. * @param uniformsList The list of uniforms used in the effect
  33012. * @param defines the list of defines currently in use
  33013. */
  33014. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  33015. if (defines.EXPOSURE) {
  33016. uniforms.push("exposureLinear");
  33017. }
  33018. if (defines.CONTRAST) {
  33019. uniforms.push("contrast");
  33020. }
  33021. if (defines.COLORGRADING) {
  33022. uniforms.push("colorTransformSettings");
  33023. }
  33024. if (defines.VIGNETTE) {
  33025. uniforms.push("vInverseScreenSize");
  33026. uniforms.push("vignetteSettings1");
  33027. uniforms.push("vignetteSettings2");
  33028. }
  33029. if (defines.COLORCURVES) {
  33030. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  33031. }
  33032. };
  33033. /**
  33034. * Prepare the list of samplers associated with the Image Processing effects.
  33035. * @param uniformsList The list of uniforms used in the effect
  33036. * @param defines the list of defines currently in use
  33037. */
  33038. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  33039. if (defines.COLORGRADING) {
  33040. samplersList.push("txColorTransform");
  33041. }
  33042. };
  33043. /**
  33044. * Prepare the list of defines associated to the shader.
  33045. * @param defines the list of defines to complete
  33046. */
  33047. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  33048. if (forPostProcess === void 0) { forPostProcess = false; }
  33049. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  33050. defines.VIGNETTE = false;
  33051. defines.TONEMAPPING = false;
  33052. defines.CONTRAST = false;
  33053. defines.EXPOSURE = false;
  33054. defines.COLORCURVES = false;
  33055. defines.COLORGRADING = false;
  33056. defines.COLORGRADING3D = false;
  33057. defines.IMAGEPROCESSING = false;
  33058. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  33059. return;
  33060. }
  33061. defines.VIGNETTE = this.vignetteEnabled;
  33062. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  33063. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  33064. defines.TONEMAPPING = this.toneMappingEnabled;
  33065. defines.CONTRAST = (this.contrast !== 1.0);
  33066. defines.EXPOSURE = (this.exposure !== 1.0);
  33067. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  33068. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  33069. if (defines.COLORGRADING) {
  33070. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  33071. }
  33072. else {
  33073. defines.COLORGRADING3D = false;
  33074. }
  33075. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  33076. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  33077. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  33078. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  33079. };
  33080. /**
  33081. * Returns true if all the image processing information are ready.
  33082. */
  33083. ImageProcessingConfiguration.prototype.isReady = function () {
  33084. // Color Grading texure can not be none blocking.
  33085. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  33086. };
  33087. /**
  33088. * Binds the image processing to the shader.
  33089. * @param effect The effect to bind to
  33090. */
  33091. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  33092. if (aspectRatio === void 0) { aspectRatio = 1; }
  33093. // Color Curves
  33094. if (this._colorCurvesEnabled && this.colorCurves) {
  33095. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  33096. }
  33097. // Vignette
  33098. if (this._vignetteEnabled) {
  33099. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  33100. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  33101. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  33102. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  33103. var vignetteScaleX = vignetteScaleY * aspectRatio;
  33104. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  33105. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  33106. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  33107. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  33108. var vignettePower = -2.0 * this.vignetteWeight;
  33109. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  33110. }
  33111. // Exposure
  33112. effect.setFloat("exposureLinear", this.exposure);
  33113. // Contrast
  33114. effect.setFloat("contrast", this.contrast);
  33115. // Color transform settings
  33116. if (this.colorGradingTexture) {
  33117. effect.setTexture("txColorTransform", this.colorGradingTexture);
  33118. var textureSize = this.colorGradingTexture.getSize().height;
  33119. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  33120. 0.5 / textureSize, // textureOffset
  33121. textureSize, // textureSize
  33122. this.colorGradingTexture.level // weight
  33123. );
  33124. }
  33125. };
  33126. /**
  33127. * Clones the current image processing instance.
  33128. * @return The cloned image processing
  33129. */
  33130. ImageProcessingConfiguration.prototype.clone = function () {
  33131. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  33132. };
  33133. /**
  33134. * Serializes the current image processing instance to a json representation.
  33135. * @return a JSON representation
  33136. */
  33137. ImageProcessingConfiguration.prototype.serialize = function () {
  33138. return BABYLON.SerializationHelper.Serialize(this);
  33139. };
  33140. /**
  33141. * Parses the image processing from a json representation.
  33142. * @param source the JSON source to parse
  33143. * @return The parsed image processing
  33144. */
  33145. ImageProcessingConfiguration.Parse = function (source) {
  33146. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  33147. };
  33148. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  33149. /**
  33150. * Used to apply the vignette as a mix with the pixel color.
  33151. */
  33152. get: function () {
  33153. return this._VIGNETTEMODE_MULTIPLY;
  33154. },
  33155. enumerable: true,
  33156. configurable: true
  33157. });
  33158. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  33159. /**
  33160. * Used to apply the vignette as a replacement of the pixel color.
  33161. */
  33162. get: function () {
  33163. return this._VIGNETTEMODE_OPAQUE;
  33164. },
  33165. enumerable: true,
  33166. configurable: true
  33167. });
  33168. // Static constants associated to the image processing.
  33169. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  33170. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  33171. __decorate([
  33172. BABYLON.serializeAsColorCurves()
  33173. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  33174. __decorate([
  33175. BABYLON.serialize()
  33176. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  33177. __decorate([
  33178. BABYLON.serializeAsTexture()
  33179. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  33180. __decorate([
  33181. BABYLON.serialize()
  33182. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  33183. __decorate([
  33184. BABYLON.serialize()
  33185. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  33186. __decorate([
  33187. BABYLON.serialize()
  33188. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  33189. __decorate([
  33190. BABYLON.serialize()
  33191. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  33192. __decorate([
  33193. BABYLON.serialize()
  33194. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  33195. __decorate([
  33196. BABYLON.serialize()
  33197. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  33198. __decorate([
  33199. BABYLON.serialize()
  33200. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  33201. __decorate([
  33202. BABYLON.serialize()
  33203. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  33204. __decorate([
  33205. BABYLON.serialize()
  33206. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  33207. __decorate([
  33208. BABYLON.serialize()
  33209. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  33210. __decorate([
  33211. BABYLON.serializeAsColor4()
  33212. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  33213. __decorate([
  33214. BABYLON.serialize()
  33215. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  33216. __decorate([
  33217. BABYLON.serialize()
  33218. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  33219. __decorate([
  33220. BABYLON.serialize()
  33221. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  33222. __decorate([
  33223. BABYLON.serialize()
  33224. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  33225. __decorate([
  33226. BABYLON.serialize()
  33227. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  33228. return ImageProcessingConfiguration;
  33229. }());
  33230. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  33231. })(BABYLON || (BABYLON = {}));
  33232. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  33233. var BABYLON;
  33234. (function (BABYLON) {
  33235. /**
  33236. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  33237. * It can help converting any input color in a desired output one. This can then be used to create effects
  33238. * from sepia, black and white to sixties or futuristic rendering...
  33239. *
  33240. * The only supported format is currently 3dl.
  33241. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  33242. */
  33243. var ColorGradingTexture = /** @class */ (function (_super) {
  33244. __extends(ColorGradingTexture, _super);
  33245. /**
  33246. * Instantiates a ColorGradingTexture from the following parameters.
  33247. *
  33248. * @param url The location of the color gradind data (currently only supporting 3dl)
  33249. * @param scene The scene the texture will be used in
  33250. */
  33251. function ColorGradingTexture(url, scene) {
  33252. var _this = _super.call(this, scene) || this;
  33253. if (!url) {
  33254. return _this;
  33255. }
  33256. _this._engine = scene.getEngine();
  33257. _this._textureMatrix = BABYLON.Matrix.Identity();
  33258. _this.name = url;
  33259. _this.url = url;
  33260. _this.hasAlpha = false;
  33261. _this.isCube = false;
  33262. _this.is3D = _this._engine.webGLVersion > 1;
  33263. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33264. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33265. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33266. _this.anisotropicFilteringLevel = 1;
  33267. _this._texture = _this._getFromCache(url, true);
  33268. if (!_this._texture) {
  33269. if (!scene.useDelayedTextureLoading) {
  33270. _this.loadTexture();
  33271. }
  33272. else {
  33273. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33274. }
  33275. }
  33276. return _this;
  33277. }
  33278. /**
  33279. * Returns the texture matrix used in most of the material.
  33280. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  33281. */
  33282. ColorGradingTexture.prototype.getTextureMatrix = function () {
  33283. return this._textureMatrix;
  33284. };
  33285. /**
  33286. * Occurs when the file being loaded is a .3dl LUT file.
  33287. */
  33288. ColorGradingTexture.prototype.load3dlTexture = function () {
  33289. var engine = this._engine;
  33290. var texture;
  33291. if (engine.webGLVersion === 1) {
  33292. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33293. }
  33294. else {
  33295. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33296. }
  33297. this._texture = texture;
  33298. var callback = function (text) {
  33299. if (typeof text !== "string") {
  33300. return;
  33301. }
  33302. var data = null;
  33303. var tempData = null;
  33304. var line;
  33305. var lines = text.split('\n');
  33306. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  33307. var maxColor = 0;
  33308. for (var i = 0; i < lines.length; i++) {
  33309. line = lines[i];
  33310. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  33311. continue;
  33312. if (line.indexOf('#') === 0)
  33313. continue;
  33314. var words = line.split(" ");
  33315. if (size === 0) {
  33316. // Number of space + one
  33317. size = words.length;
  33318. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  33319. tempData = new Float32Array(size * size * size * 4);
  33320. continue;
  33321. }
  33322. if (size != 0) {
  33323. var r = Math.max(parseInt(words[0]), 0);
  33324. var g = Math.max(parseInt(words[1]), 0);
  33325. var b = Math.max(parseInt(words[2]), 0);
  33326. maxColor = Math.max(r, maxColor);
  33327. maxColor = Math.max(g, maxColor);
  33328. maxColor = Math.max(b, maxColor);
  33329. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  33330. if (tempData) {
  33331. tempData[pixelStorageIndex + 0] = r;
  33332. tempData[pixelStorageIndex + 1] = g;
  33333. tempData[pixelStorageIndex + 2] = b;
  33334. }
  33335. pixelIndexSlice++;
  33336. if (pixelIndexSlice % size == 0) {
  33337. pixelIndexH++;
  33338. pixelIndexSlice = 0;
  33339. if (pixelIndexH % size == 0) {
  33340. pixelIndexW++;
  33341. pixelIndexH = 0;
  33342. }
  33343. }
  33344. }
  33345. }
  33346. if (tempData && data) {
  33347. for (var i = 0; i < tempData.length; i++) {
  33348. if (i > 0 && (i + 1) % 4 === 0) {
  33349. data[i] = 255;
  33350. }
  33351. else {
  33352. var value = tempData[i];
  33353. data[i] = (value / maxColor * 255);
  33354. }
  33355. }
  33356. }
  33357. if (texture.is3D) {
  33358. texture.updateSize(size, size, size);
  33359. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33360. }
  33361. else {
  33362. texture.updateSize(size * size, size);
  33363. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33364. }
  33365. };
  33366. BABYLON.Tools.LoadFile(this.url, callback);
  33367. return this._texture;
  33368. };
  33369. /**
  33370. * Starts the loading process of the texture.
  33371. */
  33372. ColorGradingTexture.prototype.loadTexture = function () {
  33373. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  33374. this.load3dlTexture();
  33375. }
  33376. };
  33377. /**
  33378. * Clones the color gradind texture.
  33379. */
  33380. ColorGradingTexture.prototype.clone = function () {
  33381. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  33382. // Base texture
  33383. newTexture.level = this.level;
  33384. return newTexture;
  33385. };
  33386. /**
  33387. * Called during delayed load for textures.
  33388. */
  33389. ColorGradingTexture.prototype.delayLoad = function () {
  33390. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  33391. return;
  33392. }
  33393. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33394. this._texture = this._getFromCache(this.url, true);
  33395. if (!this._texture) {
  33396. this.loadTexture();
  33397. }
  33398. };
  33399. /**
  33400. * Parses a color grading texture serialized by Babylon.
  33401. * @param parsedTexture The texture information being parsedTexture
  33402. * @param scene The scene to load the texture in
  33403. * @param rootUrl The root url of the data assets to load
  33404. * @return A color gradind texture
  33405. */
  33406. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  33407. var texture = null;
  33408. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  33409. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  33410. texture.name = parsedTexture.name;
  33411. texture.level = parsedTexture.level;
  33412. }
  33413. return texture;
  33414. };
  33415. /**
  33416. * Serializes the LUT texture to json format.
  33417. */
  33418. ColorGradingTexture.prototype.serialize = function () {
  33419. if (!this.name) {
  33420. return null;
  33421. }
  33422. var serializationObject = {};
  33423. serializationObject.name = this.name;
  33424. serializationObject.level = this.level;
  33425. serializationObject.customType = "BABYLON.ColorGradingTexture";
  33426. return serializationObject;
  33427. };
  33428. /**
  33429. * Empty line regex stored for GC.
  33430. */
  33431. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  33432. return ColorGradingTexture;
  33433. }(BABYLON.BaseTexture));
  33434. BABYLON.ColorGradingTexture = ColorGradingTexture;
  33435. })(BABYLON || (BABYLON = {}));
  33436. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  33437. var BABYLON;
  33438. (function (BABYLON) {
  33439. /**
  33440. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33441. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33442. * 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;
  33443. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33444. */
  33445. var ColorCurves = /** @class */ (function () {
  33446. function ColorCurves() {
  33447. this._dirty = true;
  33448. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  33449. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  33450. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  33451. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  33452. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  33453. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  33454. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  33455. this._globalHue = 30;
  33456. this._globalDensity = 0;
  33457. this._globalSaturation = 0;
  33458. this._globalExposure = 0;
  33459. this._highlightsHue = 30;
  33460. this._highlightsDensity = 0;
  33461. this._highlightsSaturation = 0;
  33462. this._highlightsExposure = 0;
  33463. this._midtonesHue = 30;
  33464. this._midtonesDensity = 0;
  33465. this._midtonesSaturation = 0;
  33466. this._midtonesExposure = 0;
  33467. this._shadowsHue = 30;
  33468. this._shadowsDensity = 0;
  33469. this._shadowsSaturation = 0;
  33470. this._shadowsExposure = 0;
  33471. }
  33472. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  33473. /**
  33474. * Gets the global Hue value.
  33475. * 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).
  33476. */
  33477. get: function () {
  33478. return this._globalHue;
  33479. },
  33480. /**
  33481. * Sets the global Hue value.
  33482. * 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).
  33483. */
  33484. set: function (value) {
  33485. this._globalHue = value;
  33486. this._dirty = true;
  33487. },
  33488. enumerable: true,
  33489. configurable: true
  33490. });
  33491. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  33492. /**
  33493. * Gets the global Density value.
  33494. * 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.
  33495. * Values less than zero provide a filter of opposite hue.
  33496. */
  33497. get: function () {
  33498. return this._globalDensity;
  33499. },
  33500. /**
  33501. * Sets the global Density value.
  33502. * 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.
  33503. * Values less than zero provide a filter of opposite hue.
  33504. */
  33505. set: function (value) {
  33506. this._globalDensity = value;
  33507. this._dirty = true;
  33508. },
  33509. enumerable: true,
  33510. configurable: true
  33511. });
  33512. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  33513. /**
  33514. * Gets the global Saturation value.
  33515. * 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.
  33516. */
  33517. get: function () {
  33518. return this._globalSaturation;
  33519. },
  33520. /**
  33521. * Sets the global Saturation value.
  33522. * 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.
  33523. */
  33524. set: function (value) {
  33525. this._globalSaturation = value;
  33526. this._dirty = true;
  33527. },
  33528. enumerable: true,
  33529. configurable: true
  33530. });
  33531. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  33532. /**
  33533. * Gets the highlights Hue value.
  33534. * 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).
  33535. */
  33536. get: function () {
  33537. return this._highlightsHue;
  33538. },
  33539. /**
  33540. * Sets the highlights Hue value.
  33541. * 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).
  33542. */
  33543. set: function (value) {
  33544. this._highlightsHue = value;
  33545. this._dirty = true;
  33546. },
  33547. enumerable: true,
  33548. configurable: true
  33549. });
  33550. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  33551. /**
  33552. * Gets the highlights Density value.
  33553. * 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.
  33554. * Values less than zero provide a filter of opposite hue.
  33555. */
  33556. get: function () {
  33557. return this._highlightsDensity;
  33558. },
  33559. /**
  33560. * Sets the highlights Density value.
  33561. * 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.
  33562. * Values less than zero provide a filter of opposite hue.
  33563. */
  33564. set: function (value) {
  33565. this._highlightsDensity = value;
  33566. this._dirty = true;
  33567. },
  33568. enumerable: true,
  33569. configurable: true
  33570. });
  33571. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  33572. /**
  33573. * Gets the highlights Saturation value.
  33574. * 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.
  33575. */
  33576. get: function () {
  33577. return this._highlightsSaturation;
  33578. },
  33579. /**
  33580. * Sets the highlights Saturation value.
  33581. * 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.
  33582. */
  33583. set: function (value) {
  33584. this._highlightsSaturation = value;
  33585. this._dirty = true;
  33586. },
  33587. enumerable: true,
  33588. configurable: true
  33589. });
  33590. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  33591. /**
  33592. * Gets the highlights Exposure value.
  33593. * 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.
  33594. */
  33595. get: function () {
  33596. return this._highlightsExposure;
  33597. },
  33598. /**
  33599. * Sets the highlights Exposure value.
  33600. * 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.
  33601. */
  33602. set: function (value) {
  33603. this._highlightsExposure = value;
  33604. this._dirty = true;
  33605. },
  33606. enumerable: true,
  33607. configurable: true
  33608. });
  33609. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  33610. /**
  33611. * Gets the midtones Hue value.
  33612. * 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).
  33613. */
  33614. get: function () {
  33615. return this._midtonesHue;
  33616. },
  33617. /**
  33618. * Sets the midtones Hue value.
  33619. * 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).
  33620. */
  33621. set: function (value) {
  33622. this._midtonesHue = value;
  33623. this._dirty = true;
  33624. },
  33625. enumerable: true,
  33626. configurable: true
  33627. });
  33628. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  33629. /**
  33630. * Gets the midtones Density value.
  33631. * 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.
  33632. * Values less than zero provide a filter of opposite hue.
  33633. */
  33634. get: function () {
  33635. return this._midtonesDensity;
  33636. },
  33637. /**
  33638. * Sets the midtones Density value.
  33639. * 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.
  33640. * Values less than zero provide a filter of opposite hue.
  33641. */
  33642. set: function (value) {
  33643. this._midtonesDensity = value;
  33644. this._dirty = true;
  33645. },
  33646. enumerable: true,
  33647. configurable: true
  33648. });
  33649. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  33650. /**
  33651. * Gets the midtones Saturation value.
  33652. * 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.
  33653. */
  33654. get: function () {
  33655. return this._midtonesSaturation;
  33656. },
  33657. /**
  33658. * Sets the midtones Saturation value.
  33659. * 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.
  33660. */
  33661. set: function (value) {
  33662. this._midtonesSaturation = value;
  33663. this._dirty = true;
  33664. },
  33665. enumerable: true,
  33666. configurable: true
  33667. });
  33668. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  33669. /**
  33670. * Gets the midtones Exposure value.
  33671. * 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.
  33672. */
  33673. get: function () {
  33674. return this._midtonesExposure;
  33675. },
  33676. /**
  33677. * Sets the midtones Exposure value.
  33678. * 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.
  33679. */
  33680. set: function (value) {
  33681. this._midtonesExposure = value;
  33682. this._dirty = true;
  33683. },
  33684. enumerable: true,
  33685. configurable: true
  33686. });
  33687. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  33688. /**
  33689. * Gets the shadows Hue value.
  33690. * 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).
  33691. */
  33692. get: function () {
  33693. return this._shadowsHue;
  33694. },
  33695. /**
  33696. * Sets the shadows Hue value.
  33697. * 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).
  33698. */
  33699. set: function (value) {
  33700. this._shadowsHue = value;
  33701. this._dirty = true;
  33702. },
  33703. enumerable: true,
  33704. configurable: true
  33705. });
  33706. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  33707. /**
  33708. * Gets the shadows Density value.
  33709. * 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.
  33710. * Values less than zero provide a filter of opposite hue.
  33711. */
  33712. get: function () {
  33713. return this._shadowsDensity;
  33714. },
  33715. /**
  33716. * Sets the shadows Density value.
  33717. * 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.
  33718. * Values less than zero provide a filter of opposite hue.
  33719. */
  33720. set: function (value) {
  33721. this._shadowsDensity = value;
  33722. this._dirty = true;
  33723. },
  33724. enumerable: true,
  33725. configurable: true
  33726. });
  33727. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  33728. /**
  33729. * Gets the shadows Saturation value.
  33730. * 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.
  33731. */
  33732. get: function () {
  33733. return this._shadowsSaturation;
  33734. },
  33735. /**
  33736. * Sets the shadows Saturation value.
  33737. * 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.
  33738. */
  33739. set: function (value) {
  33740. this._shadowsSaturation = value;
  33741. this._dirty = true;
  33742. },
  33743. enumerable: true,
  33744. configurable: true
  33745. });
  33746. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  33747. /**
  33748. * Gets the shadows Exposure value.
  33749. * 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.
  33750. */
  33751. get: function () {
  33752. return this._shadowsExposure;
  33753. },
  33754. /**
  33755. * Sets the shadows Exposure value.
  33756. * 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.
  33757. */
  33758. set: function (value) {
  33759. this._shadowsExposure = value;
  33760. this._dirty = true;
  33761. },
  33762. enumerable: true,
  33763. configurable: true
  33764. });
  33765. ColorCurves.prototype.getClassName = function () {
  33766. return "ColorCurves";
  33767. };
  33768. /**
  33769. * Binds the color curves to the shader.
  33770. * @param colorCurves The color curve to bind
  33771. * @param effect The effect to bind to
  33772. */
  33773. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  33774. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  33775. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  33776. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  33777. if (colorCurves._dirty) {
  33778. colorCurves._dirty = false;
  33779. // Fill in global info.
  33780. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  33781. // Compute highlights info.
  33782. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  33783. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  33784. // Compute midtones info.
  33785. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  33786. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  33787. // Compute shadows info.
  33788. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  33789. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  33790. // Compute deltas (neutral is midtones).
  33791. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  33792. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  33793. }
  33794. if (effect) {
  33795. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  33796. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  33797. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  33798. }
  33799. };
  33800. /**
  33801. * Prepare the list of uniforms associated with the ColorCurves effects.
  33802. * @param uniformsList The list of uniforms used in the effect
  33803. */
  33804. ColorCurves.PrepareUniforms = function (uniformsList) {
  33805. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  33806. };
  33807. /**
  33808. * Returns color grading data based on a hue, density, saturation and exposure value.
  33809. * @param filterHue The hue of the color filter.
  33810. * @param filterDensity The density of the color filter.
  33811. * @param saturation The saturation.
  33812. * @param exposure The exposure.
  33813. * @param result The result data container.
  33814. */
  33815. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  33816. if (hue == null) {
  33817. return;
  33818. }
  33819. hue = ColorCurves.clamp(hue, 0, 360);
  33820. density = ColorCurves.clamp(density, -100, 100);
  33821. saturation = ColorCurves.clamp(saturation, -100, 100);
  33822. exposure = ColorCurves.clamp(exposure, -100, 100);
  33823. // Remap the slider/config filter density with non-linear mapping and also scale by half
  33824. // so that the maximum filter density is only 50% control. This provides fine control
  33825. // for small values and reasonable range.
  33826. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  33827. density *= 0.5;
  33828. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  33829. if (density < 0) {
  33830. density *= -1;
  33831. hue = (hue + 180) % 360;
  33832. }
  33833. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  33834. result.scaleToRef(2, result);
  33835. result.a = 1 + 0.01 * saturation;
  33836. };
  33837. /**
  33838. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  33839. * @param value The input slider value in range [-100,100].
  33840. * @returns Adjusted value.
  33841. */
  33842. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  33843. value /= 100;
  33844. var x = Math.abs(value);
  33845. x = Math.pow(x, 2);
  33846. if (value < 0) {
  33847. x *= -1;
  33848. }
  33849. x *= 100;
  33850. return x;
  33851. };
  33852. /**
  33853. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  33854. * @param hue The hue (H) input.
  33855. * @param saturation The saturation (S) input.
  33856. * @param brightness The brightness (B) input.
  33857. * @result An RGBA color represented as Vector4.
  33858. */
  33859. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  33860. var h = ColorCurves.clamp(hue, 0, 360);
  33861. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  33862. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  33863. if (s === 0) {
  33864. result.r = v;
  33865. result.g = v;
  33866. result.b = v;
  33867. }
  33868. else {
  33869. // sector 0 to 5
  33870. h /= 60;
  33871. var i = Math.floor(h);
  33872. // fractional part of h
  33873. var f = h - i;
  33874. var p = v * (1 - s);
  33875. var q = v * (1 - s * f);
  33876. var t = v * (1 - s * (1 - f));
  33877. switch (i) {
  33878. case 0:
  33879. result.r = v;
  33880. result.g = t;
  33881. result.b = p;
  33882. break;
  33883. case 1:
  33884. result.r = q;
  33885. result.g = v;
  33886. result.b = p;
  33887. break;
  33888. case 2:
  33889. result.r = p;
  33890. result.g = v;
  33891. result.b = t;
  33892. break;
  33893. case 3:
  33894. result.r = p;
  33895. result.g = q;
  33896. result.b = v;
  33897. break;
  33898. case 4:
  33899. result.r = t;
  33900. result.g = p;
  33901. result.b = v;
  33902. break;
  33903. default:// case 5:
  33904. result.r = v;
  33905. result.g = p;
  33906. result.b = q;
  33907. break;
  33908. }
  33909. }
  33910. result.a = 1;
  33911. };
  33912. /**
  33913. * Returns a value clamped between min and max
  33914. * @param value The value to clamp
  33915. * @param min The minimum of value
  33916. * @param max The maximum of value
  33917. * @returns The clamped value.
  33918. */
  33919. ColorCurves.clamp = function (value, min, max) {
  33920. return Math.min(Math.max(value, min), max);
  33921. };
  33922. /**
  33923. * Clones the current color curve instance.
  33924. * @return The cloned curves
  33925. */
  33926. ColorCurves.prototype.clone = function () {
  33927. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  33928. };
  33929. /**
  33930. * Serializes the current color curve instance to a json representation.
  33931. * @return a JSON representation
  33932. */
  33933. ColorCurves.prototype.serialize = function () {
  33934. return BABYLON.SerializationHelper.Serialize(this);
  33935. };
  33936. /**
  33937. * Parses the color curve from a json representation.
  33938. * @param source the JSON source to parse
  33939. * @return The parsed curves
  33940. */
  33941. ColorCurves.Parse = function (source) {
  33942. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  33943. };
  33944. __decorate([
  33945. BABYLON.serialize()
  33946. ], ColorCurves.prototype, "_globalHue", void 0);
  33947. __decorate([
  33948. BABYLON.serialize()
  33949. ], ColorCurves.prototype, "_globalDensity", void 0);
  33950. __decorate([
  33951. BABYLON.serialize()
  33952. ], ColorCurves.prototype, "_globalSaturation", void 0);
  33953. __decorate([
  33954. BABYLON.serialize()
  33955. ], ColorCurves.prototype, "_globalExposure", void 0);
  33956. __decorate([
  33957. BABYLON.serialize()
  33958. ], ColorCurves.prototype, "_highlightsHue", void 0);
  33959. __decorate([
  33960. BABYLON.serialize()
  33961. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  33962. __decorate([
  33963. BABYLON.serialize()
  33964. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  33965. __decorate([
  33966. BABYLON.serialize()
  33967. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  33968. __decorate([
  33969. BABYLON.serialize()
  33970. ], ColorCurves.prototype, "_midtonesHue", void 0);
  33971. __decorate([
  33972. BABYLON.serialize()
  33973. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  33974. __decorate([
  33975. BABYLON.serialize()
  33976. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  33977. __decorate([
  33978. BABYLON.serialize()
  33979. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  33980. return ColorCurves;
  33981. }());
  33982. BABYLON.ColorCurves = ColorCurves;
  33983. })(BABYLON || (BABYLON = {}));
  33984. //# sourceMappingURL=babylon.colorCurves.js.map
  33985. var BABYLON;
  33986. (function (BABYLON) {
  33987. var StandardMaterialDefines = /** @class */ (function (_super) {
  33988. __extends(StandardMaterialDefines, _super);
  33989. function StandardMaterialDefines() {
  33990. var _this = _super.call(this) || this;
  33991. _this.MAINUV1 = false;
  33992. _this.MAINUV2 = false;
  33993. _this.DIFFUSE = false;
  33994. _this.DIFFUSEDIRECTUV = 0;
  33995. _this.AMBIENT = false;
  33996. _this.AMBIENTDIRECTUV = 0;
  33997. _this.OPACITY = false;
  33998. _this.OPACITYDIRECTUV = 0;
  33999. _this.OPACITYRGB = false;
  34000. _this.REFLECTION = false;
  34001. _this.EMISSIVE = false;
  34002. _this.EMISSIVEDIRECTUV = 0;
  34003. _this.SPECULAR = false;
  34004. _this.SPECULARDIRECTUV = 0;
  34005. _this.BUMP = false;
  34006. _this.BUMPDIRECTUV = 0;
  34007. _this.PARALLAX = false;
  34008. _this.PARALLAXOCCLUSION = false;
  34009. _this.SPECULAROVERALPHA = false;
  34010. _this.CLIPPLANE = false;
  34011. _this.ALPHATEST = false;
  34012. _this.DEPTHPREPASS = false;
  34013. _this.ALPHAFROMDIFFUSE = false;
  34014. _this.POINTSIZE = false;
  34015. _this.FOG = false;
  34016. _this.SPECULARTERM = false;
  34017. _this.DIFFUSEFRESNEL = false;
  34018. _this.OPACITYFRESNEL = false;
  34019. _this.REFLECTIONFRESNEL = false;
  34020. _this.REFRACTIONFRESNEL = false;
  34021. _this.EMISSIVEFRESNEL = false;
  34022. _this.FRESNEL = false;
  34023. _this.NORMAL = false;
  34024. _this.UV1 = false;
  34025. _this.UV2 = false;
  34026. _this.VERTEXCOLOR = false;
  34027. _this.VERTEXALPHA = false;
  34028. _this.NUM_BONE_INFLUENCERS = 0;
  34029. _this.BonesPerMesh = 0;
  34030. _this.INSTANCES = false;
  34031. _this.GLOSSINESS = false;
  34032. _this.ROUGHNESS = false;
  34033. _this.EMISSIVEASILLUMINATION = false;
  34034. _this.LINKEMISSIVEWITHDIFFUSE = false;
  34035. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  34036. _this.LIGHTMAP = false;
  34037. _this.LIGHTMAPDIRECTUV = 0;
  34038. _this.USELIGHTMAPASSHADOWMAP = false;
  34039. _this.REFLECTIONMAP_3D = false;
  34040. _this.REFLECTIONMAP_SPHERICAL = false;
  34041. _this.REFLECTIONMAP_PLANAR = false;
  34042. _this.REFLECTIONMAP_CUBIC = false;
  34043. _this.REFLECTIONMAP_PROJECTION = false;
  34044. _this.REFLECTIONMAP_SKYBOX = false;
  34045. _this.REFLECTIONMAP_EXPLICIT = false;
  34046. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  34047. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  34048. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  34049. _this.INVERTCUBICMAP = false;
  34050. _this.LOGARITHMICDEPTH = false;
  34051. _this.REFRACTION = false;
  34052. _this.REFRACTIONMAP_3D = false;
  34053. _this.REFLECTIONOVERALPHA = false;
  34054. _this.TWOSIDEDLIGHTING = false;
  34055. _this.SHADOWFLOAT = false;
  34056. _this.MORPHTARGETS = false;
  34057. _this.MORPHTARGETS_NORMAL = false;
  34058. _this.MORPHTARGETS_TANGENT = false;
  34059. _this.NUM_MORPH_INFLUENCERS = 0;
  34060. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  34061. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  34062. _this.IMAGEPROCESSING = false;
  34063. _this.VIGNETTE = false;
  34064. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  34065. _this.VIGNETTEBLENDMODEOPAQUE = false;
  34066. _this.TONEMAPPING = false;
  34067. _this.CONTRAST = false;
  34068. _this.COLORCURVES = false;
  34069. _this.COLORGRADING = false;
  34070. _this.COLORGRADING3D = false;
  34071. _this.SAMPLER3DGREENDEPTH = false;
  34072. _this.SAMPLER3DBGRMAP = false;
  34073. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  34074. _this.EXPOSURE = false;
  34075. _this.rebuild();
  34076. return _this;
  34077. }
  34078. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  34079. var modes = [
  34080. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  34081. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  34082. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  34083. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  34084. ];
  34085. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  34086. var mode = modes_1[_i];
  34087. this[mode] = (mode === modeToEnable);
  34088. }
  34089. };
  34090. return StandardMaterialDefines;
  34091. }(BABYLON.MaterialDefines));
  34092. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  34093. var StandardMaterial = /** @class */ (function (_super) {
  34094. __extends(StandardMaterial, _super);
  34095. function StandardMaterial(name, scene) {
  34096. var _this = _super.call(this, name, scene) || this;
  34097. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  34098. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  34099. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  34100. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  34101. _this.specularPower = 64;
  34102. _this._useAlphaFromDiffuseTexture = false;
  34103. _this._useEmissiveAsIllumination = false;
  34104. _this._linkEmissiveWithDiffuse = false;
  34105. _this._useSpecularOverAlpha = false;
  34106. _this._useReflectionOverAlpha = false;
  34107. _this._disableLighting = false;
  34108. _this._useParallax = false;
  34109. _this._useParallaxOcclusion = false;
  34110. _this.parallaxScaleBias = 0.05;
  34111. _this._roughness = 0;
  34112. _this.indexOfRefraction = 0.98;
  34113. _this.invertRefractionY = true;
  34114. _this._useLightmapAsShadowmap = false;
  34115. _this._useReflectionFresnelFromSpecular = false;
  34116. _this._useGlossinessFromSpecularMapAlpha = false;
  34117. _this._maxSimultaneousLights = 4;
  34118. /**
  34119. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  34120. */
  34121. _this._invertNormalMapX = false;
  34122. /**
  34123. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  34124. */
  34125. _this._invertNormalMapY = false;
  34126. /**
  34127. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  34128. */
  34129. _this._twoSidedLighting = false;
  34130. _this._renderTargets = new BABYLON.SmartArray(16);
  34131. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  34132. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  34133. // Setup the default processing configuration to the scene.
  34134. _this._attachImageProcessingConfiguration(null);
  34135. _this.getRenderTargetTextures = function () {
  34136. _this._renderTargets.reset();
  34137. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  34138. _this._renderTargets.push(_this._reflectionTexture);
  34139. }
  34140. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  34141. _this._renderTargets.push(_this._refractionTexture);
  34142. }
  34143. return _this._renderTargets;
  34144. };
  34145. return _this;
  34146. }
  34147. ;
  34148. ;
  34149. ;
  34150. ;
  34151. ;
  34152. ;
  34153. ;
  34154. ;
  34155. ;
  34156. ;
  34157. ;
  34158. ;
  34159. ;
  34160. ;
  34161. ;
  34162. ;
  34163. ;
  34164. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  34165. /**
  34166. * Gets the image processing configuration used either in this material.
  34167. */
  34168. get: function () {
  34169. return this._imageProcessingConfiguration;
  34170. },
  34171. /**
  34172. * Sets the Default image processing configuration used either in the this material.
  34173. *
  34174. * If sets to null, the scene one is in use.
  34175. */
  34176. set: function (value) {
  34177. this._attachImageProcessingConfiguration(value);
  34178. // Ensure the effect will be rebuilt.
  34179. this._markAllSubMeshesAsTexturesDirty();
  34180. },
  34181. enumerable: true,
  34182. configurable: true
  34183. });
  34184. /**
  34185. * Attaches a new image processing configuration to the Standard Material.
  34186. * @param configuration
  34187. */
  34188. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  34189. var _this = this;
  34190. if (configuration === this._imageProcessingConfiguration) {
  34191. return;
  34192. }
  34193. // Detaches observer.
  34194. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  34195. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  34196. }
  34197. // Pick the scene configuration if needed.
  34198. if (!configuration) {
  34199. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  34200. }
  34201. else {
  34202. this._imageProcessingConfiguration = configuration;
  34203. }
  34204. // Attaches observer.
  34205. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  34206. _this._markAllSubMeshesAsImageProcessingDirty();
  34207. });
  34208. };
  34209. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  34210. /**
  34211. * Gets wether the color curves effect is enabled.
  34212. */
  34213. get: function () {
  34214. return this.imageProcessingConfiguration.colorCurvesEnabled;
  34215. },
  34216. /**
  34217. * Sets wether the color curves effect is enabled.
  34218. */
  34219. set: function (value) {
  34220. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  34221. },
  34222. enumerable: true,
  34223. configurable: true
  34224. });
  34225. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  34226. /**
  34227. * Gets wether the color grading effect is enabled.
  34228. */
  34229. get: function () {
  34230. return this.imageProcessingConfiguration.colorGradingEnabled;
  34231. },
  34232. /**
  34233. * Gets wether the color grading effect is enabled.
  34234. */
  34235. set: function (value) {
  34236. this.imageProcessingConfiguration.colorGradingEnabled = value;
  34237. },
  34238. enumerable: true,
  34239. configurable: true
  34240. });
  34241. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  34242. /**
  34243. * Gets wether tonemapping is enabled or not.
  34244. */
  34245. get: function () {
  34246. return this._imageProcessingConfiguration.toneMappingEnabled;
  34247. },
  34248. /**
  34249. * Sets wether tonemapping is enabled or not
  34250. */
  34251. set: function (value) {
  34252. this._imageProcessingConfiguration.toneMappingEnabled = value;
  34253. },
  34254. enumerable: true,
  34255. configurable: true
  34256. });
  34257. ;
  34258. ;
  34259. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  34260. /**
  34261. * The camera exposure used on this material.
  34262. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  34263. * This corresponds to a photographic exposure.
  34264. */
  34265. get: function () {
  34266. return this._imageProcessingConfiguration.exposure;
  34267. },
  34268. /**
  34269. * The camera exposure used on this material.
  34270. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  34271. * This corresponds to a photographic exposure.
  34272. */
  34273. set: function (value) {
  34274. this._imageProcessingConfiguration.exposure = value;
  34275. },
  34276. enumerable: true,
  34277. configurable: true
  34278. });
  34279. ;
  34280. ;
  34281. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  34282. /**
  34283. * Gets The camera contrast used on this material.
  34284. */
  34285. get: function () {
  34286. return this._imageProcessingConfiguration.contrast;
  34287. },
  34288. /**
  34289. * Sets The camera contrast used on this material.
  34290. */
  34291. set: function (value) {
  34292. this._imageProcessingConfiguration.contrast = value;
  34293. },
  34294. enumerable: true,
  34295. configurable: true
  34296. });
  34297. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  34298. /**
  34299. * Gets the Color Grading 2D Lookup Texture.
  34300. */
  34301. get: function () {
  34302. return this._imageProcessingConfiguration.colorGradingTexture;
  34303. },
  34304. /**
  34305. * Sets the Color Grading 2D Lookup Texture.
  34306. */
  34307. set: function (value) {
  34308. this._imageProcessingConfiguration.colorGradingTexture = value;
  34309. },
  34310. enumerable: true,
  34311. configurable: true
  34312. });
  34313. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  34314. /**
  34315. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  34316. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  34317. * 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;
  34318. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  34319. */
  34320. get: function () {
  34321. return this._imageProcessingConfiguration.colorCurves;
  34322. },
  34323. /**
  34324. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  34325. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  34326. * 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;
  34327. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  34328. */
  34329. set: function (value) {
  34330. this._imageProcessingConfiguration.colorCurves = value;
  34331. },
  34332. enumerable: true,
  34333. configurable: true
  34334. });
  34335. StandardMaterial.prototype.getClassName = function () {
  34336. return "StandardMaterial";
  34337. };
  34338. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  34339. get: function () {
  34340. return this._useLogarithmicDepth;
  34341. },
  34342. set: function (value) {
  34343. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  34344. this._markAllSubMeshesAsMiscDirty();
  34345. },
  34346. enumerable: true,
  34347. configurable: true
  34348. });
  34349. StandardMaterial.prototype.needAlphaBlending = function () {
  34350. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  34351. };
  34352. StandardMaterial.prototype.needAlphaTesting = function () {
  34353. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  34354. };
  34355. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  34356. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  34357. };
  34358. StandardMaterial.prototype.getAlphaTestTexture = function () {
  34359. return this._diffuseTexture;
  34360. };
  34361. /**
  34362. * Child classes can use it to update shaders
  34363. */
  34364. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34365. if (useInstances === void 0) { useInstances = false; }
  34366. if (subMesh.effect && this.isFrozen) {
  34367. if (this._wasPreviouslyReady && subMesh.effect) {
  34368. return true;
  34369. }
  34370. }
  34371. if (!subMesh._materialDefines) {
  34372. subMesh._materialDefines = new StandardMaterialDefines();
  34373. }
  34374. var scene = this.getScene();
  34375. var defines = subMesh._materialDefines;
  34376. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  34377. if (defines._renderId === scene.getRenderId()) {
  34378. return true;
  34379. }
  34380. }
  34381. var engine = scene.getEngine();
  34382. // Lights
  34383. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  34384. // Textures
  34385. if (defines._areTexturesDirty) {
  34386. defines._needUVs = false;
  34387. defines.MAINUV1 = false;
  34388. defines.MAINUV2 = false;
  34389. if (scene.texturesEnabled) {
  34390. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  34391. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  34392. return false;
  34393. }
  34394. else {
  34395. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  34396. }
  34397. }
  34398. else {
  34399. defines.DIFFUSE = false;
  34400. }
  34401. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  34402. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  34403. return false;
  34404. }
  34405. else {
  34406. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  34407. }
  34408. }
  34409. else {
  34410. defines.AMBIENT = false;
  34411. }
  34412. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  34413. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  34414. return false;
  34415. }
  34416. else {
  34417. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  34418. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  34419. }
  34420. }
  34421. else {
  34422. defines.OPACITY = false;
  34423. }
  34424. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  34425. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  34426. return false;
  34427. }
  34428. else {
  34429. defines._needNormals = true;
  34430. defines.REFLECTION = true;
  34431. defines.ROUGHNESS = (this._roughness > 0);
  34432. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  34433. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  34434. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  34435. switch (this._reflectionTexture.coordinatesMode) {
  34436. case BABYLON.Texture.CUBIC_MODE:
  34437. case BABYLON.Texture.INVCUBIC_MODE:
  34438. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  34439. break;
  34440. case BABYLON.Texture.EXPLICIT_MODE:
  34441. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  34442. break;
  34443. case BABYLON.Texture.PLANAR_MODE:
  34444. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  34445. break;
  34446. case BABYLON.Texture.PROJECTION_MODE:
  34447. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  34448. break;
  34449. case BABYLON.Texture.SKYBOX_MODE:
  34450. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  34451. break;
  34452. case BABYLON.Texture.SPHERICAL_MODE:
  34453. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  34454. break;
  34455. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  34456. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  34457. break;
  34458. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  34459. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  34460. break;
  34461. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  34462. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  34463. break;
  34464. }
  34465. }
  34466. }
  34467. else {
  34468. defines.REFLECTION = false;
  34469. }
  34470. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  34471. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  34472. return false;
  34473. }
  34474. else {
  34475. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  34476. }
  34477. }
  34478. else {
  34479. defines.EMISSIVE = false;
  34480. }
  34481. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  34482. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  34483. return false;
  34484. }
  34485. else {
  34486. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  34487. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  34488. }
  34489. }
  34490. else {
  34491. defines.LIGHTMAP = false;
  34492. }
  34493. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  34494. if (!this._specularTexture.isReadyOrNotBlocking()) {
  34495. return false;
  34496. }
  34497. else {
  34498. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  34499. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  34500. }
  34501. }
  34502. else {
  34503. defines.SPECULAR = false;
  34504. }
  34505. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  34506. // Bump texure can not be not blocking.
  34507. if (!this._bumpTexture.isReady()) {
  34508. return false;
  34509. }
  34510. else {
  34511. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  34512. defines.PARALLAX = this._useParallax;
  34513. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  34514. }
  34515. }
  34516. else {
  34517. defines.BUMP = false;
  34518. }
  34519. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  34520. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  34521. return false;
  34522. }
  34523. else {
  34524. defines._needUVs = true;
  34525. defines.REFRACTION = true;
  34526. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  34527. }
  34528. }
  34529. else {
  34530. defines.REFRACTION = false;
  34531. }
  34532. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  34533. }
  34534. else {
  34535. defines.DIFFUSE = false;
  34536. defines.AMBIENT = false;
  34537. defines.OPACITY = false;
  34538. defines.REFLECTION = false;
  34539. defines.EMISSIVE = false;
  34540. defines.LIGHTMAP = false;
  34541. defines.BUMP = false;
  34542. defines.REFRACTION = false;
  34543. }
  34544. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  34545. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  34546. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  34547. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  34548. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  34549. }
  34550. if (defines._areImageProcessingDirty) {
  34551. if (!this._imageProcessingConfiguration.isReady()) {
  34552. return false;
  34553. }
  34554. this._imageProcessingConfiguration.prepareDefines(defines);
  34555. }
  34556. if (defines._areFresnelDirty) {
  34557. if (StandardMaterial.FresnelEnabled) {
  34558. // Fresnel
  34559. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  34560. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  34561. this._reflectionFresnelParameters) {
  34562. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  34563. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  34564. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  34565. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  34566. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  34567. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  34568. defines._needNormals = true;
  34569. defines.FRESNEL = true;
  34570. }
  34571. }
  34572. else {
  34573. defines.FRESNEL = false;
  34574. }
  34575. }
  34576. // Misc.
  34577. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  34578. // Attribs
  34579. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  34580. // Values that need to be evaluated on every frame
  34581. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  34582. // Get correct effect
  34583. if (defines.isDirty) {
  34584. defines.markAsProcessed();
  34585. scene.resetCachedMaterial();
  34586. // Fallbacks
  34587. var fallbacks = new BABYLON.EffectFallbacks();
  34588. if (defines.REFLECTION) {
  34589. fallbacks.addFallback(0, "REFLECTION");
  34590. }
  34591. if (defines.SPECULAR) {
  34592. fallbacks.addFallback(0, "SPECULAR");
  34593. }
  34594. if (defines.BUMP) {
  34595. fallbacks.addFallback(0, "BUMP");
  34596. }
  34597. if (defines.PARALLAX) {
  34598. fallbacks.addFallback(1, "PARALLAX");
  34599. }
  34600. if (defines.PARALLAXOCCLUSION) {
  34601. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  34602. }
  34603. if (defines.SPECULAROVERALPHA) {
  34604. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  34605. }
  34606. if (defines.FOG) {
  34607. fallbacks.addFallback(1, "FOG");
  34608. }
  34609. if (defines.POINTSIZE) {
  34610. fallbacks.addFallback(0, "POINTSIZE");
  34611. }
  34612. if (defines.LOGARITHMICDEPTH) {
  34613. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  34614. }
  34615. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  34616. if (defines.SPECULARTERM) {
  34617. fallbacks.addFallback(0, "SPECULARTERM");
  34618. }
  34619. if (defines.DIFFUSEFRESNEL) {
  34620. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  34621. }
  34622. if (defines.OPACITYFRESNEL) {
  34623. fallbacks.addFallback(2, "OPACITYFRESNEL");
  34624. }
  34625. if (defines.REFLECTIONFRESNEL) {
  34626. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  34627. }
  34628. if (defines.EMISSIVEFRESNEL) {
  34629. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  34630. }
  34631. if (defines.FRESNEL) {
  34632. fallbacks.addFallback(4, "FRESNEL");
  34633. }
  34634. //Attributes
  34635. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34636. if (defines.NORMAL) {
  34637. attribs.push(BABYLON.VertexBuffer.NormalKind);
  34638. }
  34639. if (defines.UV1) {
  34640. attribs.push(BABYLON.VertexBuffer.UVKind);
  34641. }
  34642. if (defines.UV2) {
  34643. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34644. }
  34645. if (defines.VERTEXCOLOR) {
  34646. attribs.push(BABYLON.VertexBuffer.ColorKind);
  34647. }
  34648. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  34649. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  34650. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  34651. var shaderName = "default";
  34652. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  34653. "vFogInfos", "vFogColor", "pointSize",
  34654. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  34655. "mBones",
  34656. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  34657. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  34658. "logarithmicDepthConstant", "vTangentSpaceParams"
  34659. ];
  34660. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  34661. var uniformBuffers = ["Material", "Scene"];
  34662. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  34663. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  34664. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  34665. uniformsNames: uniforms,
  34666. uniformBuffersNames: uniformBuffers,
  34667. samplers: samplers,
  34668. defines: defines,
  34669. maxSimultaneousLights: this._maxSimultaneousLights
  34670. });
  34671. if (this.customShaderNameResolve) {
  34672. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  34673. }
  34674. var join = defines.toString();
  34675. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  34676. attributes: attribs,
  34677. uniformsNames: uniforms,
  34678. uniformBuffersNames: uniformBuffers,
  34679. samplers: samplers,
  34680. defines: join,
  34681. fallbacks: fallbacks,
  34682. onCompiled: this.onCompiled,
  34683. onError: this.onError,
  34684. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  34685. }, engine), defines);
  34686. this.buildUniformLayout();
  34687. }
  34688. if (!subMesh.effect || !subMesh.effect.isReady()) {
  34689. return false;
  34690. }
  34691. defines._renderId = scene.getRenderId();
  34692. this._wasPreviouslyReady = true;
  34693. return true;
  34694. };
  34695. StandardMaterial.prototype.buildUniformLayout = function () {
  34696. // Order is important !
  34697. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  34698. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  34699. this._uniformBuffer.addUniform("opacityParts", 4);
  34700. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  34701. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  34702. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  34703. this._uniformBuffer.addUniform("refractionRightColor", 4);
  34704. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  34705. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  34706. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  34707. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  34708. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  34709. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  34710. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  34711. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  34712. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  34713. this._uniformBuffer.addUniform("vBumpInfos", 3);
  34714. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  34715. this._uniformBuffer.addUniform("ambientMatrix", 16);
  34716. this._uniformBuffer.addUniform("opacityMatrix", 16);
  34717. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  34718. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  34719. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  34720. this._uniformBuffer.addUniform("specularMatrix", 16);
  34721. this._uniformBuffer.addUniform("bumpMatrix", 16);
  34722. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  34723. this._uniformBuffer.addUniform("refractionMatrix", 16);
  34724. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  34725. this._uniformBuffer.addUniform("vSpecularColor", 4);
  34726. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  34727. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  34728. this._uniformBuffer.addUniform("pointSize", 1);
  34729. this._uniformBuffer.create();
  34730. };
  34731. StandardMaterial.prototype.unbind = function () {
  34732. if (this._activeEffect) {
  34733. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  34734. this._activeEffect.setTexture("reflection2DSampler", null);
  34735. }
  34736. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  34737. this._activeEffect.setTexture("refraction2DSampler", null);
  34738. }
  34739. }
  34740. _super.prototype.unbind.call(this);
  34741. };
  34742. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  34743. var scene = this.getScene();
  34744. var defines = subMesh._materialDefines;
  34745. if (!defines) {
  34746. return;
  34747. }
  34748. var effect = subMesh.effect;
  34749. if (!effect) {
  34750. return;
  34751. }
  34752. this._activeEffect = effect;
  34753. // Matrices
  34754. this.bindOnlyWorldMatrix(world);
  34755. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  34756. // Bones
  34757. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  34758. if (mustRebind) {
  34759. this._uniformBuffer.bindToEffect(effect, "Material");
  34760. this.bindViewProjection(effect);
  34761. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  34762. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  34763. // Fresnel
  34764. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  34765. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  34766. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  34767. }
  34768. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  34769. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  34770. }
  34771. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  34772. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  34773. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  34774. }
  34775. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  34776. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  34777. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  34778. }
  34779. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  34780. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  34781. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  34782. }
  34783. }
  34784. // Textures
  34785. if (scene.texturesEnabled) {
  34786. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  34787. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  34788. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  34789. }
  34790. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  34791. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  34792. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  34793. }
  34794. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  34795. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  34796. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  34797. }
  34798. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  34799. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  34800. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  34801. }
  34802. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  34803. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  34804. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  34805. }
  34806. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  34807. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  34808. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  34809. }
  34810. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  34811. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  34812. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  34813. }
  34814. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  34815. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  34816. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  34817. if (scene._mirroredCameraPosition) {
  34818. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  34819. }
  34820. else {
  34821. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  34822. }
  34823. }
  34824. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  34825. var depth = 1.0;
  34826. if (!this._refractionTexture.isCube) {
  34827. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  34828. if (this._refractionTexture.depth) {
  34829. depth = this._refractionTexture.depth;
  34830. }
  34831. }
  34832. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  34833. }
  34834. }
  34835. // Point size
  34836. if (this.pointsCloud) {
  34837. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  34838. }
  34839. if (defines.SPECULARTERM) {
  34840. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  34841. }
  34842. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  34843. // Diffuse
  34844. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  34845. }
  34846. // Textures
  34847. if (scene.texturesEnabled) {
  34848. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  34849. effect.setTexture("diffuseSampler", this._diffuseTexture);
  34850. }
  34851. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  34852. effect.setTexture("ambientSampler", this._ambientTexture);
  34853. }
  34854. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  34855. effect.setTexture("opacitySampler", this._opacityTexture);
  34856. }
  34857. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  34858. if (this._reflectionTexture.isCube) {
  34859. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  34860. }
  34861. else {
  34862. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  34863. }
  34864. }
  34865. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  34866. effect.setTexture("emissiveSampler", this._emissiveTexture);
  34867. }
  34868. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  34869. effect.setTexture("lightmapSampler", this._lightmapTexture);
  34870. }
  34871. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  34872. effect.setTexture("specularSampler", this._specularTexture);
  34873. }
  34874. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  34875. effect.setTexture("bumpSampler", this._bumpTexture);
  34876. }
  34877. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  34878. var depth = 1.0;
  34879. if (this._refractionTexture.isCube) {
  34880. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  34881. }
  34882. else {
  34883. effect.setTexture("refraction2DSampler", this._refractionTexture);
  34884. }
  34885. }
  34886. }
  34887. // Clip plane
  34888. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  34889. // Colors
  34890. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  34891. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  34892. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  34893. }
  34894. if (mustRebind || !this.isFrozen) {
  34895. // Lights
  34896. if (scene.lightsEnabled && !this._disableLighting) {
  34897. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  34898. }
  34899. // View
  34900. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  34901. this.bindView(effect);
  34902. }
  34903. // Fog
  34904. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  34905. // Morph targets
  34906. if (defines.NUM_MORPH_INFLUENCERS) {
  34907. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  34908. }
  34909. // Log. depth
  34910. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  34911. // image processing
  34912. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  34913. this._imageProcessingConfiguration.bind(this._activeEffect);
  34914. }
  34915. }
  34916. this._uniformBuffer.update();
  34917. this._afterBind(mesh, this._activeEffect);
  34918. };
  34919. StandardMaterial.prototype.getAnimatables = function () {
  34920. var results = [];
  34921. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  34922. results.push(this._diffuseTexture);
  34923. }
  34924. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  34925. results.push(this._ambientTexture);
  34926. }
  34927. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  34928. results.push(this._opacityTexture);
  34929. }
  34930. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  34931. results.push(this._reflectionTexture);
  34932. }
  34933. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  34934. results.push(this._emissiveTexture);
  34935. }
  34936. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  34937. results.push(this._specularTexture);
  34938. }
  34939. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  34940. results.push(this._bumpTexture);
  34941. }
  34942. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  34943. results.push(this._lightmapTexture);
  34944. }
  34945. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  34946. results.push(this._refractionTexture);
  34947. }
  34948. return results;
  34949. };
  34950. StandardMaterial.prototype.getActiveTextures = function () {
  34951. var activeTextures = _super.prototype.getActiveTextures.call(this);
  34952. if (this._diffuseTexture) {
  34953. activeTextures.push(this._diffuseTexture);
  34954. }
  34955. if (this._ambientTexture) {
  34956. activeTextures.push(this._ambientTexture);
  34957. }
  34958. if (this._opacityTexture) {
  34959. activeTextures.push(this._opacityTexture);
  34960. }
  34961. if (this._reflectionTexture) {
  34962. activeTextures.push(this._reflectionTexture);
  34963. }
  34964. if (this._emissiveTexture) {
  34965. activeTextures.push(this._emissiveTexture);
  34966. }
  34967. if (this._specularTexture) {
  34968. activeTextures.push(this._specularTexture);
  34969. }
  34970. if (this._bumpTexture) {
  34971. activeTextures.push(this._bumpTexture);
  34972. }
  34973. if (this._lightmapTexture) {
  34974. activeTextures.push(this._lightmapTexture);
  34975. }
  34976. if (this._refractionTexture) {
  34977. activeTextures.push(this._refractionTexture);
  34978. }
  34979. return activeTextures;
  34980. };
  34981. StandardMaterial.prototype.hasTexture = function (texture) {
  34982. if (_super.prototype.hasTexture.call(this, texture)) {
  34983. return true;
  34984. }
  34985. if (this._diffuseTexture === texture) {
  34986. return true;
  34987. }
  34988. if (this._ambientTexture === texture) {
  34989. return true;
  34990. }
  34991. if (this._opacityTexture === texture) {
  34992. return true;
  34993. }
  34994. if (this._reflectionTexture === texture) {
  34995. return true;
  34996. }
  34997. if (this._emissiveTexture === texture) {
  34998. return true;
  34999. }
  35000. if (this._specularTexture === texture) {
  35001. return true;
  35002. }
  35003. if (this._bumpTexture === texture) {
  35004. return true;
  35005. }
  35006. if (this._lightmapTexture === texture) {
  35007. return true;
  35008. }
  35009. if (this._refractionTexture === texture) {
  35010. return true;
  35011. }
  35012. return false;
  35013. };
  35014. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35015. if (forceDisposeTextures) {
  35016. if (this._diffuseTexture) {
  35017. this._diffuseTexture.dispose();
  35018. }
  35019. if (this._ambientTexture) {
  35020. this._ambientTexture.dispose();
  35021. }
  35022. if (this._opacityTexture) {
  35023. this._opacityTexture.dispose();
  35024. }
  35025. if (this._reflectionTexture) {
  35026. this._reflectionTexture.dispose();
  35027. }
  35028. if (this._emissiveTexture) {
  35029. this._emissiveTexture.dispose();
  35030. }
  35031. if (this._specularTexture) {
  35032. this._specularTexture.dispose();
  35033. }
  35034. if (this._bumpTexture) {
  35035. this._bumpTexture.dispose();
  35036. }
  35037. if (this._lightmapTexture) {
  35038. this._lightmapTexture.dispose();
  35039. }
  35040. if (this._refractionTexture) {
  35041. this._refractionTexture.dispose();
  35042. }
  35043. }
  35044. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35045. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35046. }
  35047. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  35048. };
  35049. StandardMaterial.prototype.clone = function (name) {
  35050. var _this = this;
  35051. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  35052. result.name = name;
  35053. result.id = name;
  35054. return result;
  35055. };
  35056. StandardMaterial.prototype.serialize = function () {
  35057. return BABYLON.SerializationHelper.Serialize(this);
  35058. };
  35059. // Statics
  35060. StandardMaterial.Parse = function (source, scene, rootUrl) {
  35061. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  35062. };
  35063. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  35064. get: function () {
  35065. return StandardMaterial._DiffuseTextureEnabled;
  35066. },
  35067. set: function (value) {
  35068. if (StandardMaterial._DiffuseTextureEnabled === value) {
  35069. return;
  35070. }
  35071. StandardMaterial._DiffuseTextureEnabled = value;
  35072. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35073. },
  35074. enumerable: true,
  35075. configurable: true
  35076. });
  35077. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  35078. get: function () {
  35079. return StandardMaterial._AmbientTextureEnabled;
  35080. },
  35081. set: function (value) {
  35082. if (StandardMaterial._AmbientTextureEnabled === value) {
  35083. return;
  35084. }
  35085. StandardMaterial._AmbientTextureEnabled = value;
  35086. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35087. },
  35088. enumerable: true,
  35089. configurable: true
  35090. });
  35091. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  35092. get: function () {
  35093. return StandardMaterial._OpacityTextureEnabled;
  35094. },
  35095. set: function (value) {
  35096. if (StandardMaterial._OpacityTextureEnabled === value) {
  35097. return;
  35098. }
  35099. StandardMaterial._OpacityTextureEnabled = value;
  35100. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35101. },
  35102. enumerable: true,
  35103. configurable: true
  35104. });
  35105. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  35106. get: function () {
  35107. return StandardMaterial._ReflectionTextureEnabled;
  35108. },
  35109. set: function (value) {
  35110. if (StandardMaterial._ReflectionTextureEnabled === value) {
  35111. return;
  35112. }
  35113. StandardMaterial._ReflectionTextureEnabled = value;
  35114. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35115. },
  35116. enumerable: true,
  35117. configurable: true
  35118. });
  35119. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  35120. get: function () {
  35121. return StandardMaterial._EmissiveTextureEnabled;
  35122. },
  35123. set: function (value) {
  35124. if (StandardMaterial._EmissiveTextureEnabled === value) {
  35125. return;
  35126. }
  35127. StandardMaterial._EmissiveTextureEnabled = value;
  35128. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35129. },
  35130. enumerable: true,
  35131. configurable: true
  35132. });
  35133. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  35134. get: function () {
  35135. return StandardMaterial._SpecularTextureEnabled;
  35136. },
  35137. set: function (value) {
  35138. if (StandardMaterial._SpecularTextureEnabled === value) {
  35139. return;
  35140. }
  35141. StandardMaterial._SpecularTextureEnabled = value;
  35142. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35143. },
  35144. enumerable: true,
  35145. configurable: true
  35146. });
  35147. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  35148. get: function () {
  35149. return StandardMaterial._BumpTextureEnabled;
  35150. },
  35151. set: function (value) {
  35152. if (StandardMaterial._BumpTextureEnabled === value) {
  35153. return;
  35154. }
  35155. StandardMaterial._BumpTextureEnabled = value;
  35156. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35157. },
  35158. enumerable: true,
  35159. configurable: true
  35160. });
  35161. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  35162. get: function () {
  35163. return StandardMaterial._LightmapTextureEnabled;
  35164. },
  35165. set: function (value) {
  35166. if (StandardMaterial._LightmapTextureEnabled === value) {
  35167. return;
  35168. }
  35169. StandardMaterial._LightmapTextureEnabled = value;
  35170. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35171. },
  35172. enumerable: true,
  35173. configurable: true
  35174. });
  35175. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  35176. get: function () {
  35177. return StandardMaterial._RefractionTextureEnabled;
  35178. },
  35179. set: function (value) {
  35180. if (StandardMaterial._RefractionTextureEnabled === value) {
  35181. return;
  35182. }
  35183. StandardMaterial._RefractionTextureEnabled = value;
  35184. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35185. },
  35186. enumerable: true,
  35187. configurable: true
  35188. });
  35189. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  35190. get: function () {
  35191. return StandardMaterial._ColorGradingTextureEnabled;
  35192. },
  35193. set: function (value) {
  35194. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  35195. return;
  35196. }
  35197. StandardMaterial._ColorGradingTextureEnabled = value;
  35198. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35199. },
  35200. enumerable: true,
  35201. configurable: true
  35202. });
  35203. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  35204. get: function () {
  35205. return StandardMaterial._FresnelEnabled;
  35206. },
  35207. set: function (value) {
  35208. if (StandardMaterial._FresnelEnabled === value) {
  35209. return;
  35210. }
  35211. StandardMaterial._FresnelEnabled = value;
  35212. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  35213. },
  35214. enumerable: true,
  35215. configurable: true
  35216. });
  35217. // Flags used to enable or disable a type of texture for all Standard Materials
  35218. StandardMaterial._DiffuseTextureEnabled = true;
  35219. StandardMaterial._AmbientTextureEnabled = true;
  35220. StandardMaterial._OpacityTextureEnabled = true;
  35221. StandardMaterial._ReflectionTextureEnabled = true;
  35222. StandardMaterial._EmissiveTextureEnabled = true;
  35223. StandardMaterial._SpecularTextureEnabled = true;
  35224. StandardMaterial._BumpTextureEnabled = true;
  35225. StandardMaterial._LightmapTextureEnabled = true;
  35226. StandardMaterial._RefractionTextureEnabled = true;
  35227. StandardMaterial._ColorGradingTextureEnabled = true;
  35228. StandardMaterial._FresnelEnabled = true;
  35229. __decorate([
  35230. BABYLON.serializeAsTexture("diffuseTexture")
  35231. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  35232. __decorate([
  35233. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35234. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  35235. __decorate([
  35236. BABYLON.serializeAsTexture("ambientTexture")
  35237. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  35238. __decorate([
  35239. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35240. ], StandardMaterial.prototype, "ambientTexture", void 0);
  35241. __decorate([
  35242. BABYLON.serializeAsTexture("opacityTexture")
  35243. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  35244. __decorate([
  35245. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35246. ], StandardMaterial.prototype, "opacityTexture", void 0);
  35247. __decorate([
  35248. BABYLON.serializeAsTexture("reflectionTexture")
  35249. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  35250. __decorate([
  35251. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35252. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  35253. __decorate([
  35254. BABYLON.serializeAsTexture("emissiveTexture")
  35255. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  35256. __decorate([
  35257. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35258. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  35259. __decorate([
  35260. BABYLON.serializeAsTexture("specularTexture")
  35261. ], StandardMaterial.prototype, "_specularTexture", void 0);
  35262. __decorate([
  35263. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35264. ], StandardMaterial.prototype, "specularTexture", void 0);
  35265. __decorate([
  35266. BABYLON.serializeAsTexture("bumpTexture")
  35267. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  35268. __decorate([
  35269. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35270. ], StandardMaterial.prototype, "bumpTexture", void 0);
  35271. __decorate([
  35272. BABYLON.serializeAsTexture("lightmapTexture")
  35273. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  35274. __decorate([
  35275. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35276. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  35277. __decorate([
  35278. BABYLON.serializeAsTexture("refractionTexture")
  35279. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  35280. __decorate([
  35281. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35282. ], StandardMaterial.prototype, "refractionTexture", void 0);
  35283. __decorate([
  35284. BABYLON.serializeAsColor3("ambient")
  35285. ], StandardMaterial.prototype, "ambientColor", void 0);
  35286. __decorate([
  35287. BABYLON.serializeAsColor3("diffuse")
  35288. ], StandardMaterial.prototype, "diffuseColor", void 0);
  35289. __decorate([
  35290. BABYLON.serializeAsColor3("specular")
  35291. ], StandardMaterial.prototype, "specularColor", void 0);
  35292. __decorate([
  35293. BABYLON.serializeAsColor3("emissive")
  35294. ], StandardMaterial.prototype, "emissiveColor", void 0);
  35295. __decorate([
  35296. BABYLON.serialize()
  35297. ], StandardMaterial.prototype, "specularPower", void 0);
  35298. __decorate([
  35299. BABYLON.serialize("useAlphaFromDiffuseTexture")
  35300. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  35301. __decorate([
  35302. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35303. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  35304. __decorate([
  35305. BABYLON.serialize("useEmissiveAsIllumination")
  35306. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  35307. __decorate([
  35308. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35309. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  35310. __decorate([
  35311. BABYLON.serialize("linkEmissiveWithDiffuse")
  35312. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  35313. __decorate([
  35314. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35315. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  35316. __decorate([
  35317. BABYLON.serialize("useSpecularOverAlpha")
  35318. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  35319. __decorate([
  35320. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35321. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  35322. __decorate([
  35323. BABYLON.serialize("useReflectionOverAlpha")
  35324. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  35325. __decorate([
  35326. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35327. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  35328. __decorate([
  35329. BABYLON.serialize("disableLighting")
  35330. ], StandardMaterial.prototype, "_disableLighting", void 0);
  35331. __decorate([
  35332. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35333. ], StandardMaterial.prototype, "disableLighting", void 0);
  35334. __decorate([
  35335. BABYLON.serialize("useParallax")
  35336. ], StandardMaterial.prototype, "_useParallax", void 0);
  35337. __decorate([
  35338. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35339. ], StandardMaterial.prototype, "useParallax", void 0);
  35340. __decorate([
  35341. BABYLON.serialize("useParallaxOcclusion")
  35342. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  35343. __decorate([
  35344. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35345. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  35346. __decorate([
  35347. BABYLON.serialize()
  35348. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  35349. __decorate([
  35350. BABYLON.serialize("roughness")
  35351. ], StandardMaterial.prototype, "_roughness", void 0);
  35352. __decorate([
  35353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35354. ], StandardMaterial.prototype, "roughness", void 0);
  35355. __decorate([
  35356. BABYLON.serialize()
  35357. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  35358. __decorate([
  35359. BABYLON.serialize()
  35360. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  35361. __decorate([
  35362. BABYLON.serialize("useLightmapAsShadowmap")
  35363. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  35364. __decorate([
  35365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35366. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  35367. __decorate([
  35368. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  35369. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  35370. __decorate([
  35371. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35372. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  35373. __decorate([
  35374. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  35375. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  35376. __decorate([
  35377. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35378. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  35379. __decorate([
  35380. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  35381. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  35382. __decorate([
  35383. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35384. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  35385. __decorate([
  35386. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  35387. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  35388. __decorate([
  35389. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35390. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  35391. __decorate([
  35392. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  35393. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  35394. __decorate([
  35395. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35396. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  35397. __decorate([
  35398. BABYLON.serialize("useReflectionFresnelFromSpecular")
  35399. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  35400. __decorate([
  35401. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35402. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  35403. __decorate([
  35404. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  35405. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  35406. __decorate([
  35407. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35408. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  35409. __decorate([
  35410. BABYLON.serialize("maxSimultaneousLights")
  35411. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  35412. __decorate([
  35413. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35414. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  35415. __decorate([
  35416. BABYLON.serialize("invertNormalMapX")
  35417. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  35418. __decorate([
  35419. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35420. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  35421. __decorate([
  35422. BABYLON.serialize("invertNormalMapY")
  35423. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  35424. __decorate([
  35425. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35426. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  35427. __decorate([
  35428. BABYLON.serialize("twoSidedLighting")
  35429. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  35430. __decorate([
  35431. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35432. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  35433. __decorate([
  35434. BABYLON.serialize()
  35435. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  35436. return StandardMaterial;
  35437. }(BABYLON.PushMaterial));
  35438. BABYLON.StandardMaterial = StandardMaterial;
  35439. })(BABYLON || (BABYLON = {}));
  35440. //# sourceMappingURL=babylon.standardMaterial.js.map
  35441. var BABYLON;
  35442. (function (BABYLON) {
  35443. var PBRMaterialDefines = /** @class */ (function (_super) {
  35444. __extends(PBRMaterialDefines, _super);
  35445. function PBRMaterialDefines() {
  35446. var _this = _super.call(this) || this;
  35447. _this.PBR = true;
  35448. _this.MAINUV1 = false;
  35449. _this.MAINUV2 = false;
  35450. _this.UV1 = false;
  35451. _this.UV2 = false;
  35452. _this.ALBEDO = false;
  35453. _this.ALBEDODIRECTUV = 0;
  35454. _this.VERTEXCOLOR = false;
  35455. _this.AMBIENT = false;
  35456. _this.AMBIENTDIRECTUV = 0;
  35457. _this.AMBIENTINGRAYSCALE = false;
  35458. _this.OPACITY = false;
  35459. _this.VERTEXALPHA = false;
  35460. _this.OPACITYDIRECTUV = 0;
  35461. _this.OPACITYRGB = false;
  35462. _this.ALPHATEST = false;
  35463. _this.DEPTHPREPASS = false;
  35464. _this.ALPHABLEND = false;
  35465. _this.ALPHAFROMALBEDO = false;
  35466. _this.ALPHATESTVALUE = 0.5;
  35467. _this.SPECULAROVERALPHA = false;
  35468. _this.RADIANCEOVERALPHA = false;
  35469. _this.ALPHAFRESNEL = false;
  35470. _this.LINEARALPHAFRESNEL = false;
  35471. _this.PREMULTIPLYALPHA = false;
  35472. _this.EMISSIVE = false;
  35473. _this.EMISSIVEDIRECTUV = 0;
  35474. _this.REFLECTIVITY = false;
  35475. _this.REFLECTIVITYDIRECTUV = 0;
  35476. _this.SPECULARTERM = false;
  35477. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  35478. _this.MICROSURFACEAUTOMATIC = false;
  35479. _this.LODBASEDMICROSFURACE = false;
  35480. _this.MICROSURFACEMAP = false;
  35481. _this.MICROSURFACEMAPDIRECTUV = 0;
  35482. _this.METALLICWORKFLOW = false;
  35483. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  35484. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  35485. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  35486. _this.AOSTOREINMETALMAPRED = false;
  35487. _this.ENVIRONMENTBRDF = false;
  35488. _this.NORMAL = false;
  35489. _this.TANGENT = false;
  35490. _this.BUMP = false;
  35491. _this.BUMPDIRECTUV = 0;
  35492. _this.PARALLAX = false;
  35493. _this.PARALLAXOCCLUSION = false;
  35494. _this.NORMALXYSCALE = true;
  35495. _this.LIGHTMAP = false;
  35496. _this.LIGHTMAPDIRECTUV = 0;
  35497. _this.USELIGHTMAPASSHADOWMAP = false;
  35498. _this.REFLECTION = false;
  35499. _this.REFLECTIONMAP_3D = false;
  35500. _this.REFLECTIONMAP_SPHERICAL = false;
  35501. _this.REFLECTIONMAP_PLANAR = false;
  35502. _this.REFLECTIONMAP_CUBIC = false;
  35503. _this.REFLECTIONMAP_PROJECTION = false;
  35504. _this.REFLECTIONMAP_SKYBOX = false;
  35505. _this.REFLECTIONMAP_EXPLICIT = false;
  35506. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  35507. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  35508. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  35509. _this.INVERTCUBICMAP = false;
  35510. _this.USESPHERICALFROMREFLECTIONMAP = false;
  35511. _this.USESPHERICALINVERTEX = false;
  35512. _this.REFLECTIONMAP_OPPOSITEZ = false;
  35513. _this.LODINREFLECTIONALPHA = false;
  35514. _this.GAMMAREFLECTION = false;
  35515. _this.RADIANCEOCCLUSION = false;
  35516. _this.HORIZONOCCLUSION = false;
  35517. _this.REFRACTION = false;
  35518. _this.REFRACTIONMAP_3D = false;
  35519. _this.REFRACTIONMAP_OPPOSITEZ = false;
  35520. _this.LODINREFRACTIONALPHA = false;
  35521. _this.GAMMAREFRACTION = false;
  35522. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  35523. _this.INSTANCES = false;
  35524. _this.NUM_BONE_INFLUENCERS = 0;
  35525. _this.BonesPerMesh = 0;
  35526. _this.NONUNIFORMSCALING = false;
  35527. _this.MORPHTARGETS = false;
  35528. _this.MORPHTARGETS_NORMAL = false;
  35529. _this.MORPHTARGETS_TANGENT = false;
  35530. _this.NUM_MORPH_INFLUENCERS = 0;
  35531. _this.IMAGEPROCESSING = false;
  35532. _this.VIGNETTE = false;
  35533. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  35534. _this.VIGNETTEBLENDMODEOPAQUE = false;
  35535. _this.TONEMAPPING = false;
  35536. _this.CONTRAST = false;
  35537. _this.COLORCURVES = false;
  35538. _this.COLORGRADING = false;
  35539. _this.COLORGRADING3D = false;
  35540. _this.SAMPLER3DGREENDEPTH = false;
  35541. _this.SAMPLER3DBGRMAP = false;
  35542. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  35543. _this.EXPOSURE = false;
  35544. _this.USEPHYSICALLIGHTFALLOFF = false;
  35545. _this.TWOSIDEDLIGHTING = false;
  35546. _this.SHADOWFLOAT = false;
  35547. _this.CLIPPLANE = false;
  35548. _this.POINTSIZE = false;
  35549. _this.FOG = false;
  35550. _this.LOGARITHMICDEPTH = false;
  35551. _this.FORCENORMALFORWARD = false;
  35552. _this.rebuild();
  35553. return _this;
  35554. }
  35555. PBRMaterialDefines.prototype.reset = function () {
  35556. _super.prototype.reset.call(this);
  35557. this.ALPHATESTVALUE = 0.5;
  35558. this.PBR = true;
  35559. };
  35560. return PBRMaterialDefines;
  35561. }(BABYLON.MaterialDefines));
  35562. /**
  35563. * The Physically based material base class of BJS.
  35564. *
  35565. * This offers the main features of a standard PBR material.
  35566. * For more information, please refer to the documentation :
  35567. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  35568. */
  35569. var PBRBaseMaterial = /** @class */ (function (_super) {
  35570. __extends(PBRBaseMaterial, _super);
  35571. /**
  35572. * Instantiates a new PBRMaterial instance.
  35573. *
  35574. * @param name The material name
  35575. * @param scene The scene the material will be use in.
  35576. */
  35577. function PBRBaseMaterial(name, scene) {
  35578. var _this = _super.call(this, name, scene) || this;
  35579. /**
  35580. * Intensity of the direct lights e.g. the four lights available in your scene.
  35581. * This impacts both the direct diffuse and specular highlights.
  35582. */
  35583. _this._directIntensity = 1.0;
  35584. /**
  35585. * Intensity of the emissive part of the material.
  35586. * This helps controlling the emissive effect without modifying the emissive color.
  35587. */
  35588. _this._emissiveIntensity = 1.0;
  35589. /**
  35590. * Intensity of the environment e.g. how much the environment will light the object
  35591. * either through harmonics for rough material or through the refelction for shiny ones.
  35592. */
  35593. _this._environmentIntensity = 1.0;
  35594. /**
  35595. * This is a special control allowing the reduction of the specular highlights coming from the
  35596. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  35597. */
  35598. _this._specularIntensity = 1.0;
  35599. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  35600. /**
  35601. * Debug Control allowing disabling the bump map on this material.
  35602. */
  35603. _this._disableBumpMap = false;
  35604. /**
  35605. * AKA Occlusion Texture Intensity in other nomenclature.
  35606. */
  35607. _this._ambientTextureStrength = 1.0;
  35608. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  35609. /**
  35610. * AKA Diffuse Color in other nomenclature.
  35611. */
  35612. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  35613. /**
  35614. * AKA Specular Color in other nomenclature.
  35615. */
  35616. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  35617. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  35618. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  35619. /**
  35620. * AKA Glossiness in other nomenclature.
  35621. */
  35622. _this._microSurface = 0.9;
  35623. /**
  35624. * source material index of refraction (IOR)' / 'destination material IOR.
  35625. */
  35626. _this._indexOfRefraction = 0.66;
  35627. /**
  35628. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  35629. */
  35630. _this._invertRefractionY = false;
  35631. /**
  35632. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  35633. * Materials half opaque for instance using refraction could benefit from this control.
  35634. */
  35635. _this._linkRefractionWithTransparency = false;
  35636. _this._useLightmapAsShadowmap = false;
  35637. /**
  35638. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  35639. * makes the reflect vector face the model (under horizon).
  35640. */
  35641. _this._useHorizonOcclusion = true;
  35642. /**
  35643. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  35644. * too much the area relying on ambient texture to define their ambient occlusion.
  35645. */
  35646. _this._useRadianceOcclusion = true;
  35647. /**
  35648. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  35649. */
  35650. _this._useAlphaFromAlbedoTexture = false;
  35651. /**
  35652. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  35653. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  35654. */
  35655. _this._useSpecularOverAlpha = true;
  35656. /**
  35657. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  35658. */
  35659. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  35660. /**
  35661. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  35662. */
  35663. _this._useRoughnessFromMetallicTextureAlpha = true;
  35664. /**
  35665. * Specifies if the metallic texture contains the roughness information in its green channel.
  35666. */
  35667. _this._useRoughnessFromMetallicTextureGreen = false;
  35668. /**
  35669. * Specifies if the metallic texture contains the metallness information in its blue channel.
  35670. */
  35671. _this._useMetallnessFromMetallicTextureBlue = false;
  35672. /**
  35673. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  35674. */
  35675. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  35676. /**
  35677. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  35678. */
  35679. _this._useAmbientInGrayScale = false;
  35680. /**
  35681. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  35682. * The material will try to infer what glossiness each pixel should be.
  35683. */
  35684. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  35685. /**
  35686. * BJS is using an harcoded light falloff based on a manually sets up range.
  35687. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  35688. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  35689. */
  35690. _this._usePhysicalLightFalloff = true;
  35691. /**
  35692. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  35693. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  35694. */
  35695. _this._useRadianceOverAlpha = true;
  35696. /**
  35697. * Allows using the bump map in parallax mode.
  35698. */
  35699. _this._useParallax = false;
  35700. /**
  35701. * Allows using the bump map in parallax occlusion mode.
  35702. */
  35703. _this._useParallaxOcclusion = false;
  35704. /**
  35705. * Controls the scale bias of the parallax mode.
  35706. */
  35707. _this._parallaxScaleBias = 0.05;
  35708. /**
  35709. * If sets to true, disables all the lights affecting the material.
  35710. */
  35711. _this._disableLighting = false;
  35712. /**
  35713. * Number of Simultaneous lights allowed on the material.
  35714. */
  35715. _this._maxSimultaneousLights = 4;
  35716. /**
  35717. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  35718. */
  35719. _this._invertNormalMapX = false;
  35720. /**
  35721. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  35722. */
  35723. _this._invertNormalMapY = false;
  35724. /**
  35725. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35726. */
  35727. _this._twoSidedLighting = false;
  35728. /**
  35729. * Defines the alpha limits in alpha test mode.
  35730. */
  35731. _this._alphaCutOff = 0.4;
  35732. /**
  35733. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  35734. */
  35735. _this._forceAlphaTest = false;
  35736. /**
  35737. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  35738. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  35739. */
  35740. _this._useAlphaFresnel = false;
  35741. /**
  35742. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  35743. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  35744. */
  35745. _this._useLinearAlphaFresnel = false;
  35746. /**
  35747. * The transparency mode of the material.
  35748. */
  35749. _this._transparencyMode = null;
  35750. /**
  35751. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  35752. * from cos thetav and roughness:
  35753. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  35754. */
  35755. _this._environmentBRDFTexture = null;
  35756. /**
  35757. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  35758. */
  35759. _this._forceIrradianceInFragment = false;
  35760. /**
  35761. * Force normal to face away from face.
  35762. * (Temporary internal fix to remove before 3.1)
  35763. */
  35764. _this._forceNormalForward = false;
  35765. _this._renderTargets = new BABYLON.SmartArray(16);
  35766. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  35767. // Setup the default processing configuration to the scene.
  35768. _this._attachImageProcessingConfiguration(null);
  35769. _this.getRenderTargetTextures = function () {
  35770. _this._renderTargets.reset();
  35771. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  35772. _this._renderTargets.push(_this._reflectionTexture);
  35773. }
  35774. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  35775. _this._renderTargets.push(_this._refractionTexture);
  35776. }
  35777. return _this._renderTargets;
  35778. };
  35779. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  35780. return _this;
  35781. }
  35782. /**
  35783. * Attaches a new image processing configuration to the PBR Material.
  35784. * @param configuration
  35785. */
  35786. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  35787. var _this = this;
  35788. if (configuration === this._imageProcessingConfiguration) {
  35789. return;
  35790. }
  35791. // Detaches observer.
  35792. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35793. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35794. }
  35795. // Pick the scene configuration if needed.
  35796. if (!configuration) {
  35797. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  35798. }
  35799. else {
  35800. this._imageProcessingConfiguration = configuration;
  35801. }
  35802. // Attaches observer.
  35803. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  35804. _this._markAllSubMeshesAsImageProcessingDirty();
  35805. });
  35806. };
  35807. PBRBaseMaterial.prototype.getClassName = function () {
  35808. return "PBRBaseMaterial";
  35809. };
  35810. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  35811. get: function () {
  35812. return this._useLogarithmicDepth;
  35813. },
  35814. set: function (value) {
  35815. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  35816. },
  35817. enumerable: true,
  35818. configurable: true
  35819. });
  35820. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  35821. /**
  35822. * Gets the current transparency mode.
  35823. */
  35824. get: function () {
  35825. return this._transparencyMode;
  35826. },
  35827. /**
  35828. * Sets the transparency mode of the material.
  35829. */
  35830. set: function (value) {
  35831. if (this._transparencyMode === value) {
  35832. return;
  35833. }
  35834. this._transparencyMode = value;
  35835. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  35836. this._markAllSubMeshesAsTexturesDirty();
  35837. },
  35838. enumerable: true,
  35839. configurable: true
  35840. });
  35841. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  35842. /**
  35843. * Returns true if alpha blending should be disabled.
  35844. */
  35845. get: function () {
  35846. return (this._linkRefractionWithTransparency ||
  35847. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  35848. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  35849. },
  35850. enumerable: true,
  35851. configurable: true
  35852. });
  35853. /**
  35854. * Specifies whether or not this material should be rendered in alpha blend mode.
  35855. */
  35856. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  35857. if (this._disableAlphaBlending) {
  35858. return false;
  35859. }
  35860. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  35861. };
  35862. /**
  35863. * Specifies whether or not this material should be rendered in alpha blend mode for the given mesh.
  35864. */
  35865. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  35866. if (this._disableAlphaBlending) {
  35867. return false;
  35868. }
  35869. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  35870. };
  35871. /**
  35872. * Specifies whether or not this material should be rendered in alpha test mode.
  35873. */
  35874. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  35875. if (this._forceAlphaTest) {
  35876. return true;
  35877. }
  35878. if (this._linkRefractionWithTransparency) {
  35879. return false;
  35880. }
  35881. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  35882. };
  35883. /**
  35884. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  35885. */
  35886. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  35887. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  35888. };
  35889. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  35890. return this._albedoTexture;
  35891. };
  35892. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35893. var _this = this;
  35894. if (subMesh.effect && this.isFrozen) {
  35895. if (this._wasPreviouslyReady) {
  35896. return true;
  35897. }
  35898. }
  35899. if (!subMesh._materialDefines) {
  35900. subMesh._materialDefines = new PBRMaterialDefines();
  35901. }
  35902. var scene = this.getScene();
  35903. var defines = subMesh._materialDefines;
  35904. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  35905. if (defines._renderId === scene.getRenderId()) {
  35906. return true;
  35907. }
  35908. }
  35909. var engine = scene.getEngine();
  35910. // Lights
  35911. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  35912. defines._needNormals = true;
  35913. // Textures
  35914. if (defines._areTexturesDirty) {
  35915. defines._needUVs = false;
  35916. if (scene.texturesEnabled) {
  35917. if (scene.getEngine().getCaps().textureLOD) {
  35918. defines.LODBASEDMICROSFURACE = true;
  35919. }
  35920. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35921. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  35922. return false;
  35923. }
  35924. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  35925. }
  35926. else {
  35927. defines.ALBEDO = false;
  35928. }
  35929. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35930. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  35931. return false;
  35932. }
  35933. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  35934. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  35935. }
  35936. else {
  35937. defines.AMBIENT = false;
  35938. }
  35939. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35940. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  35941. return false;
  35942. }
  35943. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  35944. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  35945. }
  35946. else {
  35947. defines.OPACITY = false;
  35948. }
  35949. var reflectionTexture = this._getReflectionTexture();
  35950. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35951. if (!reflectionTexture.isReadyOrNotBlocking()) {
  35952. return false;
  35953. }
  35954. defines.REFLECTION = true;
  35955. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  35956. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  35957. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  35958. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  35959. defines.INVERTCUBICMAP = true;
  35960. }
  35961. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  35962. switch (reflectionTexture.coordinatesMode) {
  35963. case BABYLON.Texture.CUBIC_MODE:
  35964. case BABYLON.Texture.INVCUBIC_MODE:
  35965. defines.REFLECTIONMAP_CUBIC = true;
  35966. break;
  35967. case BABYLON.Texture.EXPLICIT_MODE:
  35968. defines.REFLECTIONMAP_EXPLICIT = true;
  35969. break;
  35970. case BABYLON.Texture.PLANAR_MODE:
  35971. defines.REFLECTIONMAP_PLANAR = true;
  35972. break;
  35973. case BABYLON.Texture.PROJECTION_MODE:
  35974. defines.REFLECTIONMAP_PROJECTION = true;
  35975. break;
  35976. case BABYLON.Texture.SKYBOX_MODE:
  35977. defines.REFLECTIONMAP_SKYBOX = true;
  35978. break;
  35979. case BABYLON.Texture.SPHERICAL_MODE:
  35980. defines.REFLECTIONMAP_SPHERICAL = true;
  35981. break;
  35982. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  35983. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  35984. break;
  35985. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  35986. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  35987. break;
  35988. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  35989. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  35990. break;
  35991. }
  35992. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  35993. if (reflectionTexture.sphericalPolynomial) {
  35994. defines.USESPHERICALFROMREFLECTIONMAP = true;
  35995. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  35996. defines.USESPHERICALINVERTEX = false;
  35997. }
  35998. else {
  35999. defines.USESPHERICALINVERTEX = true;
  36000. }
  36001. }
  36002. }
  36003. }
  36004. else {
  36005. defines.REFLECTION = false;
  36006. defines.REFLECTIONMAP_3D = false;
  36007. defines.REFLECTIONMAP_SPHERICAL = false;
  36008. defines.REFLECTIONMAP_PLANAR = false;
  36009. defines.REFLECTIONMAP_CUBIC = false;
  36010. defines.REFLECTIONMAP_PROJECTION = false;
  36011. defines.REFLECTIONMAP_SKYBOX = false;
  36012. defines.REFLECTIONMAP_EXPLICIT = false;
  36013. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  36014. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  36015. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  36016. defines.INVERTCUBICMAP = false;
  36017. defines.USESPHERICALFROMREFLECTIONMAP = false;
  36018. defines.USESPHERICALINVERTEX = false;
  36019. defines.REFLECTIONMAP_OPPOSITEZ = false;
  36020. defines.LODINREFLECTIONALPHA = false;
  36021. defines.GAMMAREFLECTION = false;
  36022. }
  36023. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  36024. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  36025. return false;
  36026. }
  36027. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  36028. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  36029. }
  36030. else {
  36031. defines.LIGHTMAP = false;
  36032. }
  36033. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  36034. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  36035. return false;
  36036. }
  36037. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  36038. }
  36039. else {
  36040. defines.EMISSIVE = false;
  36041. }
  36042. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  36043. if (this._metallicTexture) {
  36044. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  36045. return false;
  36046. }
  36047. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  36048. defines.METALLICWORKFLOW = true;
  36049. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  36050. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  36051. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  36052. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  36053. }
  36054. else if (this._reflectivityTexture) {
  36055. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  36056. return false;
  36057. }
  36058. defines.METALLICWORKFLOW = false;
  36059. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  36060. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  36061. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  36062. }
  36063. else {
  36064. defines.METALLICWORKFLOW = false;
  36065. defines.REFLECTIVITY = false;
  36066. }
  36067. if (this._microSurfaceTexture) {
  36068. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  36069. return false;
  36070. }
  36071. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  36072. }
  36073. else {
  36074. defines.MICROSURFACEMAP = false;
  36075. }
  36076. }
  36077. else {
  36078. defines.REFLECTIVITY = false;
  36079. defines.MICROSURFACEMAP = false;
  36080. }
  36081. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  36082. // Bump texure can not be none blocking.
  36083. if (!this._bumpTexture.isReady()) {
  36084. return false;
  36085. }
  36086. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  36087. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36088. defines.PARALLAX = true;
  36089. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  36090. }
  36091. else {
  36092. defines.PARALLAX = false;
  36093. }
  36094. }
  36095. else {
  36096. defines.BUMP = false;
  36097. }
  36098. var refractionTexture = this._getRefractionTexture();
  36099. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  36100. if (!refractionTexture.isReadyOrNotBlocking()) {
  36101. return false;
  36102. }
  36103. defines.REFRACTION = true;
  36104. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  36105. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  36106. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  36107. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  36108. if (this._linkRefractionWithTransparency) {
  36109. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  36110. }
  36111. }
  36112. else {
  36113. defines.REFRACTION = false;
  36114. }
  36115. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36116. // This is blocking.
  36117. if (!this._environmentBRDFTexture.isReady()) {
  36118. return false;
  36119. }
  36120. defines.ENVIRONMENTBRDF = true;
  36121. }
  36122. else {
  36123. defines.ENVIRONMENTBRDF = false;
  36124. }
  36125. if (this._shouldUseAlphaFromAlbedoTexture()) {
  36126. defines.ALPHAFROMALBEDO = true;
  36127. }
  36128. else {
  36129. defines.ALPHAFROMALBEDO = false;
  36130. }
  36131. }
  36132. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  36133. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  36134. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  36135. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  36136. defines.METALLICWORKFLOW = true;
  36137. }
  36138. else {
  36139. defines.METALLICWORKFLOW = false;
  36140. }
  36141. if (!this.backFaceCulling && this._twoSidedLighting) {
  36142. defines.TWOSIDEDLIGHTING = true;
  36143. }
  36144. else {
  36145. defines.TWOSIDEDLIGHTING = false;
  36146. }
  36147. defines.ALPHATESTVALUE = this._alphaCutOff;
  36148. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  36149. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  36150. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  36151. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  36152. }
  36153. if (defines._areImageProcessingDirty) {
  36154. if (!this._imageProcessingConfiguration.isReady()) {
  36155. return false;
  36156. }
  36157. this._imageProcessingConfiguration.prepareDefines(defines);
  36158. }
  36159. defines.FORCENORMALFORWARD = this._forceNormalForward;
  36160. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  36161. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  36162. // Misc.
  36163. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  36164. // Values that need to be evaluated on every frame
  36165. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, this._forceAlphaTest);
  36166. // Attribs
  36167. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE) && mesh) {
  36168. var bufferMesh = null;
  36169. if (mesh instanceof BABYLON.InstancedMesh) {
  36170. bufferMesh = mesh.sourceMesh;
  36171. }
  36172. else if (mesh instanceof BABYLON.Mesh) {
  36173. bufferMesh = mesh;
  36174. }
  36175. if (bufferMesh) {
  36176. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36177. // If the first normal's components is the zero vector in one of the submeshes, we have invalid normals
  36178. var normalVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.NormalKind);
  36179. var normals = normalVertexBuffer.getData();
  36180. var vertexBufferOffset = normalVertexBuffer.getOffset();
  36181. var strideSize = normalVertexBuffer.getStrideSize();
  36182. var offset = vertexBufferOffset + subMesh.indexStart * strideSize;
  36183. if (normals[offset] === 0 && normals[offset + 1] === 0 && normals[offset + 2] === 0) {
  36184. defines.NORMAL = false;
  36185. }
  36186. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36187. // If the first tangent's components is the zero vector in one of the submeshes, we have invalid tangents
  36188. var tangentVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.TangentKind);
  36189. var tangents = tangentVertexBuffer.getData();
  36190. var vertexBufferOffset_1 = tangentVertexBuffer.getOffset();
  36191. var strideSize_1 = tangentVertexBuffer.getStrideSize();
  36192. var offset_1 = vertexBufferOffset_1 + subMesh.indexStart * strideSize_1;
  36193. if (tangents[offset_1] === 0 && tangents[offset_1 + 1] === 0 && tangents[offset_1 + 2] === 0) {
  36194. defines.TANGENT = false;
  36195. }
  36196. }
  36197. }
  36198. else {
  36199. if (!scene.getEngine().getCaps().standardDerivatives) {
  36200. bufferMesh.createNormals(true);
  36201. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  36202. }
  36203. }
  36204. }
  36205. }
  36206. // Get correct effect
  36207. if (defines.isDirty) {
  36208. defines.markAsProcessed();
  36209. scene.resetCachedMaterial();
  36210. // Fallbacks
  36211. var fallbacks = new BABYLON.EffectFallbacks();
  36212. var fallbackRank = 0;
  36213. if (defines.USESPHERICALINVERTEX) {
  36214. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  36215. }
  36216. if (defines.FOG) {
  36217. fallbacks.addFallback(fallbackRank, "FOG");
  36218. }
  36219. if (defines.POINTSIZE) {
  36220. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  36221. }
  36222. if (defines.LOGARITHMICDEPTH) {
  36223. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  36224. }
  36225. if (defines.PARALLAX) {
  36226. fallbacks.addFallback(fallbackRank, "PARALLAX");
  36227. }
  36228. if (defines.PARALLAXOCCLUSION) {
  36229. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  36230. }
  36231. if (defines.ENVIRONMENTBRDF) {
  36232. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  36233. }
  36234. if (defines.TANGENT) {
  36235. fallbacks.addFallback(fallbackRank++, "TANGENT");
  36236. }
  36237. if (defines.BUMP) {
  36238. fallbacks.addFallback(fallbackRank++, "BUMP");
  36239. }
  36240. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  36241. if (defines.SPECULARTERM) {
  36242. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  36243. }
  36244. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  36245. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  36246. }
  36247. if (defines.LIGHTMAP) {
  36248. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  36249. }
  36250. if (defines.NORMAL) {
  36251. fallbacks.addFallback(fallbackRank++, "NORMAL");
  36252. }
  36253. if (defines.AMBIENT) {
  36254. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  36255. }
  36256. if (defines.EMISSIVE) {
  36257. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  36258. }
  36259. if (defines.VERTEXCOLOR) {
  36260. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  36261. }
  36262. if (defines.NUM_BONE_INFLUENCERS > 0) {
  36263. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  36264. }
  36265. if (defines.MORPHTARGETS) {
  36266. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  36267. }
  36268. //Attributes
  36269. var attribs = [BABYLON.VertexBuffer.PositionKind];
  36270. if (defines.NORMAL) {
  36271. attribs.push(BABYLON.VertexBuffer.NormalKind);
  36272. }
  36273. if (defines.TANGENT) {
  36274. attribs.push(BABYLON.VertexBuffer.TangentKind);
  36275. }
  36276. if (defines.UV1) {
  36277. attribs.push(BABYLON.VertexBuffer.UVKind);
  36278. }
  36279. if (defines.UV2) {
  36280. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  36281. }
  36282. if (defines.VERTEXCOLOR) {
  36283. attribs.push(BABYLON.VertexBuffer.ColorKind);
  36284. }
  36285. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  36286. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  36287. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  36288. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  36289. "vFogInfos", "vFogColor", "pointSize",
  36290. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  36291. "mBones",
  36292. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  36293. "vLightingIntensity",
  36294. "logarithmicDepthConstant",
  36295. "vSphericalX", "vSphericalY", "vSphericalZ",
  36296. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  36297. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  36298. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  36299. "vTangentSpaceParams"
  36300. ];
  36301. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  36302. "bumpSampler", "lightmapSampler", "opacitySampler",
  36303. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  36304. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  36305. "microSurfaceSampler", "environmentBrdfSampler"];
  36306. var uniformBuffers = ["Material", "Scene"];
  36307. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  36308. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  36309. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  36310. uniformsNames: uniforms,
  36311. uniformBuffersNames: uniformBuffers,
  36312. samplers: samplers,
  36313. defines: defines,
  36314. maxSimultaneousLights: this._maxSimultaneousLights
  36315. });
  36316. var onCompiled = function (effect) {
  36317. if (_this.onCompiled) {
  36318. _this.onCompiled(effect);
  36319. }
  36320. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  36321. };
  36322. var join = defines.toString();
  36323. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  36324. attributes: attribs,
  36325. uniformsNames: uniforms,
  36326. uniformBuffersNames: uniformBuffers,
  36327. samplers: samplers,
  36328. defines: join,
  36329. fallbacks: fallbacks,
  36330. onCompiled: onCompiled,
  36331. onError: this.onError,
  36332. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  36333. }, engine), defines);
  36334. this.buildUniformLayout();
  36335. }
  36336. if (!subMesh.effect || !subMesh.effect.isReady()) {
  36337. return false;
  36338. }
  36339. defines._renderId = scene.getRenderId();
  36340. this._wasPreviouslyReady = true;
  36341. return true;
  36342. };
  36343. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  36344. // Order is important !
  36345. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  36346. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  36347. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  36348. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  36349. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  36350. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  36351. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  36352. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  36353. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  36354. this._uniformBuffer.addUniform("vBumpInfos", 3);
  36355. this._uniformBuffer.addUniform("albedoMatrix", 16);
  36356. this._uniformBuffer.addUniform("ambientMatrix", 16);
  36357. this._uniformBuffer.addUniform("opacityMatrix", 16);
  36358. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  36359. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  36360. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  36361. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  36362. this._uniformBuffer.addUniform("bumpMatrix", 16);
  36363. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  36364. this._uniformBuffer.addUniform("refractionMatrix", 16);
  36365. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  36366. this._uniformBuffer.addUniform("vReflectionColor", 3);
  36367. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  36368. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  36369. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  36370. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  36371. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  36372. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  36373. this._uniformBuffer.addUniform("pointSize", 1);
  36374. this._uniformBuffer.create();
  36375. };
  36376. PBRBaseMaterial.prototype.unbind = function () {
  36377. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  36378. this._uniformBuffer.setTexture("reflectionSampler", null);
  36379. }
  36380. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  36381. this._uniformBuffer.setTexture("refractionSampler", null);
  36382. }
  36383. _super.prototype.unbind.call(this);
  36384. };
  36385. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  36386. this._activeEffect.setMatrix("world", world);
  36387. };
  36388. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  36389. var scene = this.getScene();
  36390. var defines = subMesh._materialDefines;
  36391. if (!defines) {
  36392. return;
  36393. }
  36394. var effect = subMesh.effect;
  36395. if (!effect) {
  36396. return;
  36397. }
  36398. this._activeEffect = effect;
  36399. // Matrices
  36400. this.bindOnlyWorldMatrix(world);
  36401. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  36402. // Bones
  36403. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  36404. var reflectionTexture = null;
  36405. if (mustRebind) {
  36406. this._uniformBuffer.bindToEffect(effect, "Material");
  36407. this.bindViewProjection(effect);
  36408. reflectionTexture = this._getReflectionTexture();
  36409. var refractionTexture = this._getRefractionTexture();
  36410. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  36411. // Texture uniforms
  36412. if (scene.texturesEnabled) {
  36413. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36414. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  36415. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  36416. }
  36417. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  36418. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  36419. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  36420. }
  36421. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  36422. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  36423. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  36424. }
  36425. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36426. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  36427. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  36428. var polynomials = reflectionTexture.sphericalPolynomial;
  36429. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  36430. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  36431. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  36432. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  36433. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  36434. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  36435. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  36436. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  36437. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  36438. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  36439. }
  36440. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  36441. }
  36442. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  36443. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  36444. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  36445. }
  36446. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  36447. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  36448. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  36449. }
  36450. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  36451. if (this._metallicTexture) {
  36452. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  36453. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  36454. }
  36455. else if (this._reflectivityTexture) {
  36456. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  36457. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  36458. }
  36459. if (this._microSurfaceTexture) {
  36460. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  36461. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  36462. }
  36463. }
  36464. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  36465. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  36466. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  36467. if (scene._mirroredCameraPosition) {
  36468. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  36469. }
  36470. else {
  36471. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  36472. }
  36473. }
  36474. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  36475. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  36476. var depth = 1.0;
  36477. if (!refractionTexture.isCube) {
  36478. if (refractionTexture.depth) {
  36479. depth = refractionTexture.depth;
  36480. }
  36481. }
  36482. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  36483. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  36484. }
  36485. }
  36486. // Point size
  36487. if (this.pointsCloud) {
  36488. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  36489. }
  36490. // Colors
  36491. if (defines.METALLICWORKFLOW) {
  36492. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  36493. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  36494. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  36495. }
  36496. else {
  36497. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  36498. }
  36499. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  36500. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  36501. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  36502. // Misc
  36503. this._lightingInfos.x = this._directIntensity;
  36504. this._lightingInfos.y = this._emissiveIntensity;
  36505. this._lightingInfos.z = this._environmentIntensity;
  36506. this._lightingInfos.w = this._specularIntensity;
  36507. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  36508. }
  36509. // Textures
  36510. if (scene.texturesEnabled) {
  36511. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36512. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  36513. }
  36514. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  36515. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  36516. }
  36517. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  36518. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  36519. }
  36520. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36521. if (defines.LODBASEDMICROSFURACE) {
  36522. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  36523. }
  36524. else {
  36525. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  36526. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  36527. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  36528. }
  36529. }
  36530. if (defines.ENVIRONMENTBRDF) {
  36531. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  36532. }
  36533. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  36534. if (defines.LODBASEDMICROSFURACE) {
  36535. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  36536. }
  36537. else {
  36538. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  36539. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  36540. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  36541. }
  36542. }
  36543. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  36544. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  36545. }
  36546. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  36547. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  36548. }
  36549. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  36550. if (this._metallicTexture) {
  36551. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  36552. }
  36553. else if (this._reflectivityTexture) {
  36554. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  36555. }
  36556. if (this._microSurfaceTexture) {
  36557. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  36558. }
  36559. }
  36560. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  36561. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  36562. }
  36563. }
  36564. // Clip plane
  36565. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  36566. // Colors
  36567. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  36568. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  36569. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  36570. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  36571. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  36572. }
  36573. if (mustRebind || !this.isFrozen) {
  36574. // Lights
  36575. if (scene.lightsEnabled && !this._disableLighting) {
  36576. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  36577. }
  36578. // View
  36579. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  36580. this.bindView(effect);
  36581. }
  36582. // Fog
  36583. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  36584. // Morph targets
  36585. if (defines.NUM_MORPH_INFLUENCERS) {
  36586. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  36587. }
  36588. // image processing
  36589. this._imageProcessingConfiguration.bind(this._activeEffect);
  36590. // Log. depth
  36591. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  36592. }
  36593. this._uniformBuffer.update();
  36594. this._afterBind(mesh);
  36595. };
  36596. PBRBaseMaterial.prototype.getAnimatables = function () {
  36597. var results = [];
  36598. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  36599. results.push(this._albedoTexture);
  36600. }
  36601. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  36602. results.push(this._ambientTexture);
  36603. }
  36604. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  36605. results.push(this._opacityTexture);
  36606. }
  36607. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  36608. results.push(this._reflectionTexture);
  36609. }
  36610. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  36611. results.push(this._emissiveTexture);
  36612. }
  36613. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  36614. results.push(this._metallicTexture);
  36615. }
  36616. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  36617. results.push(this._reflectivityTexture);
  36618. }
  36619. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  36620. results.push(this._bumpTexture);
  36621. }
  36622. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  36623. results.push(this._lightmapTexture);
  36624. }
  36625. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  36626. results.push(this._refractionTexture);
  36627. }
  36628. return results;
  36629. };
  36630. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  36631. if (this._reflectionTexture) {
  36632. return this._reflectionTexture;
  36633. }
  36634. return this.getScene().environmentTexture;
  36635. };
  36636. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  36637. if (this._refractionTexture) {
  36638. return this._refractionTexture;
  36639. }
  36640. if (this._linkRefractionWithTransparency) {
  36641. return this.getScene().environmentTexture;
  36642. }
  36643. return null;
  36644. };
  36645. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36646. if (forceDisposeTextures) {
  36647. if (this._albedoTexture) {
  36648. this._albedoTexture.dispose();
  36649. }
  36650. if (this._ambientTexture) {
  36651. this._ambientTexture.dispose();
  36652. }
  36653. if (this._opacityTexture) {
  36654. this._opacityTexture.dispose();
  36655. }
  36656. if (this._reflectionTexture) {
  36657. this._reflectionTexture.dispose();
  36658. }
  36659. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  36660. this._environmentBRDFTexture.dispose();
  36661. }
  36662. if (this._emissiveTexture) {
  36663. this._emissiveTexture.dispose();
  36664. }
  36665. if (this._metallicTexture) {
  36666. this._metallicTexture.dispose();
  36667. }
  36668. if (this._reflectivityTexture) {
  36669. this._reflectivityTexture.dispose();
  36670. }
  36671. if (this._bumpTexture) {
  36672. this._bumpTexture.dispose();
  36673. }
  36674. if (this._lightmapTexture) {
  36675. this._lightmapTexture.dispose();
  36676. }
  36677. if (this._refractionTexture) {
  36678. this._refractionTexture.dispose();
  36679. }
  36680. }
  36681. this._renderTargets.dispose();
  36682. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36683. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36684. }
  36685. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  36686. };
  36687. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  36688. __decorate([
  36689. BABYLON.serializeAsImageProcessingConfiguration()
  36690. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  36691. __decorate([
  36692. BABYLON.serialize()
  36693. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  36694. __decorate([
  36695. BABYLON.serialize()
  36696. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  36697. return PBRBaseMaterial;
  36698. }(BABYLON.PushMaterial));
  36699. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  36700. })(BABYLON || (BABYLON = {}));
  36701. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  36702. var BABYLON;
  36703. (function (BABYLON) {
  36704. var Internals;
  36705. (function (Internals) {
  36706. /**
  36707. * The Physically based simple base material of BJS.
  36708. *
  36709. * This enables better naming and convention enforcements on top of the pbrMaterial.
  36710. * It is used as the base class for both the specGloss and metalRough conventions.
  36711. */
  36712. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  36713. __extends(PBRBaseSimpleMaterial, _super);
  36714. /**
  36715. * Instantiates a new PBRMaterial instance.
  36716. *
  36717. * @param name The material name
  36718. * @param scene The scene the material will be use in.
  36719. */
  36720. function PBRBaseSimpleMaterial(name, scene) {
  36721. var _this = _super.call(this, name, scene) || this;
  36722. /**
  36723. * Number of Simultaneous lights allowed on the material.
  36724. */
  36725. _this.maxSimultaneousLights = 4;
  36726. /**
  36727. * If sets to true, disables all the lights affecting the material.
  36728. */
  36729. _this.disableLighting = false;
  36730. /**
  36731. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  36732. */
  36733. _this.invertNormalMapX = false;
  36734. /**
  36735. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  36736. */
  36737. _this.invertNormalMapY = false;
  36738. /**
  36739. * Emissivie color used to self-illuminate the model.
  36740. */
  36741. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  36742. /**
  36743. * Occlusion Channel Strenght.
  36744. */
  36745. _this.occlusionStrength = 1.0;
  36746. _this.useLightmapAsShadowmap = false;
  36747. _this._useAlphaFromAlbedoTexture = true;
  36748. _this._useAmbientInGrayScale = true;
  36749. return _this;
  36750. }
  36751. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  36752. /**
  36753. * Gets the current double sided mode.
  36754. */
  36755. get: function () {
  36756. return this._twoSidedLighting;
  36757. },
  36758. /**
  36759. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36760. */
  36761. set: function (value) {
  36762. if (this._twoSidedLighting === value) {
  36763. return;
  36764. }
  36765. this._twoSidedLighting = value;
  36766. this.backFaceCulling = !value;
  36767. this._markAllSubMeshesAsTexturesDirty();
  36768. },
  36769. enumerable: true,
  36770. configurable: true
  36771. });
  36772. /**
  36773. * Return the active textures of the material.
  36774. */
  36775. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  36776. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36777. if (this.environmentTexture) {
  36778. activeTextures.push(this.environmentTexture);
  36779. }
  36780. if (this.normalTexture) {
  36781. activeTextures.push(this.normalTexture);
  36782. }
  36783. if (this.emissiveTexture) {
  36784. activeTextures.push(this.emissiveTexture);
  36785. }
  36786. if (this.occlusionTexture) {
  36787. activeTextures.push(this.occlusionTexture);
  36788. }
  36789. if (this.lightmapTexture) {
  36790. activeTextures.push(this.lightmapTexture);
  36791. }
  36792. return activeTextures;
  36793. };
  36794. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  36795. if (_super.prototype.hasTexture.call(this, texture)) {
  36796. return true;
  36797. }
  36798. if (this.lightmapTexture === texture) {
  36799. return true;
  36800. }
  36801. return false;
  36802. };
  36803. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  36804. return "PBRBaseSimpleMaterial";
  36805. };
  36806. __decorate([
  36807. BABYLON.serialize(),
  36808. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36809. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  36810. __decorate([
  36811. BABYLON.serialize(),
  36812. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36813. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  36814. __decorate([
  36815. BABYLON.serializeAsTexture(),
  36816. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  36817. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  36818. __decorate([
  36819. BABYLON.serialize(),
  36820. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36821. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  36822. __decorate([
  36823. BABYLON.serialize(),
  36824. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36825. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  36826. __decorate([
  36827. BABYLON.serializeAsTexture(),
  36828. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  36829. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  36830. __decorate([
  36831. BABYLON.serializeAsColor3("emissive"),
  36832. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36833. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  36834. __decorate([
  36835. BABYLON.serializeAsTexture(),
  36836. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36837. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  36838. __decorate([
  36839. BABYLON.serialize(),
  36840. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  36841. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  36842. __decorate([
  36843. BABYLON.serializeAsTexture(),
  36844. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  36845. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  36846. __decorate([
  36847. BABYLON.serialize(),
  36848. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  36849. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  36850. __decorate([
  36851. BABYLON.serialize()
  36852. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  36853. __decorate([
  36854. BABYLON.serializeAsTexture(),
  36855. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  36856. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  36857. __decorate([
  36858. BABYLON.serialize(),
  36859. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36860. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  36861. return PBRBaseSimpleMaterial;
  36862. }(BABYLON.PBRBaseMaterial));
  36863. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  36864. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  36865. })(BABYLON || (BABYLON = {}));
  36866. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  36867. var BABYLON;
  36868. (function (BABYLON) {
  36869. /**
  36870. * The Physically based material of BJS.
  36871. *
  36872. * This offers the main features of a standard PBR material.
  36873. * For more information, please refer to the documentation :
  36874. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  36875. */
  36876. var PBRMaterial = /** @class */ (function (_super) {
  36877. __extends(PBRMaterial, _super);
  36878. /**
  36879. * Instantiates a new PBRMaterial instance.
  36880. *
  36881. * @param name The material name
  36882. * @param scene The scene the material will be use in.
  36883. */
  36884. function PBRMaterial(name, scene) {
  36885. var _this = _super.call(this, name, scene) || this;
  36886. /**
  36887. * Intensity of the direct lights e.g. the four lights available in your scene.
  36888. * This impacts both the direct diffuse and specular highlights.
  36889. */
  36890. _this.directIntensity = 1.0;
  36891. /**
  36892. * Intensity of the emissive part of the material.
  36893. * This helps controlling the emissive effect without modifying the emissive color.
  36894. */
  36895. _this.emissiveIntensity = 1.0;
  36896. /**
  36897. * Intensity of the environment e.g. how much the environment will light the object
  36898. * either through harmonics for rough material or through the refelction for shiny ones.
  36899. */
  36900. _this.environmentIntensity = 1.0;
  36901. /**
  36902. * This is a special control allowing the reduction of the specular highlights coming from the
  36903. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  36904. */
  36905. _this.specularIntensity = 1.0;
  36906. /**
  36907. * Debug Control allowing disabling the bump map on this material.
  36908. */
  36909. _this.disableBumpMap = false;
  36910. /**
  36911. * AKA Occlusion Texture Intensity in other nomenclature.
  36912. */
  36913. _this.ambientTextureStrength = 1.0;
  36914. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  36915. /**
  36916. * AKA Diffuse Color in other nomenclature.
  36917. */
  36918. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  36919. /**
  36920. * AKA Specular Color in other nomenclature.
  36921. */
  36922. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  36923. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  36924. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  36925. /**
  36926. * AKA Glossiness in other nomenclature.
  36927. */
  36928. _this.microSurface = 1.0;
  36929. /**
  36930. * source material index of refraction (IOR)' / 'destination material IOR.
  36931. */
  36932. _this.indexOfRefraction = 0.66;
  36933. /**
  36934. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  36935. */
  36936. _this.invertRefractionY = false;
  36937. /**
  36938. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  36939. * Materials half opaque for instance using refraction could benefit from this control.
  36940. */
  36941. _this.linkRefractionWithTransparency = false;
  36942. _this.useLightmapAsShadowmap = false;
  36943. /**
  36944. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  36945. */
  36946. _this.useAlphaFromAlbedoTexture = false;
  36947. /**
  36948. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  36949. */
  36950. _this.forceAlphaTest = false;
  36951. /**
  36952. * Defines the alpha limits in alpha test mode.
  36953. */
  36954. _this.alphaCutOff = 0.4;
  36955. /**
  36956. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  36957. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  36958. */
  36959. _this.useSpecularOverAlpha = true;
  36960. /**
  36961. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  36962. */
  36963. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  36964. /**
  36965. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  36966. */
  36967. _this.useRoughnessFromMetallicTextureAlpha = true;
  36968. /**
  36969. * Specifies if the metallic texture contains the roughness information in its green channel.
  36970. */
  36971. _this.useRoughnessFromMetallicTextureGreen = false;
  36972. /**
  36973. * Specifies if the metallic texture contains the metallness information in its blue channel.
  36974. */
  36975. _this.useMetallnessFromMetallicTextureBlue = false;
  36976. /**
  36977. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  36978. */
  36979. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  36980. /**
  36981. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  36982. */
  36983. _this.useAmbientInGrayScale = false;
  36984. /**
  36985. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  36986. * The material will try to infer what glossiness each pixel should be.
  36987. */
  36988. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  36989. /**
  36990. * BJS is using an harcoded light falloff based on a manually sets up range.
  36991. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  36992. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  36993. */
  36994. _this.usePhysicalLightFalloff = true;
  36995. /**
  36996. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  36997. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  36998. */
  36999. _this.useRadianceOverAlpha = true;
  37000. /**
  37001. * Allows using the bump map in parallax mode.
  37002. */
  37003. _this.useParallax = false;
  37004. /**
  37005. * Allows using the bump map in parallax occlusion mode.
  37006. */
  37007. _this.useParallaxOcclusion = false;
  37008. /**
  37009. * Controls the scale bias of the parallax mode.
  37010. */
  37011. _this.parallaxScaleBias = 0.05;
  37012. /**
  37013. * If sets to true, disables all the lights affecting the material.
  37014. */
  37015. _this.disableLighting = false;
  37016. /**
  37017. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  37018. */
  37019. _this.forceIrradianceInFragment = false;
  37020. /**
  37021. * Number of Simultaneous lights allowed on the material.
  37022. */
  37023. _this.maxSimultaneousLights = 4;
  37024. /**
  37025. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  37026. */
  37027. _this.invertNormalMapX = false;
  37028. /**
  37029. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  37030. */
  37031. _this.invertNormalMapY = false;
  37032. /**
  37033. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  37034. */
  37035. _this.twoSidedLighting = false;
  37036. /**
  37037. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37038. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  37039. */
  37040. _this.useAlphaFresnel = false;
  37041. /**
  37042. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37043. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  37044. */
  37045. _this.useLinearAlphaFresnel = false;
  37046. /**
  37047. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37048. * And/Or occlude the blended part.
  37049. */
  37050. _this.environmentBRDFTexture = null;
  37051. /**
  37052. * Force normal to face away from face.
  37053. * (Temporary internal fix to remove before 3.1)
  37054. */
  37055. _this.forceNormalForward = false;
  37056. /**
  37057. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  37058. * makes the reflect vector face the model (under horizon).
  37059. */
  37060. _this.useHorizonOcclusion = true;
  37061. /**
  37062. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  37063. * too much the area relying on ambient texture to define their ambient occlusion.
  37064. */
  37065. _this.useRadianceOcclusion = true;
  37066. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  37067. return _this;
  37068. }
  37069. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  37070. /**
  37071. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  37072. */
  37073. get: function () {
  37074. return this._PBRMATERIAL_OPAQUE;
  37075. },
  37076. enumerable: true,
  37077. configurable: true
  37078. });
  37079. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  37080. /**
  37081. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  37082. */
  37083. get: function () {
  37084. return this._PBRMATERIAL_ALPHATEST;
  37085. },
  37086. enumerable: true,
  37087. configurable: true
  37088. });
  37089. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  37090. /**
  37091. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  37092. */
  37093. get: function () {
  37094. return this._PBRMATERIAL_ALPHABLEND;
  37095. },
  37096. enumerable: true,
  37097. configurable: true
  37098. });
  37099. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  37100. /**
  37101. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  37102. * They are also discarded below the alpha cutoff threshold to improve performances.
  37103. */
  37104. get: function () {
  37105. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  37106. },
  37107. enumerable: true,
  37108. configurable: true
  37109. });
  37110. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  37111. /**
  37112. * Gets the image processing configuration used either in this material.
  37113. */
  37114. get: function () {
  37115. return this._imageProcessingConfiguration;
  37116. },
  37117. /**
  37118. * Sets the Default image processing configuration used either in the this material.
  37119. *
  37120. * If sets to null, the scene one is in use.
  37121. */
  37122. set: function (value) {
  37123. this._attachImageProcessingConfiguration(value);
  37124. // Ensure the effect will be rebuilt.
  37125. this._markAllSubMeshesAsTexturesDirty();
  37126. },
  37127. enumerable: true,
  37128. configurable: true
  37129. });
  37130. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  37131. /**
  37132. * Gets wether the color curves effect is enabled.
  37133. */
  37134. get: function () {
  37135. return this.imageProcessingConfiguration.colorCurvesEnabled;
  37136. },
  37137. /**
  37138. * Sets wether the color curves effect is enabled.
  37139. */
  37140. set: function (value) {
  37141. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  37142. },
  37143. enumerable: true,
  37144. configurable: true
  37145. });
  37146. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  37147. /**
  37148. * Gets wether the color grading effect is enabled.
  37149. */
  37150. get: function () {
  37151. return this.imageProcessingConfiguration.colorGradingEnabled;
  37152. },
  37153. /**
  37154. * Gets wether the color grading effect is enabled.
  37155. */
  37156. set: function (value) {
  37157. this.imageProcessingConfiguration.colorGradingEnabled = value;
  37158. },
  37159. enumerable: true,
  37160. configurable: true
  37161. });
  37162. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  37163. /**
  37164. * Gets wether tonemapping is enabled or not.
  37165. */
  37166. get: function () {
  37167. return this._imageProcessingConfiguration.toneMappingEnabled;
  37168. },
  37169. /**
  37170. * Sets wether tonemapping is enabled or not
  37171. */
  37172. set: function (value) {
  37173. this._imageProcessingConfiguration.toneMappingEnabled = value;
  37174. },
  37175. enumerable: true,
  37176. configurable: true
  37177. });
  37178. ;
  37179. ;
  37180. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  37181. /**
  37182. * The camera exposure used on this material.
  37183. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  37184. * This corresponds to a photographic exposure.
  37185. */
  37186. get: function () {
  37187. return this._imageProcessingConfiguration.exposure;
  37188. },
  37189. /**
  37190. * The camera exposure used on this material.
  37191. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  37192. * This corresponds to a photographic exposure.
  37193. */
  37194. set: function (value) {
  37195. this._imageProcessingConfiguration.exposure = value;
  37196. },
  37197. enumerable: true,
  37198. configurable: true
  37199. });
  37200. ;
  37201. ;
  37202. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  37203. /**
  37204. * Gets The camera contrast used on this material.
  37205. */
  37206. get: function () {
  37207. return this._imageProcessingConfiguration.contrast;
  37208. },
  37209. /**
  37210. * Sets The camera contrast used on this material.
  37211. */
  37212. set: function (value) {
  37213. this._imageProcessingConfiguration.contrast = value;
  37214. },
  37215. enumerable: true,
  37216. configurable: true
  37217. });
  37218. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  37219. /**
  37220. * Gets the Color Grading 2D Lookup Texture.
  37221. */
  37222. get: function () {
  37223. return this._imageProcessingConfiguration.colorGradingTexture;
  37224. },
  37225. /**
  37226. * Sets the Color Grading 2D Lookup Texture.
  37227. */
  37228. set: function (value) {
  37229. this._imageProcessingConfiguration.colorGradingTexture = value;
  37230. },
  37231. enumerable: true,
  37232. configurable: true
  37233. });
  37234. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  37235. /**
  37236. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37237. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37238. * 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;
  37239. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37240. */
  37241. get: function () {
  37242. return this._imageProcessingConfiguration.colorCurves;
  37243. },
  37244. /**
  37245. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37246. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37247. * 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;
  37248. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37249. */
  37250. set: function (value) {
  37251. this._imageProcessingConfiguration.colorCurves = value;
  37252. },
  37253. enumerable: true,
  37254. configurable: true
  37255. });
  37256. PBRMaterial.prototype.getClassName = function () {
  37257. return "PBRMaterial";
  37258. };
  37259. PBRMaterial.prototype.getActiveTextures = function () {
  37260. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37261. if (this._albedoTexture) {
  37262. activeTextures.push(this._albedoTexture);
  37263. }
  37264. if (this._ambientTexture) {
  37265. activeTextures.push(this._ambientTexture);
  37266. }
  37267. if (this._opacityTexture) {
  37268. activeTextures.push(this._opacityTexture);
  37269. }
  37270. if (this._reflectionTexture) {
  37271. activeTextures.push(this._reflectionTexture);
  37272. }
  37273. if (this._emissiveTexture) {
  37274. activeTextures.push(this._emissiveTexture);
  37275. }
  37276. if (this._reflectivityTexture) {
  37277. activeTextures.push(this._reflectivityTexture);
  37278. }
  37279. if (this._metallicTexture) {
  37280. activeTextures.push(this._metallicTexture);
  37281. }
  37282. if (this._microSurfaceTexture) {
  37283. activeTextures.push(this._microSurfaceTexture);
  37284. }
  37285. if (this._bumpTexture) {
  37286. activeTextures.push(this._bumpTexture);
  37287. }
  37288. if (this._lightmapTexture) {
  37289. activeTextures.push(this._lightmapTexture);
  37290. }
  37291. if (this._refractionTexture) {
  37292. activeTextures.push(this._refractionTexture);
  37293. }
  37294. return activeTextures;
  37295. };
  37296. PBRMaterial.prototype.hasTexture = function (texture) {
  37297. if (_super.prototype.hasTexture.call(this, texture)) {
  37298. return true;
  37299. }
  37300. if (this._albedoTexture === texture) {
  37301. return true;
  37302. }
  37303. if (this._ambientTexture === texture) {
  37304. return true;
  37305. }
  37306. if (this._opacityTexture === texture) {
  37307. return true;
  37308. }
  37309. if (this._reflectionTexture === texture) {
  37310. return true;
  37311. }
  37312. if (this._reflectivityTexture === texture) {
  37313. return true;
  37314. }
  37315. if (this._metallicTexture === texture) {
  37316. return true;
  37317. }
  37318. if (this._microSurfaceTexture === texture) {
  37319. return true;
  37320. }
  37321. if (this._bumpTexture === texture) {
  37322. return true;
  37323. }
  37324. if (this._lightmapTexture === texture) {
  37325. return true;
  37326. }
  37327. if (this._refractionTexture === texture) {
  37328. return true;
  37329. }
  37330. return false;
  37331. };
  37332. PBRMaterial.prototype.clone = function (name) {
  37333. var _this = this;
  37334. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  37335. clone.id = name;
  37336. clone.name = name;
  37337. return clone;
  37338. };
  37339. PBRMaterial.prototype.serialize = function () {
  37340. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  37341. serializationObject.customType = "BABYLON.PBRMaterial";
  37342. return serializationObject;
  37343. };
  37344. // Statics
  37345. PBRMaterial.Parse = function (source, scene, rootUrl) {
  37346. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  37347. };
  37348. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  37349. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  37350. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  37351. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  37352. __decorate([
  37353. BABYLON.serialize(),
  37354. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37355. ], PBRMaterial.prototype, "directIntensity", void 0);
  37356. __decorate([
  37357. BABYLON.serialize(),
  37358. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37359. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  37360. __decorate([
  37361. BABYLON.serialize(),
  37362. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37363. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  37364. __decorate([
  37365. BABYLON.serialize(),
  37366. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37367. ], PBRMaterial.prototype, "specularIntensity", void 0);
  37368. __decorate([
  37369. BABYLON.serialize(),
  37370. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37371. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  37372. __decorate([
  37373. BABYLON.serializeAsTexture(),
  37374. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37375. ], PBRMaterial.prototype, "albedoTexture", void 0);
  37376. __decorate([
  37377. BABYLON.serializeAsTexture(),
  37378. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37379. ], PBRMaterial.prototype, "ambientTexture", void 0);
  37380. __decorate([
  37381. BABYLON.serialize(),
  37382. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37383. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  37384. __decorate([
  37385. BABYLON.serializeAsTexture(),
  37386. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37387. ], PBRMaterial.prototype, "opacityTexture", void 0);
  37388. __decorate([
  37389. BABYLON.serializeAsTexture(),
  37390. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37391. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  37392. __decorate([
  37393. BABYLON.serializeAsTexture(),
  37394. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37395. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  37396. __decorate([
  37397. BABYLON.serializeAsTexture(),
  37398. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37399. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  37400. __decorate([
  37401. BABYLON.serializeAsTexture(),
  37402. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37403. ], PBRMaterial.prototype, "metallicTexture", void 0);
  37404. __decorate([
  37405. BABYLON.serialize(),
  37406. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37407. ], PBRMaterial.prototype, "metallic", void 0);
  37408. __decorate([
  37409. BABYLON.serialize(),
  37410. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37411. ], PBRMaterial.prototype, "roughness", void 0);
  37412. __decorate([
  37413. BABYLON.serializeAsTexture(),
  37414. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37415. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  37416. __decorate([
  37417. BABYLON.serializeAsTexture(),
  37418. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37419. ], PBRMaterial.prototype, "bumpTexture", void 0);
  37420. __decorate([
  37421. BABYLON.serializeAsTexture(),
  37422. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  37423. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  37424. __decorate([
  37425. BABYLON.serializeAsTexture(),
  37426. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37427. ], PBRMaterial.prototype, "refractionTexture", void 0);
  37428. __decorate([
  37429. BABYLON.serializeAsColor3("ambient"),
  37430. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37431. ], PBRMaterial.prototype, "ambientColor", void 0);
  37432. __decorate([
  37433. BABYLON.serializeAsColor3("albedo"),
  37434. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37435. ], PBRMaterial.prototype, "albedoColor", void 0);
  37436. __decorate([
  37437. BABYLON.serializeAsColor3("reflectivity"),
  37438. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37439. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  37440. __decorate([
  37441. BABYLON.serializeAsColor3("reflection"),
  37442. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37443. ], PBRMaterial.prototype, "reflectionColor", void 0);
  37444. __decorate([
  37445. BABYLON.serializeAsColor3("emissive"),
  37446. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37447. ], PBRMaterial.prototype, "emissiveColor", void 0);
  37448. __decorate([
  37449. BABYLON.serialize(),
  37450. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37451. ], PBRMaterial.prototype, "microSurface", void 0);
  37452. __decorate([
  37453. BABYLON.serialize(),
  37454. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37455. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  37456. __decorate([
  37457. BABYLON.serialize(),
  37458. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37459. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  37460. __decorate([
  37461. BABYLON.serialize(),
  37462. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37463. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  37464. __decorate([
  37465. BABYLON.serialize(),
  37466. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37467. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  37468. __decorate([
  37469. BABYLON.serialize(),
  37470. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37471. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  37472. __decorate([
  37473. BABYLON.serialize(),
  37474. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37475. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  37476. __decorate([
  37477. BABYLON.serialize(),
  37478. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37479. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  37480. __decorate([
  37481. BABYLON.serialize(),
  37482. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37483. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  37484. __decorate([
  37485. BABYLON.serialize(),
  37486. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37487. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  37488. __decorate([
  37489. BABYLON.serialize(),
  37490. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37491. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  37492. __decorate([
  37493. BABYLON.serialize(),
  37494. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37495. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  37496. __decorate([
  37497. BABYLON.serialize(),
  37498. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37499. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  37500. __decorate([
  37501. BABYLON.serialize(),
  37502. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37503. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  37504. __decorate([
  37505. BABYLON.serialize(),
  37506. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37507. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  37508. __decorate([
  37509. BABYLON.serialize(),
  37510. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37511. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  37512. __decorate([
  37513. BABYLON.serialize(),
  37514. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37515. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  37516. __decorate([
  37517. BABYLON.serialize(),
  37518. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37519. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  37520. __decorate([
  37521. BABYLON.serialize(),
  37522. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37523. ], PBRMaterial.prototype, "useParallax", void 0);
  37524. __decorate([
  37525. BABYLON.serialize(),
  37526. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37527. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  37528. __decorate([
  37529. BABYLON.serialize(),
  37530. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37531. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  37532. __decorate([
  37533. BABYLON.serialize(),
  37534. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37535. ], PBRMaterial.prototype, "disableLighting", void 0);
  37536. __decorate([
  37537. BABYLON.serialize(),
  37538. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37539. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  37540. __decorate([
  37541. BABYLON.serialize(),
  37542. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37543. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  37544. __decorate([
  37545. BABYLON.serialize(),
  37546. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37547. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  37548. __decorate([
  37549. BABYLON.serialize(),
  37550. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37551. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  37552. __decorate([
  37553. BABYLON.serialize(),
  37554. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37555. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  37556. __decorate([
  37557. BABYLON.serialize(),
  37558. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37559. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  37560. __decorate([
  37561. BABYLON.serialize(),
  37562. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37563. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  37564. __decorate([
  37565. BABYLON.serializeAsTexture(),
  37566. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37567. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  37568. __decorate([
  37569. BABYLON.serialize(),
  37570. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37571. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  37572. __decorate([
  37573. BABYLON.serialize(),
  37574. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37575. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  37576. __decorate([
  37577. BABYLON.serialize(),
  37578. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37579. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  37580. return PBRMaterial;
  37581. }(BABYLON.PBRBaseMaterial));
  37582. BABYLON.PBRMaterial = PBRMaterial;
  37583. })(BABYLON || (BABYLON = {}));
  37584. //# sourceMappingURL=babylon.pbrMaterial.js.map
  37585. var BABYLON;
  37586. (function (BABYLON) {
  37587. /**
  37588. * The PBR material of BJS following the metal roughness convention.
  37589. *
  37590. * This fits to the PBR convention in the GLTF definition:
  37591. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  37592. */
  37593. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  37594. __extends(PBRMetallicRoughnessMaterial, _super);
  37595. /**
  37596. * Instantiates a new PBRMetalRoughnessMaterial instance.
  37597. *
  37598. * @param name The material name
  37599. * @param scene The scene the material will be use in.
  37600. */
  37601. function PBRMetallicRoughnessMaterial(name, scene) {
  37602. var _this = _super.call(this, name, scene) || this;
  37603. _this._useRoughnessFromMetallicTextureAlpha = false;
  37604. _this._useRoughnessFromMetallicTextureGreen = true;
  37605. _this._useMetallnessFromMetallicTextureBlue = true;
  37606. return _this;
  37607. }
  37608. /**
  37609. * Return the currrent class name of the material.
  37610. */
  37611. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  37612. return "PBRMetallicRoughnessMaterial";
  37613. };
  37614. /**
  37615. * Return the active textures of the material.
  37616. */
  37617. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  37618. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37619. if (this.baseTexture) {
  37620. activeTextures.push(this.baseTexture);
  37621. }
  37622. if (this.metallicRoughnessTexture) {
  37623. activeTextures.push(this.metallicRoughnessTexture);
  37624. }
  37625. return activeTextures;
  37626. };
  37627. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  37628. if (_super.prototype.hasTexture.call(this, texture)) {
  37629. return true;
  37630. }
  37631. if (this.baseTexture === texture) {
  37632. return true;
  37633. }
  37634. if (this.metallicRoughnessTexture === texture) {
  37635. return true;
  37636. }
  37637. return false;
  37638. };
  37639. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  37640. var _this = this;
  37641. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  37642. clone.id = name;
  37643. clone.name = name;
  37644. return clone;
  37645. };
  37646. /**
  37647. * Serialize the material to a parsable JSON object.
  37648. */
  37649. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  37650. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  37651. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  37652. return serializationObject;
  37653. };
  37654. /**
  37655. * Parses a JSON object correponding to the serialize function.
  37656. */
  37657. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  37658. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  37659. };
  37660. __decorate([
  37661. BABYLON.serializeAsColor3(),
  37662. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  37663. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  37664. __decorate([
  37665. BABYLON.serializeAsTexture(),
  37666. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  37667. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  37668. __decorate([
  37669. BABYLON.serialize(),
  37670. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37671. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  37672. __decorate([
  37673. BABYLON.serialize(),
  37674. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37675. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  37676. __decorate([
  37677. BABYLON.serializeAsTexture(),
  37678. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  37679. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  37680. return PBRMetallicRoughnessMaterial;
  37681. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  37682. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  37683. })(BABYLON || (BABYLON = {}));
  37684. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  37685. var BABYLON;
  37686. (function (BABYLON) {
  37687. /**
  37688. * The PBR material of BJS following the specular glossiness convention.
  37689. *
  37690. * This fits to the PBR convention in the GLTF definition:
  37691. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  37692. */
  37693. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  37694. __extends(PBRSpecularGlossinessMaterial, _super);
  37695. /**
  37696. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  37697. *
  37698. * @param name The material name
  37699. * @param scene The scene the material will be use in.
  37700. */
  37701. function PBRSpecularGlossinessMaterial(name, scene) {
  37702. var _this = _super.call(this, name, scene) || this;
  37703. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  37704. return _this;
  37705. }
  37706. /**
  37707. * Return the currrent class name of the material.
  37708. */
  37709. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  37710. return "PBRSpecularGlossinessMaterial";
  37711. };
  37712. /**
  37713. * Return the active textures of the material.
  37714. */
  37715. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  37716. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37717. if (this.diffuseTexture) {
  37718. activeTextures.push(this.diffuseTexture);
  37719. }
  37720. if (this.specularGlossinessTexture) {
  37721. activeTextures.push(this.specularGlossinessTexture);
  37722. }
  37723. return activeTextures;
  37724. };
  37725. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  37726. if (_super.prototype.hasTexture.call(this, texture)) {
  37727. return true;
  37728. }
  37729. if (this.diffuseTexture === texture) {
  37730. return true;
  37731. }
  37732. if (this.specularGlossinessTexture === texture) {
  37733. return true;
  37734. }
  37735. return false;
  37736. };
  37737. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  37738. var _this = this;
  37739. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  37740. clone.id = name;
  37741. clone.name = name;
  37742. return clone;
  37743. };
  37744. /**
  37745. * Serialize the material to a parsable JSON object.
  37746. */
  37747. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  37748. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  37749. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  37750. return serializationObject;
  37751. };
  37752. /**
  37753. * Parses a JSON object correponding to the serialize function.
  37754. */
  37755. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  37756. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  37757. };
  37758. __decorate([
  37759. BABYLON.serializeAsColor3("diffuse"),
  37760. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  37761. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  37762. __decorate([
  37763. BABYLON.serializeAsTexture(),
  37764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  37765. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  37766. __decorate([
  37767. BABYLON.serializeAsColor3("specular"),
  37768. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  37769. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  37770. __decorate([
  37771. BABYLON.serialize(),
  37772. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  37773. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  37774. __decorate([
  37775. BABYLON.serializeAsTexture(),
  37776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  37777. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  37778. return PBRSpecularGlossinessMaterial;
  37779. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  37780. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  37781. })(BABYLON || (BABYLON = {}));
  37782. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  37783. var BABYLON;
  37784. (function (BABYLON) {
  37785. BABYLON.CameraInputTypes = {};
  37786. var CameraInputsManager = /** @class */ (function () {
  37787. function CameraInputsManager(camera) {
  37788. this.attached = {};
  37789. this.camera = camera;
  37790. this.checkInputs = function () { };
  37791. }
  37792. CameraInputsManager.prototype.add = function (input) {
  37793. var type = input.getSimpleName();
  37794. if (this.attached[type]) {
  37795. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  37796. return;
  37797. }
  37798. this.attached[type] = input;
  37799. input.camera = this.camera;
  37800. //for checkInputs, we are dynamically creating a function
  37801. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  37802. if (input.checkInputs) {
  37803. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  37804. }
  37805. if (this.attachedElement) {
  37806. input.attachControl(this.attachedElement);
  37807. }
  37808. };
  37809. CameraInputsManager.prototype.remove = function (inputToRemove) {
  37810. for (var cam in this.attached) {
  37811. var input = this.attached[cam];
  37812. if (input === inputToRemove) {
  37813. input.detachControl(this.attachedElement);
  37814. input.camera = null;
  37815. delete this.attached[cam];
  37816. this.rebuildInputCheck();
  37817. }
  37818. }
  37819. };
  37820. CameraInputsManager.prototype.removeByType = function (inputType) {
  37821. for (var cam in this.attached) {
  37822. var input = this.attached[cam];
  37823. if (input.getClassName() === inputType) {
  37824. input.detachControl(this.attachedElement);
  37825. input.camera = null;
  37826. delete this.attached[cam];
  37827. this.rebuildInputCheck();
  37828. }
  37829. }
  37830. };
  37831. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  37832. var current = this.checkInputs;
  37833. return function () {
  37834. current();
  37835. fn();
  37836. };
  37837. };
  37838. CameraInputsManager.prototype.attachInput = function (input) {
  37839. if (this.attachedElement) {
  37840. input.attachControl(this.attachedElement, this.noPreventDefault);
  37841. }
  37842. };
  37843. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  37844. if (noPreventDefault === void 0) { noPreventDefault = false; }
  37845. if (this.attachedElement) {
  37846. return;
  37847. }
  37848. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  37849. this.attachedElement = element;
  37850. this.noPreventDefault = noPreventDefault;
  37851. for (var cam in this.attached) {
  37852. this.attached[cam].attachControl(element, noPreventDefault);
  37853. }
  37854. };
  37855. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  37856. if (disconnect === void 0) { disconnect = false; }
  37857. if (this.attachedElement !== element) {
  37858. return;
  37859. }
  37860. for (var cam in this.attached) {
  37861. this.attached[cam].detachControl(element);
  37862. if (disconnect) {
  37863. this.attached[cam].camera = null;
  37864. }
  37865. }
  37866. this.attachedElement = null;
  37867. };
  37868. CameraInputsManager.prototype.rebuildInputCheck = function () {
  37869. this.checkInputs = function () { };
  37870. for (var cam in this.attached) {
  37871. var input = this.attached[cam];
  37872. if (input.checkInputs) {
  37873. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  37874. }
  37875. }
  37876. };
  37877. CameraInputsManager.prototype.clear = function () {
  37878. if (this.attachedElement) {
  37879. this.detachElement(this.attachedElement, true);
  37880. }
  37881. this.attached = {};
  37882. this.attachedElement = null;
  37883. this.checkInputs = function () { };
  37884. };
  37885. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  37886. var inputs = {};
  37887. for (var cam in this.attached) {
  37888. var input = this.attached[cam];
  37889. var res = BABYLON.SerializationHelper.Serialize(input);
  37890. inputs[input.getClassName()] = res;
  37891. }
  37892. serializedCamera.inputsmgr = inputs;
  37893. };
  37894. CameraInputsManager.prototype.parse = function (parsedCamera) {
  37895. var parsedInputs = parsedCamera.inputsmgr;
  37896. if (parsedInputs) {
  37897. this.clear();
  37898. for (var n in parsedInputs) {
  37899. var construct = BABYLON.CameraInputTypes[n];
  37900. if (construct) {
  37901. var parsedinput = parsedInputs[n];
  37902. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  37903. this.add(input);
  37904. }
  37905. }
  37906. }
  37907. else {
  37908. //2016-03-08 this part is for managing backward compatibility
  37909. for (var n in this.attached) {
  37910. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  37911. if (construct) {
  37912. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  37913. this.remove(this.attached[n]);
  37914. this.add(input);
  37915. }
  37916. }
  37917. }
  37918. };
  37919. return CameraInputsManager;
  37920. }());
  37921. BABYLON.CameraInputsManager = CameraInputsManager;
  37922. })(BABYLON || (BABYLON = {}));
  37923. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  37924. var BABYLON;
  37925. (function (BABYLON) {
  37926. var FreeCameraMouseInput = /** @class */ (function () {
  37927. function FreeCameraMouseInput(touchEnabled) {
  37928. if (touchEnabled === void 0) { touchEnabled = true; }
  37929. this.touchEnabled = touchEnabled;
  37930. this.buttons = [0, 1, 2];
  37931. this.angularSensibility = 2000.0;
  37932. this.previousPosition = null;
  37933. }
  37934. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  37935. var _this = this;
  37936. var engine = this.camera.getEngine();
  37937. if (!this._pointerInput) {
  37938. this._pointerInput = function (p, s) {
  37939. var evt = p.event;
  37940. if (engine.isInVRExclusivePointerMode) {
  37941. return;
  37942. }
  37943. if (!_this.touchEnabled && evt.pointerType === "touch") {
  37944. return;
  37945. }
  37946. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  37947. return;
  37948. }
  37949. var srcElement = (evt.srcElement || evt.target);
  37950. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  37951. try {
  37952. srcElement.setPointerCapture(evt.pointerId);
  37953. }
  37954. catch (e) {
  37955. //Nothing to do with the error. Execution will continue.
  37956. }
  37957. _this.previousPosition = {
  37958. x: evt.clientX,
  37959. y: evt.clientY
  37960. };
  37961. if (!noPreventDefault) {
  37962. evt.preventDefault();
  37963. element.focus();
  37964. }
  37965. }
  37966. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  37967. try {
  37968. srcElement.releasePointerCapture(evt.pointerId);
  37969. }
  37970. catch (e) {
  37971. //Nothing to do with the error.
  37972. }
  37973. _this.previousPosition = null;
  37974. if (!noPreventDefault) {
  37975. evt.preventDefault();
  37976. }
  37977. }
  37978. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  37979. if (!_this.previousPosition || engine.isPointerLock) {
  37980. return;
  37981. }
  37982. var offsetX = evt.clientX - _this.previousPosition.x;
  37983. var offsetY = evt.clientY - _this.previousPosition.y;
  37984. if (_this.camera.getScene().useRightHandedSystem) {
  37985. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  37986. }
  37987. else {
  37988. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  37989. }
  37990. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  37991. _this.previousPosition = {
  37992. x: evt.clientX,
  37993. y: evt.clientY
  37994. };
  37995. if (!noPreventDefault) {
  37996. evt.preventDefault();
  37997. }
  37998. }
  37999. };
  38000. }
  38001. this._onMouseMove = function (evt) {
  38002. if (!engine.isPointerLock) {
  38003. return;
  38004. }
  38005. if (engine.isInVRExclusivePointerMode) {
  38006. return;
  38007. }
  38008. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  38009. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  38010. if (_this.camera.getScene().useRightHandedSystem) {
  38011. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  38012. }
  38013. else {
  38014. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  38015. }
  38016. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  38017. _this.previousPosition = null;
  38018. if (!noPreventDefault) {
  38019. evt.preventDefault();
  38020. }
  38021. };
  38022. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  38023. element.addEventListener("mousemove", this._onMouseMove, false);
  38024. };
  38025. FreeCameraMouseInput.prototype.detachControl = function (element) {
  38026. if (this._observer && element) {
  38027. this.camera.getScene().onPointerObservable.remove(this._observer);
  38028. if (this._onMouseMove) {
  38029. element.removeEventListener("mousemove", this._onMouseMove);
  38030. }
  38031. this._observer = null;
  38032. this._onMouseMove = null;
  38033. this.previousPosition = null;
  38034. }
  38035. };
  38036. FreeCameraMouseInput.prototype.getClassName = function () {
  38037. return "FreeCameraMouseInput";
  38038. };
  38039. FreeCameraMouseInput.prototype.getSimpleName = function () {
  38040. return "mouse";
  38041. };
  38042. __decorate([
  38043. BABYLON.serialize()
  38044. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  38045. __decorate([
  38046. BABYLON.serialize()
  38047. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  38048. return FreeCameraMouseInput;
  38049. }());
  38050. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  38051. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  38052. })(BABYLON || (BABYLON = {}));
  38053. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  38054. var BABYLON;
  38055. (function (BABYLON) {
  38056. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  38057. function FreeCameraKeyboardMoveInput() {
  38058. this._keys = new Array();
  38059. this.keysUp = [38];
  38060. this.keysDown = [40];
  38061. this.keysLeft = [37];
  38062. this.keysRight = [39];
  38063. }
  38064. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  38065. var _this = this;
  38066. if (this._onCanvasBlurObserver) {
  38067. return;
  38068. }
  38069. this._scene = this.camera.getScene();
  38070. this._engine = this._scene.getEngine();
  38071. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  38072. _this._keys = [];
  38073. });
  38074. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  38075. var evt = info.event;
  38076. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  38077. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  38078. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  38079. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  38080. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  38081. var index = _this._keys.indexOf(evt.keyCode);
  38082. if (index === -1) {
  38083. _this._keys.push(evt.keyCode);
  38084. }
  38085. if (!noPreventDefault) {
  38086. evt.preventDefault();
  38087. }
  38088. }
  38089. }
  38090. else {
  38091. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  38092. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  38093. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  38094. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  38095. var index = _this._keys.indexOf(evt.keyCode);
  38096. if (index >= 0) {
  38097. _this._keys.splice(index, 1);
  38098. }
  38099. if (!noPreventDefault) {
  38100. evt.preventDefault();
  38101. }
  38102. }
  38103. }
  38104. });
  38105. };
  38106. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  38107. if (this._scene) {
  38108. if (this._onKeyboardObserver) {
  38109. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  38110. }
  38111. if (this._onCanvasBlurObserver) {
  38112. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  38113. }
  38114. this._onKeyboardObserver = null;
  38115. this._onCanvasBlurObserver = null;
  38116. }
  38117. this._keys = [];
  38118. };
  38119. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  38120. if (this._onKeyboardObserver) {
  38121. var camera = this.camera;
  38122. // Keyboard
  38123. for (var index = 0; index < this._keys.length; index++) {
  38124. var keyCode = this._keys[index];
  38125. var speed = camera._computeLocalCameraSpeed();
  38126. if (this.keysLeft.indexOf(keyCode) !== -1) {
  38127. camera._localDirection.copyFromFloats(-speed, 0, 0);
  38128. }
  38129. else if (this.keysUp.indexOf(keyCode) !== -1) {
  38130. camera._localDirection.copyFromFloats(0, 0, speed);
  38131. }
  38132. else if (this.keysRight.indexOf(keyCode) !== -1) {
  38133. camera._localDirection.copyFromFloats(speed, 0, 0);
  38134. }
  38135. else if (this.keysDown.indexOf(keyCode) !== -1) {
  38136. camera._localDirection.copyFromFloats(0, 0, -speed);
  38137. }
  38138. if (camera.getScene().useRightHandedSystem) {
  38139. camera._localDirection.z *= -1;
  38140. }
  38141. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  38142. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  38143. camera.cameraDirection.addInPlace(camera._transformedDirection);
  38144. }
  38145. }
  38146. };
  38147. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  38148. return "FreeCameraKeyboardMoveInput";
  38149. };
  38150. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  38151. this._keys = [];
  38152. };
  38153. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  38154. return "keyboard";
  38155. };
  38156. __decorate([
  38157. BABYLON.serialize()
  38158. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  38159. __decorate([
  38160. BABYLON.serialize()
  38161. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  38162. __decorate([
  38163. BABYLON.serialize()
  38164. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  38165. __decorate([
  38166. BABYLON.serialize()
  38167. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  38168. return FreeCameraKeyboardMoveInput;
  38169. }());
  38170. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  38171. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  38172. })(BABYLON || (BABYLON = {}));
  38173. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  38174. var BABYLON;
  38175. (function (BABYLON) {
  38176. var FreeCameraInputsManager = /** @class */ (function (_super) {
  38177. __extends(FreeCameraInputsManager, _super);
  38178. function FreeCameraInputsManager(camera) {
  38179. return _super.call(this, camera) || this;
  38180. }
  38181. FreeCameraInputsManager.prototype.addKeyboard = function () {
  38182. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  38183. return this;
  38184. };
  38185. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  38186. if (touchEnabled === void 0) { touchEnabled = true; }
  38187. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  38188. return this;
  38189. };
  38190. FreeCameraInputsManager.prototype.addGamepad = function () {
  38191. this.add(new BABYLON.FreeCameraGamepadInput());
  38192. return this;
  38193. };
  38194. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  38195. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  38196. return this;
  38197. };
  38198. FreeCameraInputsManager.prototype.addTouch = function () {
  38199. this.add(new BABYLON.FreeCameraTouchInput());
  38200. return this;
  38201. };
  38202. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  38203. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  38204. return this;
  38205. };
  38206. return FreeCameraInputsManager;
  38207. }(BABYLON.CameraInputsManager));
  38208. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  38209. })(BABYLON || (BABYLON = {}));
  38210. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  38211. var BABYLON;
  38212. (function (BABYLON) {
  38213. var TargetCamera = /** @class */ (function (_super) {
  38214. __extends(TargetCamera, _super);
  38215. function TargetCamera(name, position, scene) {
  38216. var _this = _super.call(this, name, position, scene) || this;
  38217. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  38218. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  38219. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  38220. _this.speed = 2.0;
  38221. _this.noRotationConstraint = false;
  38222. _this.lockedTarget = null;
  38223. _this._currentTarget = BABYLON.Vector3.Zero();
  38224. _this._viewMatrix = BABYLON.Matrix.Zero();
  38225. _this._camMatrix = BABYLON.Matrix.Zero();
  38226. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  38227. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  38228. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  38229. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  38230. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  38231. _this._lookAtTemp = BABYLON.Matrix.Zero();
  38232. _this._tempMatrix = BABYLON.Matrix.Zero();
  38233. return _this;
  38234. }
  38235. TargetCamera.prototype.getFrontPosition = function (distance) {
  38236. var direction = this.getTarget().subtract(this.position);
  38237. direction.normalize();
  38238. direction.scaleInPlace(distance);
  38239. return this.globalPosition.add(direction);
  38240. };
  38241. TargetCamera.prototype._getLockedTargetPosition = function () {
  38242. if (!this.lockedTarget) {
  38243. return null;
  38244. }
  38245. if (this.lockedTarget.absolutePosition) {
  38246. this.lockedTarget.computeWorldMatrix();
  38247. }
  38248. return this.lockedTarget.absolutePosition || this.lockedTarget;
  38249. };
  38250. TargetCamera.prototype.storeState = function () {
  38251. this._storedPosition = this.position.clone();
  38252. this._storedRotation = this.rotation.clone();
  38253. if (this.rotationQuaternion) {
  38254. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  38255. }
  38256. return _super.prototype.storeState.call(this);
  38257. };
  38258. /**
  38259. * Restored camera state. You must call storeState() first
  38260. */
  38261. TargetCamera.prototype._restoreStateValues = function () {
  38262. if (!_super.prototype._restoreStateValues.call(this)) {
  38263. return false;
  38264. }
  38265. this.position = this._storedPosition.clone();
  38266. this.rotation = this._storedRotation.clone();
  38267. if (this.rotationQuaternion) {
  38268. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  38269. }
  38270. this.cameraDirection.copyFromFloats(0, 0, 0);
  38271. this.cameraRotation.copyFromFloats(0, 0);
  38272. return true;
  38273. };
  38274. // Cache
  38275. TargetCamera.prototype._initCache = function () {
  38276. _super.prototype._initCache.call(this);
  38277. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38278. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38279. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38280. };
  38281. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  38282. if (!ignoreParentClass) {
  38283. _super.prototype._updateCache.call(this);
  38284. }
  38285. var lockedTargetPosition = this._getLockedTargetPosition();
  38286. if (!lockedTargetPosition) {
  38287. this._cache.lockedTarget = null;
  38288. }
  38289. else {
  38290. if (!this._cache.lockedTarget) {
  38291. this._cache.lockedTarget = lockedTargetPosition.clone();
  38292. }
  38293. else {
  38294. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  38295. }
  38296. }
  38297. this._cache.rotation.copyFrom(this.rotation);
  38298. if (this.rotationQuaternion)
  38299. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  38300. };
  38301. // Synchronized
  38302. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  38303. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  38304. return false;
  38305. }
  38306. var lockedTargetPosition = this._getLockedTargetPosition();
  38307. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  38308. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  38309. };
  38310. // Methods
  38311. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  38312. var engine = this.getEngine();
  38313. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  38314. };
  38315. // Target
  38316. TargetCamera.prototype.setTarget = function (target) {
  38317. this.upVector.normalize();
  38318. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  38319. this._camMatrix.invert();
  38320. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  38321. var vDir = target.subtract(this.position);
  38322. if (vDir.x >= 0.0) {
  38323. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  38324. }
  38325. else {
  38326. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  38327. }
  38328. this.rotation.z = 0;
  38329. if (isNaN(this.rotation.x)) {
  38330. this.rotation.x = 0;
  38331. }
  38332. if (isNaN(this.rotation.y)) {
  38333. this.rotation.y = 0;
  38334. }
  38335. if (isNaN(this.rotation.z)) {
  38336. this.rotation.z = 0;
  38337. }
  38338. if (this.rotationQuaternion) {
  38339. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  38340. }
  38341. };
  38342. /**
  38343. * Return the current target position of the camera. This value is expressed in local space.
  38344. */
  38345. TargetCamera.prototype.getTarget = function () {
  38346. return this._currentTarget;
  38347. };
  38348. TargetCamera.prototype._decideIfNeedsToMove = function () {
  38349. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  38350. };
  38351. TargetCamera.prototype._updatePosition = function () {
  38352. if (this.parent) {
  38353. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  38354. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  38355. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  38356. return;
  38357. }
  38358. this.position.addInPlace(this.cameraDirection);
  38359. };
  38360. TargetCamera.prototype._checkInputs = function () {
  38361. var needToMove = this._decideIfNeedsToMove();
  38362. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  38363. // Move
  38364. if (needToMove) {
  38365. this._updatePosition();
  38366. }
  38367. // Rotate
  38368. if (needToRotate) {
  38369. this.rotation.x += this.cameraRotation.x;
  38370. this.rotation.y += this.cameraRotation.y;
  38371. //rotate, if quaternion is set and rotation was used
  38372. if (this.rotationQuaternion) {
  38373. var len = this.rotation.lengthSquared();
  38374. if (len) {
  38375. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  38376. }
  38377. }
  38378. if (!this.noRotationConstraint) {
  38379. var limit = (Math.PI / 2) * 0.95;
  38380. if (this.rotation.x > limit)
  38381. this.rotation.x = limit;
  38382. if (this.rotation.x < -limit)
  38383. this.rotation.x = -limit;
  38384. }
  38385. }
  38386. // Inertia
  38387. if (needToMove) {
  38388. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  38389. this.cameraDirection.x = 0;
  38390. }
  38391. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  38392. this.cameraDirection.y = 0;
  38393. }
  38394. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  38395. this.cameraDirection.z = 0;
  38396. }
  38397. this.cameraDirection.scaleInPlace(this.inertia);
  38398. }
  38399. if (needToRotate) {
  38400. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  38401. this.cameraRotation.x = 0;
  38402. }
  38403. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  38404. this.cameraRotation.y = 0;
  38405. }
  38406. this.cameraRotation.scaleInPlace(this.inertia);
  38407. }
  38408. _super.prototype._checkInputs.call(this);
  38409. };
  38410. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  38411. if (this.rotationQuaternion) {
  38412. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  38413. }
  38414. else {
  38415. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  38416. }
  38417. //update the up vector!
  38418. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  38419. };
  38420. TargetCamera.prototype._getViewMatrix = function () {
  38421. if (this.lockedTarget) {
  38422. this.setTarget(this._getLockedTargetPosition());
  38423. }
  38424. // Compute
  38425. this._updateCameraRotationMatrix();
  38426. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  38427. // Computing target and final matrix
  38428. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  38429. if (this.getScene().useRightHandedSystem) {
  38430. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  38431. }
  38432. else {
  38433. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  38434. }
  38435. return this._viewMatrix;
  38436. };
  38437. /**
  38438. * @override
  38439. * Override Camera.createRigCamera
  38440. */
  38441. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  38442. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  38443. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  38444. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  38445. if (!this.rotationQuaternion) {
  38446. this.rotationQuaternion = new BABYLON.Quaternion();
  38447. }
  38448. rigCamera._cameraRigParams = {};
  38449. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  38450. }
  38451. return rigCamera;
  38452. }
  38453. return null;
  38454. };
  38455. /**
  38456. * @override
  38457. * Override Camera._updateRigCameras
  38458. */
  38459. TargetCamera.prototype._updateRigCameras = function () {
  38460. var camLeft = this._rigCameras[0];
  38461. var camRight = this._rigCameras[1];
  38462. switch (this.cameraRigMode) {
  38463. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  38464. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  38465. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  38466. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  38467. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  38468. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  38469. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  38470. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  38471. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  38472. camLeft.setTarget(this.getTarget());
  38473. camRight.setTarget(this.getTarget());
  38474. break;
  38475. case BABYLON.Camera.RIG_MODE_VR:
  38476. if (camLeft.rotationQuaternion) {
  38477. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  38478. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  38479. }
  38480. else {
  38481. camLeft.rotation.copyFrom(this.rotation);
  38482. camRight.rotation.copyFrom(this.rotation);
  38483. }
  38484. camLeft.position.copyFrom(this.position);
  38485. camRight.position.copyFrom(this.position);
  38486. break;
  38487. }
  38488. _super.prototype._updateRigCameras.call(this);
  38489. };
  38490. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  38491. if (!this._rigCamTransformMatrix) {
  38492. this._rigCamTransformMatrix = new BABYLON.Matrix();
  38493. }
  38494. var target = this.getTarget();
  38495. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  38496. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  38497. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  38498. };
  38499. TargetCamera.prototype.getClassName = function () {
  38500. return "TargetCamera";
  38501. };
  38502. __decorate([
  38503. BABYLON.serializeAsVector3()
  38504. ], TargetCamera.prototype, "rotation", void 0);
  38505. __decorate([
  38506. BABYLON.serialize()
  38507. ], TargetCamera.prototype, "speed", void 0);
  38508. __decorate([
  38509. BABYLON.serializeAsMeshReference("lockedTargetId")
  38510. ], TargetCamera.prototype, "lockedTarget", void 0);
  38511. return TargetCamera;
  38512. }(BABYLON.Camera));
  38513. BABYLON.TargetCamera = TargetCamera;
  38514. })(BABYLON || (BABYLON = {}));
  38515. //# sourceMappingURL=babylon.targetCamera.js.map
  38516. var BABYLON;
  38517. (function (BABYLON) {
  38518. var FreeCamera = /** @class */ (function (_super) {
  38519. __extends(FreeCamera, _super);
  38520. function FreeCamera(name, position, scene) {
  38521. var _this = _super.call(this, name, position, scene) || this;
  38522. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  38523. _this.checkCollisions = false;
  38524. _this.applyGravity = false;
  38525. _this._needMoveForGravity = false;
  38526. _this._oldPosition = BABYLON.Vector3.Zero();
  38527. _this._diffPosition = BABYLON.Vector3.Zero();
  38528. _this._newPosition = BABYLON.Vector3.Zero();
  38529. // Collisions
  38530. _this._collisionMask = -1;
  38531. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  38532. if (collidedMesh === void 0) { collidedMesh = null; }
  38533. //TODO move this to the collision coordinator!
  38534. if (_this.getScene().workerCollisions)
  38535. newPosition.multiplyInPlace(_this._collider.radius);
  38536. var updatePosition = function (newPos) {
  38537. _this._newPosition.copyFrom(newPos);
  38538. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  38539. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  38540. _this.position.addInPlace(_this._diffPosition);
  38541. if (_this.onCollide && collidedMesh) {
  38542. _this.onCollide(collidedMesh);
  38543. }
  38544. }
  38545. };
  38546. updatePosition(newPosition);
  38547. };
  38548. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  38549. _this.inputs.addKeyboard().addMouse();
  38550. return _this;
  38551. }
  38552. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  38553. //-- begin properties for backward compatibility for inputs
  38554. get: function () {
  38555. var mouse = this.inputs.attached["mouse"];
  38556. if (mouse)
  38557. return mouse.angularSensibility;
  38558. return 0;
  38559. },
  38560. set: function (value) {
  38561. var mouse = this.inputs.attached["mouse"];
  38562. if (mouse)
  38563. mouse.angularSensibility = value;
  38564. },
  38565. enumerable: true,
  38566. configurable: true
  38567. });
  38568. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  38569. get: function () {
  38570. var keyboard = this.inputs.attached["keyboard"];
  38571. if (keyboard)
  38572. return keyboard.keysUp;
  38573. return [];
  38574. },
  38575. set: function (value) {
  38576. var keyboard = this.inputs.attached["keyboard"];
  38577. if (keyboard)
  38578. keyboard.keysUp = value;
  38579. },
  38580. enumerable: true,
  38581. configurable: true
  38582. });
  38583. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  38584. get: function () {
  38585. var keyboard = this.inputs.attached["keyboard"];
  38586. if (keyboard)
  38587. return keyboard.keysDown;
  38588. return [];
  38589. },
  38590. set: function (value) {
  38591. var keyboard = this.inputs.attached["keyboard"];
  38592. if (keyboard)
  38593. keyboard.keysDown = value;
  38594. },
  38595. enumerable: true,
  38596. configurable: true
  38597. });
  38598. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  38599. get: function () {
  38600. var keyboard = this.inputs.attached["keyboard"];
  38601. if (keyboard)
  38602. return keyboard.keysLeft;
  38603. return [];
  38604. },
  38605. set: function (value) {
  38606. var keyboard = this.inputs.attached["keyboard"];
  38607. if (keyboard)
  38608. keyboard.keysLeft = value;
  38609. },
  38610. enumerable: true,
  38611. configurable: true
  38612. });
  38613. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  38614. get: function () {
  38615. var keyboard = this.inputs.attached["keyboard"];
  38616. if (keyboard)
  38617. return keyboard.keysRight;
  38618. return [];
  38619. },
  38620. set: function (value) {
  38621. var keyboard = this.inputs.attached["keyboard"];
  38622. if (keyboard)
  38623. keyboard.keysRight = value;
  38624. },
  38625. enumerable: true,
  38626. configurable: true
  38627. });
  38628. // Controls
  38629. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  38630. this.inputs.attachElement(element, noPreventDefault);
  38631. };
  38632. FreeCamera.prototype.detachControl = function (element) {
  38633. this.inputs.detachElement(element);
  38634. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  38635. this.cameraRotation = new BABYLON.Vector2(0, 0);
  38636. };
  38637. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  38638. get: function () {
  38639. return this._collisionMask;
  38640. },
  38641. set: function (mask) {
  38642. this._collisionMask = !isNaN(mask) ? mask : -1;
  38643. },
  38644. enumerable: true,
  38645. configurable: true
  38646. });
  38647. FreeCamera.prototype._collideWithWorld = function (displacement) {
  38648. var globalPosition;
  38649. if (this.parent) {
  38650. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  38651. }
  38652. else {
  38653. globalPosition = this.position;
  38654. }
  38655. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  38656. if (!this._collider) {
  38657. this._collider = new BABYLON.Collider();
  38658. }
  38659. this._collider.radius = this.ellipsoid;
  38660. this._collider.collisionMask = this._collisionMask;
  38661. //no need for clone, as long as gravity is not on.
  38662. var actualDisplacement = displacement;
  38663. //add gravity to the direction to prevent the dual-collision checking
  38664. if (this.applyGravity) {
  38665. //this prevents mending with cameraDirection, a global variable of the free camera class.
  38666. actualDisplacement = displacement.add(this.getScene().gravity);
  38667. }
  38668. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  38669. };
  38670. FreeCamera.prototype._checkInputs = function () {
  38671. if (!this._localDirection) {
  38672. this._localDirection = BABYLON.Vector3.Zero();
  38673. this._transformedDirection = BABYLON.Vector3.Zero();
  38674. }
  38675. this.inputs.checkInputs();
  38676. _super.prototype._checkInputs.call(this);
  38677. };
  38678. FreeCamera.prototype._decideIfNeedsToMove = function () {
  38679. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  38680. };
  38681. FreeCamera.prototype._updatePosition = function () {
  38682. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  38683. this._collideWithWorld(this.cameraDirection);
  38684. }
  38685. else {
  38686. _super.prototype._updatePosition.call(this);
  38687. }
  38688. };
  38689. FreeCamera.prototype.dispose = function () {
  38690. this.inputs.clear();
  38691. _super.prototype.dispose.call(this);
  38692. };
  38693. FreeCamera.prototype.getClassName = function () {
  38694. return "FreeCamera";
  38695. };
  38696. __decorate([
  38697. BABYLON.serializeAsVector3()
  38698. ], FreeCamera.prototype, "ellipsoid", void 0);
  38699. __decorate([
  38700. BABYLON.serialize()
  38701. ], FreeCamera.prototype, "checkCollisions", void 0);
  38702. __decorate([
  38703. BABYLON.serialize()
  38704. ], FreeCamera.prototype, "applyGravity", void 0);
  38705. return FreeCamera;
  38706. }(BABYLON.TargetCamera));
  38707. BABYLON.FreeCamera = FreeCamera;
  38708. })(BABYLON || (BABYLON = {}));
  38709. //# sourceMappingURL=babylon.freeCamera.js.map
  38710. var BABYLON;
  38711. (function (BABYLON) {
  38712. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  38713. function ArcRotateCameraKeyboardMoveInput() {
  38714. this._keys = new Array();
  38715. this.keysUp = [38];
  38716. this.keysDown = [40];
  38717. this.keysLeft = [37];
  38718. this.keysRight = [39];
  38719. this.keysReset = [220];
  38720. this.panningSensibility = 50.0;
  38721. this.zoomingSensibility = 25.0;
  38722. this.useAltToZoom = true;
  38723. }
  38724. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  38725. var _this = this;
  38726. if (this._onCanvasBlurObserver) {
  38727. return;
  38728. }
  38729. this._scene = this.camera.getScene();
  38730. this._engine = this._scene.getEngine();
  38731. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  38732. _this._keys = [];
  38733. });
  38734. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  38735. var evt = info.event;
  38736. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  38737. _this._ctrlPressed = evt.ctrlKey;
  38738. _this._altPressed = evt.altKey;
  38739. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  38740. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  38741. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  38742. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  38743. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  38744. var index = _this._keys.indexOf(evt.keyCode);
  38745. if (index === -1) {
  38746. _this._keys.push(evt.keyCode);
  38747. }
  38748. if (evt.preventDefault) {
  38749. if (!noPreventDefault) {
  38750. evt.preventDefault();
  38751. }
  38752. }
  38753. }
  38754. }
  38755. else {
  38756. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  38757. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  38758. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  38759. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  38760. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  38761. var index = _this._keys.indexOf(evt.keyCode);
  38762. if (index >= 0) {
  38763. _this._keys.splice(index, 1);
  38764. }
  38765. if (evt.preventDefault) {
  38766. if (!noPreventDefault) {
  38767. evt.preventDefault();
  38768. }
  38769. }
  38770. }
  38771. }
  38772. });
  38773. };
  38774. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  38775. if (this._scene) {
  38776. if (this._onKeyboardObserver) {
  38777. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  38778. }
  38779. if (this._onCanvasBlurObserver) {
  38780. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  38781. }
  38782. this._onKeyboardObserver = null;
  38783. this._onCanvasBlurObserver = null;
  38784. }
  38785. this._keys = [];
  38786. };
  38787. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  38788. if (this._onKeyboardObserver) {
  38789. var camera = this.camera;
  38790. for (var index = 0; index < this._keys.length; index++) {
  38791. var keyCode = this._keys[index];
  38792. if (this.keysLeft.indexOf(keyCode) !== -1) {
  38793. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  38794. camera.inertialPanningX -= 1 / this.panningSensibility;
  38795. }
  38796. else {
  38797. camera.inertialAlphaOffset -= 0.01;
  38798. }
  38799. }
  38800. else if (this.keysUp.indexOf(keyCode) !== -1) {
  38801. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  38802. camera.inertialPanningY += 1 / this.panningSensibility;
  38803. }
  38804. else if (this._altPressed && this.useAltToZoom) {
  38805. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  38806. }
  38807. else {
  38808. camera.inertialBetaOffset -= 0.01;
  38809. }
  38810. }
  38811. else if (this.keysRight.indexOf(keyCode) !== -1) {
  38812. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  38813. camera.inertialPanningX += 1 / this.panningSensibility;
  38814. }
  38815. else {
  38816. camera.inertialAlphaOffset += 0.01;
  38817. }
  38818. }
  38819. else if (this.keysDown.indexOf(keyCode) !== -1) {
  38820. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  38821. camera.inertialPanningY -= 1 / this.panningSensibility;
  38822. }
  38823. else if (this._altPressed && this.useAltToZoom) {
  38824. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  38825. }
  38826. else {
  38827. camera.inertialBetaOffset += 0.01;
  38828. }
  38829. }
  38830. else if (this.keysReset.indexOf(keyCode) !== -1) {
  38831. camera.restoreState();
  38832. }
  38833. }
  38834. }
  38835. };
  38836. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  38837. return "ArcRotateCameraKeyboardMoveInput";
  38838. };
  38839. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  38840. return "keyboard";
  38841. };
  38842. __decorate([
  38843. BABYLON.serialize()
  38844. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  38845. __decorate([
  38846. BABYLON.serialize()
  38847. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  38848. __decorate([
  38849. BABYLON.serialize()
  38850. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  38851. __decorate([
  38852. BABYLON.serialize()
  38853. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  38854. __decorate([
  38855. BABYLON.serialize()
  38856. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  38857. __decorate([
  38858. BABYLON.serialize()
  38859. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  38860. __decorate([
  38861. BABYLON.serialize()
  38862. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  38863. __decorate([
  38864. BABYLON.serialize()
  38865. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  38866. return ArcRotateCameraKeyboardMoveInput;
  38867. }());
  38868. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  38869. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  38870. })(BABYLON || (BABYLON = {}));
  38871. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  38872. var BABYLON;
  38873. (function (BABYLON) {
  38874. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  38875. function ArcRotateCameraMouseWheelInput() {
  38876. this.wheelPrecision = 3.0;
  38877. /**
  38878. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  38879. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  38880. */
  38881. this.wheelDeltaPercentage = 0;
  38882. }
  38883. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  38884. var _this = this;
  38885. this._wheel = function (p, s) {
  38886. //sanity check - this should be a PointerWheel event.
  38887. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  38888. return;
  38889. var event = p.event;
  38890. var delta = 0;
  38891. if (event.wheelDelta) {
  38892. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  38893. }
  38894. else if (event.detail) {
  38895. delta = -event.detail / _this.wheelPrecision;
  38896. }
  38897. if (delta)
  38898. _this.camera.inertialRadiusOffset += delta;
  38899. if (event.preventDefault) {
  38900. if (!noPreventDefault) {
  38901. event.preventDefault();
  38902. }
  38903. }
  38904. };
  38905. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  38906. };
  38907. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  38908. if (this._observer && element) {
  38909. this.camera.getScene().onPointerObservable.remove(this._observer);
  38910. this._observer = null;
  38911. this._wheel = null;
  38912. }
  38913. };
  38914. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  38915. return "ArcRotateCameraMouseWheelInput";
  38916. };
  38917. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  38918. return "mousewheel";
  38919. };
  38920. __decorate([
  38921. BABYLON.serialize()
  38922. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  38923. __decorate([
  38924. BABYLON.serialize()
  38925. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  38926. return ArcRotateCameraMouseWheelInput;
  38927. }());
  38928. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  38929. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  38930. })(BABYLON || (BABYLON = {}));
  38931. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  38932. var BABYLON;
  38933. (function (BABYLON) {
  38934. var ArcRotateCameraPointersInput = /** @class */ (function () {
  38935. function ArcRotateCameraPointersInput() {
  38936. this.buttons = [0, 1, 2];
  38937. this.angularSensibilityX = 1000.0;
  38938. this.angularSensibilityY = 1000.0;
  38939. this.pinchPrecision = 12.0;
  38940. /**
  38941. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  38942. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  38943. */
  38944. this.pinchDeltaPercentage = 0;
  38945. this.panningSensibility = 1000.0;
  38946. this.multiTouchPanning = true;
  38947. this.multiTouchPanAndZoom = true;
  38948. this._isPanClick = false;
  38949. this.pinchInwards = true;
  38950. }
  38951. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  38952. var _this = this;
  38953. var engine = this.camera.getEngine();
  38954. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  38955. var pointA = null;
  38956. var pointB = null;
  38957. var previousPinchSquaredDistance = 0;
  38958. var initialDistance = 0;
  38959. var twoFingerActivityCount = 0;
  38960. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  38961. this._pointerInput = function (p, s) {
  38962. var evt = p.event;
  38963. var isTouch = p.event.pointerType === "touch";
  38964. if (engine.isInVRExclusivePointerMode) {
  38965. return;
  38966. }
  38967. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  38968. return;
  38969. }
  38970. var srcElement = (evt.srcElement || evt.target);
  38971. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  38972. try {
  38973. srcElement.setPointerCapture(evt.pointerId);
  38974. }
  38975. catch (e) {
  38976. //Nothing to do with the error. Execution will continue.
  38977. }
  38978. // Manage panning with pan button click
  38979. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  38980. // manage pointers
  38981. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  38982. if (pointA === null) {
  38983. pointA = cacheSoloPointer;
  38984. }
  38985. else if (pointB === null) {
  38986. pointB = cacheSoloPointer;
  38987. }
  38988. if (!noPreventDefault) {
  38989. evt.preventDefault();
  38990. element.focus();
  38991. }
  38992. }
  38993. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  38994. _this.camera.restoreState();
  38995. }
  38996. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  38997. try {
  38998. srcElement.releasePointerCapture(evt.pointerId);
  38999. }
  39000. catch (e) {
  39001. //Nothing to do with the error.
  39002. }
  39003. cacheSoloPointer = null;
  39004. previousPinchSquaredDistance = 0;
  39005. previousMultiTouchPanPosition.isPaning = false;
  39006. previousMultiTouchPanPosition.isPinching = false;
  39007. twoFingerActivityCount = 0;
  39008. initialDistance = 0;
  39009. if (!isTouch) {
  39010. pointB = null; // Mouse and pen are mono pointer
  39011. }
  39012. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  39013. //but emptying completly pointers collection is required to fix a bug on iPhone :
  39014. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  39015. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  39016. if (engine.badOS) {
  39017. pointA = pointB = null;
  39018. }
  39019. else {
  39020. //only remove the impacted pointer in case of multitouch allowing on most
  39021. //platforms switching from rotate to zoom and pan seamlessly.
  39022. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  39023. pointA = pointB;
  39024. pointB = null;
  39025. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  39026. }
  39027. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  39028. pointB = null;
  39029. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  39030. }
  39031. else {
  39032. pointA = pointB = null;
  39033. }
  39034. }
  39035. if (!noPreventDefault) {
  39036. evt.preventDefault();
  39037. }
  39038. }
  39039. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  39040. if (!noPreventDefault) {
  39041. evt.preventDefault();
  39042. }
  39043. // One button down
  39044. if (pointA && pointB === null && cacheSoloPointer) {
  39045. if (_this.panningSensibility !== 0 &&
  39046. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  39047. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  39048. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  39049. }
  39050. else {
  39051. var offsetX = evt.clientX - cacheSoloPointer.x;
  39052. var offsetY = evt.clientY - cacheSoloPointer.y;
  39053. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  39054. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  39055. }
  39056. cacheSoloPointer.x = evt.clientX;
  39057. cacheSoloPointer.y = evt.clientY;
  39058. }
  39059. else if (pointA && pointB) {
  39060. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  39061. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  39062. ed.x = evt.clientX;
  39063. ed.y = evt.clientY;
  39064. var direction = _this.pinchInwards ? 1 : -1;
  39065. var distX = pointA.x - pointB.x;
  39066. var distY = pointA.y - pointB.y;
  39067. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  39068. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  39069. if (previousPinchSquaredDistance === 0) {
  39070. initialDistance = pinchDistance;
  39071. previousPinchSquaredDistance = pinchSquaredDistance;
  39072. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  39073. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  39074. return;
  39075. }
  39076. if (_this.multiTouchPanAndZoom) {
  39077. if (_this.pinchDeltaPercentage) {
  39078. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  39079. }
  39080. else {
  39081. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  39082. (_this.pinchPrecision *
  39083. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  39084. direction);
  39085. }
  39086. if (_this.panningSensibility !== 0) {
  39087. var pointersCenterX = (pointA.x + pointB.x) / 2;
  39088. var pointersCenterY = (pointA.y + pointB.y) / 2;
  39089. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  39090. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  39091. previousMultiTouchPanPosition.x = pointersCenterX;
  39092. previousMultiTouchPanPosition.y = pointersCenterY;
  39093. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  39094. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  39095. }
  39096. }
  39097. else {
  39098. twoFingerActivityCount++;
  39099. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  39100. if (_this.pinchDeltaPercentage) {
  39101. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  39102. }
  39103. else {
  39104. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  39105. (_this.pinchPrecision *
  39106. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  39107. direction);
  39108. }
  39109. previousMultiTouchPanPosition.isPaning = false;
  39110. previousMultiTouchPanPosition.isPinching = true;
  39111. }
  39112. else {
  39113. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  39114. if (!previousMultiTouchPanPosition.isPaning) {
  39115. previousMultiTouchPanPosition.isPaning = true;
  39116. previousMultiTouchPanPosition.isPinching = false;
  39117. previousMultiTouchPanPosition.x = ed.x;
  39118. previousMultiTouchPanPosition.y = ed.y;
  39119. return;
  39120. }
  39121. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  39122. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  39123. }
  39124. }
  39125. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  39126. previousMultiTouchPanPosition.x = ed.x;
  39127. previousMultiTouchPanPosition.y = ed.y;
  39128. }
  39129. }
  39130. previousPinchSquaredDistance = pinchSquaredDistance;
  39131. }
  39132. }
  39133. };
  39134. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  39135. this._onContextMenu = function (evt) {
  39136. evt.preventDefault();
  39137. };
  39138. if (!this.camera._useCtrlForPanning) {
  39139. element.addEventListener("contextmenu", this._onContextMenu, false);
  39140. }
  39141. this._onLostFocus = function () {
  39142. //this._keys = [];
  39143. pointA = pointB = null;
  39144. previousPinchSquaredDistance = 0;
  39145. previousMultiTouchPanPosition.isPaning = false;
  39146. previousMultiTouchPanPosition.isPinching = false;
  39147. twoFingerActivityCount = 0;
  39148. cacheSoloPointer = null;
  39149. initialDistance = 0;
  39150. };
  39151. this._onMouseMove = function (evt) {
  39152. if (!engine.isPointerLock) {
  39153. return;
  39154. }
  39155. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  39156. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  39157. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  39158. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  39159. if (!noPreventDefault) {
  39160. evt.preventDefault();
  39161. }
  39162. };
  39163. this._onGestureStart = function (e) {
  39164. if (window.MSGesture === undefined) {
  39165. return;
  39166. }
  39167. if (!_this._MSGestureHandler) {
  39168. _this._MSGestureHandler = new MSGesture();
  39169. _this._MSGestureHandler.target = element;
  39170. }
  39171. _this._MSGestureHandler.addPointer(e.pointerId);
  39172. };
  39173. this._onGesture = function (e) {
  39174. _this.camera.radius *= e.scale;
  39175. if (e.preventDefault) {
  39176. if (!noPreventDefault) {
  39177. e.stopPropagation();
  39178. e.preventDefault();
  39179. }
  39180. }
  39181. };
  39182. element.addEventListener("mousemove", this._onMouseMove, false);
  39183. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  39184. element.addEventListener("MSGestureChange", this._onGesture, false);
  39185. BABYLON.Tools.RegisterTopRootEvents([
  39186. { name: "blur", handler: this._onLostFocus }
  39187. ]);
  39188. };
  39189. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  39190. if (this._onLostFocus) {
  39191. BABYLON.Tools.UnregisterTopRootEvents([
  39192. { name: "blur", handler: this._onLostFocus }
  39193. ]);
  39194. }
  39195. if (element && this._observer) {
  39196. this.camera.getScene().onPointerObservable.remove(this._observer);
  39197. this._observer = null;
  39198. if (this._onContextMenu) {
  39199. element.removeEventListener("contextmenu", this._onContextMenu);
  39200. }
  39201. if (this._onMouseMove) {
  39202. element.removeEventListener("mousemove", this._onMouseMove);
  39203. }
  39204. if (this._onGestureStart) {
  39205. element.removeEventListener("MSPointerDown", this._onGestureStart);
  39206. }
  39207. if (this._onGesture) {
  39208. element.removeEventListener("MSGestureChange", this._onGesture);
  39209. }
  39210. this._isPanClick = false;
  39211. this.pinchInwards = true;
  39212. this._onMouseMove = null;
  39213. this._onGestureStart = null;
  39214. this._onGesture = null;
  39215. this._MSGestureHandler = null;
  39216. this._onLostFocus = null;
  39217. this._onContextMenu = null;
  39218. }
  39219. };
  39220. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  39221. return "ArcRotateCameraPointersInput";
  39222. };
  39223. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  39224. return "pointers";
  39225. };
  39226. __decorate([
  39227. BABYLON.serialize()
  39228. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  39229. __decorate([
  39230. BABYLON.serialize()
  39231. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  39232. __decorate([
  39233. BABYLON.serialize()
  39234. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  39235. __decorate([
  39236. BABYLON.serialize()
  39237. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  39238. __decorate([
  39239. BABYLON.serialize()
  39240. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  39241. __decorate([
  39242. BABYLON.serialize()
  39243. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  39244. __decorate([
  39245. BABYLON.serialize()
  39246. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  39247. __decorate([
  39248. BABYLON.serialize()
  39249. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  39250. return ArcRotateCameraPointersInput;
  39251. }());
  39252. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  39253. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  39254. })(BABYLON || (BABYLON = {}));
  39255. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  39256. var BABYLON;
  39257. (function (BABYLON) {
  39258. var ArcRotateCamera = /** @class */ (function (_super) {
  39259. __extends(ArcRotateCamera, _super);
  39260. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  39261. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  39262. _this.inertialAlphaOffset = 0;
  39263. _this.inertialBetaOffset = 0;
  39264. _this.inertialRadiusOffset = 0;
  39265. _this.lowerAlphaLimit = null;
  39266. _this.upperAlphaLimit = null;
  39267. _this.lowerBetaLimit = 0.01;
  39268. _this.upperBetaLimit = Math.PI;
  39269. _this.lowerRadiusLimit = null;
  39270. _this.upperRadiusLimit = null;
  39271. _this.inertialPanningX = 0;
  39272. _this.inertialPanningY = 0;
  39273. _this.pinchToPanMaxDistance = 20;
  39274. _this.panningDistanceLimit = null;
  39275. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  39276. _this.panningInertia = 0.9;
  39277. //-- end properties for backward compatibility for inputs
  39278. _this.zoomOnFactor = 1;
  39279. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  39280. _this.allowUpsideDown = true;
  39281. _this._viewMatrix = new BABYLON.Matrix();
  39282. // Panning
  39283. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  39284. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  39285. _this.checkCollisions = false;
  39286. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  39287. _this._previousPosition = BABYLON.Vector3.Zero();
  39288. _this._collisionVelocity = BABYLON.Vector3.Zero();
  39289. _this._newPosition = BABYLON.Vector3.Zero();
  39290. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  39291. if (collidedMesh === void 0) { collidedMesh = null; }
  39292. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  39293. newPosition.multiplyInPlace(_this._collider.radius);
  39294. }
  39295. if (!collidedMesh) {
  39296. _this._previousPosition.copyFrom(_this.position);
  39297. }
  39298. else {
  39299. _this.setPosition(newPosition);
  39300. if (_this.onCollide) {
  39301. _this.onCollide(collidedMesh);
  39302. }
  39303. }
  39304. // Recompute because of constraints
  39305. var cosa = Math.cos(_this.alpha);
  39306. var sina = Math.sin(_this.alpha);
  39307. var cosb = Math.cos(_this.beta);
  39308. var sinb = Math.sin(_this.beta);
  39309. if (sinb === 0) {
  39310. sinb = 0.0001;
  39311. }
  39312. var target = _this._getTargetPosition();
  39313. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  39314. _this.position.copyFrom(_this._newPosition);
  39315. var up = _this.upVector;
  39316. if (_this.allowUpsideDown && _this.beta < 0) {
  39317. up = up.clone();
  39318. up = up.negate();
  39319. }
  39320. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  39321. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  39322. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  39323. _this._collisionTriggered = false;
  39324. };
  39325. _this._target = BABYLON.Vector3.Zero();
  39326. if (target) {
  39327. _this.setTarget(target);
  39328. }
  39329. _this.alpha = alpha;
  39330. _this.beta = beta;
  39331. _this.radius = radius;
  39332. _this.getViewMatrix();
  39333. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  39334. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  39335. return _this;
  39336. }
  39337. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  39338. get: function () {
  39339. return this._target;
  39340. },
  39341. set: function (value) {
  39342. this.setTarget(value);
  39343. },
  39344. enumerable: true,
  39345. configurable: true
  39346. });
  39347. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  39348. //-- begin properties for backward compatibility for inputs
  39349. get: function () {
  39350. var pointers = this.inputs.attached["pointers"];
  39351. if (pointers)
  39352. return pointers.angularSensibilityX;
  39353. return 0;
  39354. },
  39355. set: function (value) {
  39356. var pointers = this.inputs.attached["pointers"];
  39357. if (pointers) {
  39358. pointers.angularSensibilityX = value;
  39359. }
  39360. },
  39361. enumerable: true,
  39362. configurable: true
  39363. });
  39364. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  39365. get: function () {
  39366. var pointers = this.inputs.attached["pointers"];
  39367. if (pointers)
  39368. return pointers.angularSensibilityY;
  39369. return 0;
  39370. },
  39371. set: function (value) {
  39372. var pointers = this.inputs.attached["pointers"];
  39373. if (pointers) {
  39374. pointers.angularSensibilityY = value;
  39375. }
  39376. },
  39377. enumerable: true,
  39378. configurable: true
  39379. });
  39380. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  39381. get: function () {
  39382. var pointers = this.inputs.attached["pointers"];
  39383. if (pointers)
  39384. return pointers.pinchPrecision;
  39385. return 0;
  39386. },
  39387. set: function (value) {
  39388. var pointers = this.inputs.attached["pointers"];
  39389. if (pointers) {
  39390. pointers.pinchPrecision = value;
  39391. }
  39392. },
  39393. enumerable: true,
  39394. configurable: true
  39395. });
  39396. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  39397. get: function () {
  39398. var pointers = this.inputs.attached["pointers"];
  39399. if (pointers)
  39400. return pointers.pinchDeltaPercentage;
  39401. return 0;
  39402. },
  39403. set: function (value) {
  39404. var pointers = this.inputs.attached["pointers"];
  39405. if (pointers) {
  39406. pointers.pinchDeltaPercentage = value;
  39407. }
  39408. },
  39409. enumerable: true,
  39410. configurable: true
  39411. });
  39412. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  39413. get: function () {
  39414. var pointers = this.inputs.attached["pointers"];
  39415. if (pointers)
  39416. return pointers.panningSensibility;
  39417. return 0;
  39418. },
  39419. set: function (value) {
  39420. var pointers = this.inputs.attached["pointers"];
  39421. if (pointers) {
  39422. pointers.panningSensibility = value;
  39423. }
  39424. },
  39425. enumerable: true,
  39426. configurable: true
  39427. });
  39428. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  39429. get: function () {
  39430. var keyboard = this.inputs.attached["keyboard"];
  39431. if (keyboard)
  39432. return keyboard.keysUp;
  39433. return [];
  39434. },
  39435. set: function (value) {
  39436. var keyboard = this.inputs.attached["keyboard"];
  39437. if (keyboard)
  39438. keyboard.keysUp = value;
  39439. },
  39440. enumerable: true,
  39441. configurable: true
  39442. });
  39443. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  39444. get: function () {
  39445. var keyboard = this.inputs.attached["keyboard"];
  39446. if (keyboard)
  39447. return keyboard.keysDown;
  39448. return [];
  39449. },
  39450. set: function (value) {
  39451. var keyboard = this.inputs.attached["keyboard"];
  39452. if (keyboard)
  39453. keyboard.keysDown = value;
  39454. },
  39455. enumerable: true,
  39456. configurable: true
  39457. });
  39458. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  39459. get: function () {
  39460. var keyboard = this.inputs.attached["keyboard"];
  39461. if (keyboard)
  39462. return keyboard.keysLeft;
  39463. return [];
  39464. },
  39465. set: function (value) {
  39466. var keyboard = this.inputs.attached["keyboard"];
  39467. if (keyboard)
  39468. keyboard.keysLeft = value;
  39469. },
  39470. enumerable: true,
  39471. configurable: true
  39472. });
  39473. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  39474. get: function () {
  39475. var keyboard = this.inputs.attached["keyboard"];
  39476. if (keyboard)
  39477. return keyboard.keysRight;
  39478. return [];
  39479. },
  39480. set: function (value) {
  39481. var keyboard = this.inputs.attached["keyboard"];
  39482. if (keyboard)
  39483. keyboard.keysRight = value;
  39484. },
  39485. enumerable: true,
  39486. configurable: true
  39487. });
  39488. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  39489. get: function () {
  39490. var mousewheel = this.inputs.attached["mousewheel"];
  39491. if (mousewheel)
  39492. return mousewheel.wheelPrecision;
  39493. return 0;
  39494. },
  39495. set: function (value) {
  39496. var mousewheel = this.inputs.attached["mousewheel"];
  39497. if (mousewheel)
  39498. mousewheel.wheelPrecision = value;
  39499. },
  39500. enumerable: true,
  39501. configurable: true
  39502. });
  39503. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  39504. get: function () {
  39505. var mousewheel = this.inputs.attached["mousewheel"];
  39506. if (mousewheel)
  39507. return mousewheel.wheelDeltaPercentage;
  39508. return 0;
  39509. },
  39510. set: function (value) {
  39511. var mousewheel = this.inputs.attached["mousewheel"];
  39512. if (mousewheel)
  39513. mousewheel.wheelDeltaPercentage = value;
  39514. },
  39515. enumerable: true,
  39516. configurable: true
  39517. });
  39518. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  39519. get: function () {
  39520. return this._bouncingBehavior;
  39521. },
  39522. enumerable: true,
  39523. configurable: true
  39524. });
  39525. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  39526. get: function () {
  39527. return this._bouncingBehavior != null;
  39528. },
  39529. set: function (value) {
  39530. if (value === this.useBouncingBehavior) {
  39531. return;
  39532. }
  39533. if (value) {
  39534. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  39535. this.addBehavior(this._bouncingBehavior);
  39536. }
  39537. else if (this._bouncingBehavior) {
  39538. this.removeBehavior(this._bouncingBehavior);
  39539. this._bouncingBehavior = null;
  39540. }
  39541. },
  39542. enumerable: true,
  39543. configurable: true
  39544. });
  39545. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  39546. get: function () {
  39547. return this._framingBehavior;
  39548. },
  39549. enumerable: true,
  39550. configurable: true
  39551. });
  39552. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  39553. get: function () {
  39554. return this._framingBehavior != null;
  39555. },
  39556. set: function (value) {
  39557. if (value === this.useFramingBehavior) {
  39558. return;
  39559. }
  39560. if (value) {
  39561. this._framingBehavior = new BABYLON.FramingBehavior();
  39562. this.addBehavior(this._framingBehavior);
  39563. }
  39564. else if (this._framingBehavior) {
  39565. this.removeBehavior(this._framingBehavior);
  39566. this._framingBehavior = null;
  39567. }
  39568. },
  39569. enumerable: true,
  39570. configurable: true
  39571. });
  39572. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  39573. get: function () {
  39574. return this._autoRotationBehavior;
  39575. },
  39576. enumerable: true,
  39577. configurable: true
  39578. });
  39579. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  39580. get: function () {
  39581. return this._autoRotationBehavior != null;
  39582. },
  39583. set: function (value) {
  39584. if (value === this.useAutoRotationBehavior) {
  39585. return;
  39586. }
  39587. if (value) {
  39588. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  39589. this.addBehavior(this._autoRotationBehavior);
  39590. }
  39591. else if (this._autoRotationBehavior) {
  39592. this.removeBehavior(this._autoRotationBehavior);
  39593. this._autoRotationBehavior = null;
  39594. }
  39595. },
  39596. enumerable: true,
  39597. configurable: true
  39598. });
  39599. // Cache
  39600. ArcRotateCamera.prototype._initCache = function () {
  39601. _super.prototype._initCache.call(this);
  39602. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  39603. this._cache.alpha = undefined;
  39604. this._cache.beta = undefined;
  39605. this._cache.radius = undefined;
  39606. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  39607. };
  39608. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  39609. if (!ignoreParentClass) {
  39610. _super.prototype._updateCache.call(this);
  39611. }
  39612. this._cache._target.copyFrom(this._getTargetPosition());
  39613. this._cache.alpha = this.alpha;
  39614. this._cache.beta = this.beta;
  39615. this._cache.radius = this.radius;
  39616. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  39617. };
  39618. ArcRotateCamera.prototype._getTargetPosition = function () {
  39619. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  39620. var pos = this._targetHost.getAbsolutePosition();
  39621. if (this._targetBoundingCenter) {
  39622. pos.addToRef(this._targetBoundingCenter, this._target);
  39623. }
  39624. else {
  39625. this._target.copyFrom(pos);
  39626. }
  39627. }
  39628. var lockedTargetPosition = this._getLockedTargetPosition();
  39629. if (lockedTargetPosition) {
  39630. return lockedTargetPosition;
  39631. }
  39632. return this._target;
  39633. };
  39634. ArcRotateCamera.prototype.storeState = function () {
  39635. this._storedAlpha = this.alpha;
  39636. this._storedBeta = this.beta;
  39637. this._storedRadius = this.radius;
  39638. this._storedTarget = this._getTargetPosition().clone();
  39639. return _super.prototype.storeState.call(this);
  39640. };
  39641. /**
  39642. * Restored camera state. You must call storeState() first
  39643. */
  39644. ArcRotateCamera.prototype._restoreStateValues = function () {
  39645. if (!_super.prototype._restoreStateValues.call(this)) {
  39646. return false;
  39647. }
  39648. this.alpha = this._storedAlpha;
  39649. this.beta = this._storedBeta;
  39650. this.radius = this._storedRadius;
  39651. this.setTarget(this._storedTarget.clone());
  39652. this.inertialAlphaOffset = 0;
  39653. this.inertialBetaOffset = 0;
  39654. this.inertialRadiusOffset = 0;
  39655. this.inertialPanningX = 0;
  39656. this.inertialPanningY = 0;
  39657. return true;
  39658. };
  39659. // Synchronized
  39660. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  39661. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  39662. return false;
  39663. return this._cache._target.equals(this._getTargetPosition())
  39664. && this._cache.alpha === this.alpha
  39665. && this._cache.beta === this.beta
  39666. && this._cache.radius === this.radius
  39667. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  39668. };
  39669. // Methods
  39670. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  39671. var _this = this;
  39672. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  39673. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  39674. this._useCtrlForPanning = useCtrlForPanning;
  39675. this._panningMouseButton = panningMouseButton;
  39676. this.inputs.attachElement(element, noPreventDefault);
  39677. this._reset = function () {
  39678. _this.inertialAlphaOffset = 0;
  39679. _this.inertialBetaOffset = 0;
  39680. _this.inertialRadiusOffset = 0;
  39681. _this.inertialPanningX = 0;
  39682. _this.inertialPanningY = 0;
  39683. };
  39684. };
  39685. ArcRotateCamera.prototype.detachControl = function (element) {
  39686. this.inputs.detachElement(element);
  39687. if (this._reset) {
  39688. this._reset();
  39689. }
  39690. };
  39691. ArcRotateCamera.prototype._checkInputs = function () {
  39692. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  39693. if (this._collisionTriggered) {
  39694. return;
  39695. }
  39696. this.inputs.checkInputs();
  39697. // Inertia
  39698. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  39699. if (this.getScene().useRightHandedSystem) {
  39700. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  39701. }
  39702. else {
  39703. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  39704. }
  39705. this.beta += this.inertialBetaOffset;
  39706. this.radius -= this.inertialRadiusOffset;
  39707. this.inertialAlphaOffset *= this.inertia;
  39708. this.inertialBetaOffset *= this.inertia;
  39709. this.inertialRadiusOffset *= this.inertia;
  39710. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  39711. this.inertialAlphaOffset = 0;
  39712. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  39713. this.inertialBetaOffset = 0;
  39714. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  39715. this.inertialRadiusOffset = 0;
  39716. }
  39717. // Panning inertia
  39718. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  39719. if (!this._localDirection) {
  39720. this._localDirection = BABYLON.Vector3.Zero();
  39721. this._transformedDirection = BABYLON.Vector3.Zero();
  39722. }
  39723. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  39724. this._localDirection.multiplyInPlace(this.panningAxis);
  39725. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  39726. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  39727. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  39728. if (!this.panningAxis.y) {
  39729. this._transformedDirection.y = 0;
  39730. }
  39731. if (!this._targetHost) {
  39732. if (this.panningDistanceLimit) {
  39733. this._transformedDirection.addInPlace(this._target);
  39734. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  39735. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  39736. this._target.copyFrom(this._transformedDirection);
  39737. }
  39738. }
  39739. else {
  39740. this._target.addInPlace(this._transformedDirection);
  39741. }
  39742. }
  39743. this.inertialPanningX *= this.panningInertia;
  39744. this.inertialPanningY *= this.panningInertia;
  39745. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  39746. this.inertialPanningX = 0;
  39747. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  39748. this.inertialPanningY = 0;
  39749. }
  39750. // Limits
  39751. this._checkLimits();
  39752. _super.prototype._checkInputs.call(this);
  39753. };
  39754. ArcRotateCamera.prototype._checkLimits = function () {
  39755. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  39756. if (this.allowUpsideDown && this.beta > Math.PI) {
  39757. this.beta = this.beta - (2 * Math.PI);
  39758. }
  39759. }
  39760. else {
  39761. if (this.beta < this.lowerBetaLimit) {
  39762. this.beta = this.lowerBetaLimit;
  39763. }
  39764. }
  39765. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  39766. if (this.allowUpsideDown && this.beta < -Math.PI) {
  39767. this.beta = this.beta + (2 * Math.PI);
  39768. }
  39769. }
  39770. else {
  39771. if (this.beta > this.upperBetaLimit) {
  39772. this.beta = this.upperBetaLimit;
  39773. }
  39774. }
  39775. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  39776. this.alpha = this.lowerAlphaLimit;
  39777. }
  39778. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  39779. this.alpha = this.upperAlphaLimit;
  39780. }
  39781. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  39782. this.radius = this.lowerRadiusLimit;
  39783. }
  39784. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  39785. this.radius = this.upperRadiusLimit;
  39786. }
  39787. };
  39788. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  39789. var radiusv3 = this.position.subtract(this._getTargetPosition());
  39790. this.radius = radiusv3.length();
  39791. if (this.radius === 0) {
  39792. this.radius = 0.0001; // Just to avoid division by zero
  39793. }
  39794. // Alpha
  39795. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  39796. if (radiusv3.z < 0) {
  39797. this.alpha = 2 * Math.PI - this.alpha;
  39798. }
  39799. // Beta
  39800. this.beta = Math.acos(radiusv3.y / this.radius);
  39801. this._checkLimits();
  39802. };
  39803. ArcRotateCamera.prototype.setPosition = function (position) {
  39804. if (this.position.equals(position)) {
  39805. return;
  39806. }
  39807. this.position.copyFrom(position);
  39808. this.rebuildAnglesAndRadius();
  39809. };
  39810. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  39811. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  39812. if (allowSamePosition === void 0) { allowSamePosition = false; }
  39813. if (target.getBoundingInfo) {
  39814. if (toBoundingCenter) {
  39815. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  39816. }
  39817. else {
  39818. this._targetBoundingCenter = null;
  39819. }
  39820. this._targetHost = target;
  39821. this._target = this._getTargetPosition();
  39822. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  39823. }
  39824. else {
  39825. var newTarget = target;
  39826. var currentTarget = this._getTargetPosition();
  39827. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  39828. return;
  39829. }
  39830. this._targetHost = null;
  39831. this._target = newTarget;
  39832. this._targetBoundingCenter = null;
  39833. this.onMeshTargetChangedObservable.notifyObservers(null);
  39834. }
  39835. this.rebuildAnglesAndRadius();
  39836. };
  39837. ArcRotateCamera.prototype._getViewMatrix = function () {
  39838. // Compute
  39839. var cosa = Math.cos(this.alpha);
  39840. var sina = Math.sin(this.alpha);
  39841. var cosb = Math.cos(this.beta);
  39842. var sinb = Math.sin(this.beta);
  39843. if (sinb === 0) {
  39844. sinb = 0.0001;
  39845. }
  39846. var target = this._getTargetPosition();
  39847. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  39848. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  39849. if (!this._collider) {
  39850. this._collider = new BABYLON.Collider();
  39851. }
  39852. this._collider.radius = this.collisionRadius;
  39853. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  39854. this._collisionTriggered = true;
  39855. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  39856. }
  39857. else {
  39858. this.position.copyFrom(this._newPosition);
  39859. var up = this.upVector;
  39860. if (this.allowUpsideDown && sinb < 0) {
  39861. up = up.clone();
  39862. up = up.negate();
  39863. }
  39864. if (this.getScene().useRightHandedSystem) {
  39865. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  39866. }
  39867. else {
  39868. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  39869. }
  39870. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  39871. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  39872. }
  39873. this._currentTarget = target;
  39874. return this._viewMatrix;
  39875. };
  39876. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  39877. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  39878. meshes = meshes || this.getScene().meshes;
  39879. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  39880. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  39881. this.radius = distance * this.zoomOnFactor;
  39882. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  39883. };
  39884. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  39885. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  39886. var meshesOrMinMaxVector;
  39887. var distance;
  39888. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  39889. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  39890. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  39891. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  39892. }
  39893. else {
  39894. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  39895. meshesOrMinMaxVector = minMaxVectorAndDistance;
  39896. distance = minMaxVectorAndDistance.distance;
  39897. }
  39898. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  39899. if (!doNotUpdateMaxZ) {
  39900. this.maxZ = distance * 2;
  39901. }
  39902. };
  39903. /**
  39904. * @override
  39905. * Override Camera.createRigCamera
  39906. */
  39907. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  39908. var alphaShift = 0;
  39909. switch (this.cameraRigMode) {
  39910. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  39911. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  39912. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  39913. case BABYLON.Camera.RIG_MODE_VR:
  39914. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  39915. break;
  39916. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  39917. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  39918. break;
  39919. }
  39920. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  39921. rigCam._cameraRigParams = {};
  39922. return rigCam;
  39923. };
  39924. /**
  39925. * @override
  39926. * Override Camera._updateRigCameras
  39927. */
  39928. ArcRotateCamera.prototype._updateRigCameras = function () {
  39929. var camLeft = this._rigCameras[0];
  39930. var camRight = this._rigCameras[1];
  39931. camLeft.beta = camRight.beta = this.beta;
  39932. camLeft.radius = camRight.radius = this.radius;
  39933. switch (this.cameraRigMode) {
  39934. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  39935. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  39936. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  39937. case BABYLON.Camera.RIG_MODE_VR:
  39938. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  39939. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  39940. break;
  39941. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  39942. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  39943. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  39944. break;
  39945. }
  39946. _super.prototype._updateRigCameras.call(this);
  39947. };
  39948. ArcRotateCamera.prototype.dispose = function () {
  39949. this.inputs.clear();
  39950. _super.prototype.dispose.call(this);
  39951. };
  39952. ArcRotateCamera.prototype.getClassName = function () {
  39953. return "ArcRotateCamera";
  39954. };
  39955. __decorate([
  39956. BABYLON.serialize()
  39957. ], ArcRotateCamera.prototype, "alpha", void 0);
  39958. __decorate([
  39959. BABYLON.serialize()
  39960. ], ArcRotateCamera.prototype, "beta", void 0);
  39961. __decorate([
  39962. BABYLON.serialize()
  39963. ], ArcRotateCamera.prototype, "radius", void 0);
  39964. __decorate([
  39965. BABYLON.serializeAsVector3("target")
  39966. ], ArcRotateCamera.prototype, "_target", void 0);
  39967. __decorate([
  39968. BABYLON.serialize()
  39969. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  39970. __decorate([
  39971. BABYLON.serialize()
  39972. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  39973. __decorate([
  39974. BABYLON.serialize()
  39975. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  39976. __decorate([
  39977. BABYLON.serialize()
  39978. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  39979. __decorate([
  39980. BABYLON.serialize()
  39981. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  39982. __decorate([
  39983. BABYLON.serialize()
  39984. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  39985. __decorate([
  39986. BABYLON.serialize()
  39987. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  39988. __decorate([
  39989. BABYLON.serialize()
  39990. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  39991. __decorate([
  39992. BABYLON.serialize()
  39993. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  39994. __decorate([
  39995. BABYLON.serialize()
  39996. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  39997. __decorate([
  39998. BABYLON.serialize()
  39999. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  40000. __decorate([
  40001. BABYLON.serialize()
  40002. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  40003. __decorate([
  40004. BABYLON.serialize()
  40005. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  40006. __decorate([
  40007. BABYLON.serializeAsVector3()
  40008. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  40009. __decorate([
  40010. BABYLON.serialize()
  40011. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  40012. __decorate([
  40013. BABYLON.serialize()
  40014. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  40015. __decorate([
  40016. BABYLON.serialize()
  40017. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  40018. return ArcRotateCamera;
  40019. }(BABYLON.TargetCamera));
  40020. BABYLON.ArcRotateCamera = ArcRotateCamera;
  40021. })(BABYLON || (BABYLON = {}));
  40022. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  40023. var BABYLON;
  40024. (function (BABYLON) {
  40025. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  40026. __extends(ArcRotateCameraInputsManager, _super);
  40027. function ArcRotateCameraInputsManager(camera) {
  40028. return _super.call(this, camera) || this;
  40029. }
  40030. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  40031. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  40032. return this;
  40033. };
  40034. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  40035. this.add(new BABYLON.ArcRotateCameraPointersInput());
  40036. return this;
  40037. };
  40038. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  40039. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  40040. return this;
  40041. };
  40042. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  40043. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  40044. return this;
  40045. };
  40046. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  40047. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  40048. return this;
  40049. };
  40050. return ArcRotateCameraInputsManager;
  40051. }(BABYLON.CameraInputsManager));
  40052. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  40053. })(BABYLON || (BABYLON = {}));
  40054. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  40055. var BABYLON;
  40056. (function (BABYLON) {
  40057. var HemisphericLight = /** @class */ (function (_super) {
  40058. __extends(HemisphericLight, _super);
  40059. /**
  40060. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  40061. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  40062. * The HemisphericLight can't cast shadows.
  40063. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40064. */
  40065. function HemisphericLight(name, direction, scene) {
  40066. var _this = _super.call(this, name, scene) || this;
  40067. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  40068. _this.direction = direction || BABYLON.Vector3.Up();
  40069. return _this;
  40070. }
  40071. HemisphericLight.prototype._buildUniformLayout = function () {
  40072. this._uniformBuffer.addUniform("vLightData", 4);
  40073. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40074. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40075. this._uniformBuffer.addUniform("vLightGround", 3);
  40076. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40077. this._uniformBuffer.addUniform("depthValues", 2);
  40078. this._uniformBuffer.create();
  40079. };
  40080. /**
  40081. * Returns the string "HemisphericLight".
  40082. */
  40083. HemisphericLight.prototype.getClassName = function () {
  40084. return "HemisphericLight";
  40085. };
  40086. /**
  40087. * Sets the HemisphericLight direction towards the passed target (Vector3).
  40088. * Returns the updated direction.
  40089. */
  40090. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  40091. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  40092. return this.direction;
  40093. };
  40094. HemisphericLight.prototype.getShadowGenerator = function () {
  40095. return null;
  40096. };
  40097. /**
  40098. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  40099. * Returns the HemisphericLight.
  40100. */
  40101. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  40102. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  40103. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  40104. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  40105. return this;
  40106. };
  40107. HemisphericLight.prototype._getWorldMatrix = function () {
  40108. if (!this._worldMatrix) {
  40109. this._worldMatrix = BABYLON.Matrix.Identity();
  40110. }
  40111. return this._worldMatrix;
  40112. };
  40113. /**
  40114. * Returns the integer 3.
  40115. */
  40116. HemisphericLight.prototype.getTypeID = function () {
  40117. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  40118. };
  40119. __decorate([
  40120. BABYLON.serializeAsColor3()
  40121. ], HemisphericLight.prototype, "groundColor", void 0);
  40122. __decorate([
  40123. BABYLON.serializeAsVector3()
  40124. ], HemisphericLight.prototype, "direction", void 0);
  40125. return HemisphericLight;
  40126. }(BABYLON.Light));
  40127. BABYLON.HemisphericLight = HemisphericLight;
  40128. })(BABYLON || (BABYLON = {}));
  40129. //# sourceMappingURL=babylon.hemisphericLight.js.map
  40130. var BABYLON;
  40131. (function (BABYLON) {
  40132. var ShadowLight = /** @class */ (function (_super) {
  40133. __extends(ShadowLight, _super);
  40134. function ShadowLight() {
  40135. var _this = _super !== null && _super.apply(this, arguments) || this;
  40136. _this._needProjectionMatrixCompute = true;
  40137. return _this;
  40138. }
  40139. Object.defineProperty(ShadowLight.prototype, "direction", {
  40140. get: function () {
  40141. return this._direction;
  40142. },
  40143. set: function (value) {
  40144. this._direction = value;
  40145. },
  40146. enumerable: true,
  40147. configurable: true
  40148. });
  40149. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  40150. get: function () {
  40151. return this._shadowMinZ;
  40152. },
  40153. set: function (value) {
  40154. this._shadowMinZ = value;
  40155. this.forceProjectionMatrixCompute();
  40156. },
  40157. enumerable: true,
  40158. configurable: true
  40159. });
  40160. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  40161. get: function () {
  40162. return this._shadowMaxZ;
  40163. },
  40164. set: function (value) {
  40165. this._shadowMaxZ = value;
  40166. this.forceProjectionMatrixCompute();
  40167. },
  40168. enumerable: true,
  40169. configurable: true
  40170. });
  40171. /**
  40172. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  40173. */
  40174. ShadowLight.prototype.computeTransformedInformation = function () {
  40175. if (this.parent && this.parent.getWorldMatrix) {
  40176. if (!this.transformedPosition) {
  40177. this.transformedPosition = BABYLON.Vector3.Zero();
  40178. }
  40179. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  40180. // In case the direction is present.
  40181. if (this.direction) {
  40182. if (!this.transformedDirection) {
  40183. this.transformedDirection = BABYLON.Vector3.Zero();
  40184. }
  40185. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  40186. }
  40187. return true;
  40188. }
  40189. return false;
  40190. };
  40191. /**
  40192. * Return the depth scale used for the shadow map.
  40193. */
  40194. ShadowLight.prototype.getDepthScale = function () {
  40195. return 50.0;
  40196. };
  40197. /**
  40198. * Returns the light direction (Vector3) for any passed face index.
  40199. */
  40200. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  40201. return this.transformedDirection ? this.transformedDirection : this.direction;
  40202. };
  40203. /**
  40204. * Returns the DirectionalLight absolute position in the World.
  40205. */
  40206. ShadowLight.prototype.getAbsolutePosition = function () {
  40207. return this.transformedPosition ? this.transformedPosition : this.position;
  40208. };
  40209. /**
  40210. * Sets the DirectionalLight direction toward the passed target (Vector3).
  40211. * Returns the updated DirectionalLight direction (Vector3).
  40212. */
  40213. ShadowLight.prototype.setDirectionToTarget = function (target) {
  40214. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  40215. return this.direction;
  40216. };
  40217. /**
  40218. * Returns the light rotation (Vector3).
  40219. */
  40220. ShadowLight.prototype.getRotation = function () {
  40221. this.direction.normalize();
  40222. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  40223. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  40224. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  40225. };
  40226. /**
  40227. * Boolean : false by default.
  40228. */
  40229. ShadowLight.prototype.needCube = function () {
  40230. return false;
  40231. };
  40232. /**
  40233. * Specifies wether or not the projection matrix should be recomputed this frame.
  40234. */
  40235. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  40236. return this._needProjectionMatrixCompute;
  40237. };
  40238. /**
  40239. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  40240. */
  40241. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  40242. this._needProjectionMatrixCompute = true;
  40243. };
  40244. /**
  40245. * Get the world matrix of the sahdow lights.
  40246. */
  40247. ShadowLight.prototype._getWorldMatrix = function () {
  40248. if (!this._worldMatrix) {
  40249. this._worldMatrix = BABYLON.Matrix.Identity();
  40250. }
  40251. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  40252. return this._worldMatrix;
  40253. };
  40254. /**
  40255. * Gets the minZ used for shadow according to both the scene and the light.
  40256. * @param activeCamera
  40257. */
  40258. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  40259. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  40260. };
  40261. /**
  40262. * Gets the maxZ used for shadow according to both the scene and the light.
  40263. * @param activeCamera
  40264. */
  40265. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  40266. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  40267. };
  40268. /**
  40269. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  40270. * Returns the light.
  40271. */
  40272. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40273. if (this.customProjectionMatrixBuilder) {
  40274. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  40275. }
  40276. else {
  40277. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  40278. }
  40279. return this;
  40280. };
  40281. __decorate([
  40282. BABYLON.serializeAsVector3()
  40283. ], ShadowLight.prototype, "position", void 0);
  40284. __decorate([
  40285. BABYLON.serializeAsVector3()
  40286. ], ShadowLight.prototype, "direction", null);
  40287. __decorate([
  40288. BABYLON.serialize()
  40289. ], ShadowLight.prototype, "shadowMinZ", null);
  40290. __decorate([
  40291. BABYLON.serialize()
  40292. ], ShadowLight.prototype, "shadowMaxZ", null);
  40293. return ShadowLight;
  40294. }(BABYLON.Light));
  40295. BABYLON.ShadowLight = ShadowLight;
  40296. })(BABYLON || (BABYLON = {}));
  40297. //# sourceMappingURL=babylon.shadowLight.js.map
  40298. var BABYLON;
  40299. (function (BABYLON) {
  40300. var PointLight = /** @class */ (function (_super) {
  40301. __extends(PointLight, _super);
  40302. /**
  40303. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  40304. * A PointLight emits the light in every direction.
  40305. * It can cast shadows.
  40306. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  40307. * ```javascript
  40308. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  40309. * ```
  40310. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40311. */
  40312. function PointLight(name, position, scene) {
  40313. var _this = _super.call(this, name, scene) || this;
  40314. _this._shadowAngle = Math.PI / 2;
  40315. _this.position = position;
  40316. return _this;
  40317. }
  40318. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  40319. /**
  40320. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40321. * This specifies what angle the shadow will use to be created.
  40322. *
  40323. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  40324. */
  40325. get: function () {
  40326. return this._shadowAngle;
  40327. },
  40328. /**
  40329. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40330. * This specifies what angle the shadow will use to be created.
  40331. *
  40332. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  40333. */
  40334. set: function (value) {
  40335. this._shadowAngle = value;
  40336. this.forceProjectionMatrixCompute();
  40337. },
  40338. enumerable: true,
  40339. configurable: true
  40340. });
  40341. Object.defineProperty(PointLight.prototype, "direction", {
  40342. get: function () {
  40343. return this._direction;
  40344. },
  40345. /**
  40346. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40347. */
  40348. set: function (value) {
  40349. var previousNeedCube = this.needCube();
  40350. this._direction = value;
  40351. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  40352. this._shadowGenerator.recreateShadowMap();
  40353. }
  40354. },
  40355. enumerable: true,
  40356. configurable: true
  40357. });
  40358. /**
  40359. * Returns the string "PointLight"
  40360. */
  40361. PointLight.prototype.getClassName = function () {
  40362. return "PointLight";
  40363. };
  40364. /**
  40365. * Returns the integer 0.
  40366. */
  40367. PointLight.prototype.getTypeID = function () {
  40368. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  40369. };
  40370. /**
  40371. * Specifies wether or not the shadowmap should be a cube texture.
  40372. */
  40373. PointLight.prototype.needCube = function () {
  40374. return !this.direction;
  40375. };
  40376. /**
  40377. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  40378. */
  40379. PointLight.prototype.getShadowDirection = function (faceIndex) {
  40380. if (this.direction) {
  40381. return _super.prototype.getShadowDirection.call(this, faceIndex);
  40382. }
  40383. else {
  40384. switch (faceIndex) {
  40385. case 0:
  40386. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  40387. case 1:
  40388. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  40389. case 2:
  40390. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  40391. case 3:
  40392. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  40393. case 4:
  40394. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  40395. case 5:
  40396. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  40397. }
  40398. }
  40399. return BABYLON.Vector3.Zero();
  40400. };
  40401. /**
  40402. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  40403. * - fov = PI / 2
  40404. * - aspect ratio : 1.0
  40405. * - z-near and far equal to the active camera minZ and maxZ.
  40406. * Returns the PointLight.
  40407. */
  40408. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40409. var activeCamera = this.getScene().activeCamera;
  40410. if (!activeCamera) {
  40411. return;
  40412. }
  40413. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  40414. };
  40415. PointLight.prototype._buildUniformLayout = function () {
  40416. this._uniformBuffer.addUniform("vLightData", 4);
  40417. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40418. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40419. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40420. this._uniformBuffer.addUniform("depthValues", 2);
  40421. this._uniformBuffer.create();
  40422. };
  40423. /**
  40424. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  40425. * Returns the PointLight.
  40426. */
  40427. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  40428. if (this.computeTransformedInformation()) {
  40429. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  40430. return this;
  40431. }
  40432. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  40433. return this;
  40434. };
  40435. __decorate([
  40436. BABYLON.serialize()
  40437. ], PointLight.prototype, "shadowAngle", null);
  40438. return PointLight;
  40439. }(BABYLON.ShadowLight));
  40440. BABYLON.PointLight = PointLight;
  40441. })(BABYLON || (BABYLON = {}));
  40442. //# sourceMappingURL=babylon.pointLight.js.map
  40443. var BABYLON;
  40444. (function (BABYLON) {
  40445. var DirectionalLight = /** @class */ (function (_super) {
  40446. __extends(DirectionalLight, _super);
  40447. /**
  40448. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  40449. * The directional light is emitted from everywhere in the given direction.
  40450. * It can cast shawdows.
  40451. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40452. */
  40453. function DirectionalLight(name, direction, scene) {
  40454. var _this = _super.call(this, name, scene) || this;
  40455. _this._shadowFrustumSize = 0;
  40456. _this._shadowOrthoScale = 0.5;
  40457. _this.autoUpdateExtends = true;
  40458. // Cache
  40459. _this._orthoLeft = Number.MAX_VALUE;
  40460. _this._orthoRight = Number.MIN_VALUE;
  40461. _this._orthoTop = Number.MIN_VALUE;
  40462. _this._orthoBottom = Number.MAX_VALUE;
  40463. _this.position = direction.scale(-1.0);
  40464. _this.direction = direction;
  40465. return _this;
  40466. }
  40467. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  40468. /**
  40469. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  40470. */
  40471. get: function () {
  40472. return this._shadowFrustumSize;
  40473. },
  40474. /**
  40475. * Specifies a fix frustum size for the shadow generation.
  40476. */
  40477. set: function (value) {
  40478. this._shadowFrustumSize = value;
  40479. this.forceProjectionMatrixCompute();
  40480. },
  40481. enumerable: true,
  40482. configurable: true
  40483. });
  40484. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  40485. get: function () {
  40486. return this._shadowOrthoScale;
  40487. },
  40488. set: function (value) {
  40489. this._shadowOrthoScale = value;
  40490. this.forceProjectionMatrixCompute();
  40491. },
  40492. enumerable: true,
  40493. configurable: true
  40494. });
  40495. /**
  40496. * Returns the string "DirectionalLight".
  40497. */
  40498. DirectionalLight.prototype.getClassName = function () {
  40499. return "DirectionalLight";
  40500. };
  40501. /**
  40502. * Returns the integer 1.
  40503. */
  40504. DirectionalLight.prototype.getTypeID = function () {
  40505. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  40506. };
  40507. /**
  40508. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  40509. * Returns the DirectionalLight Shadow projection matrix.
  40510. */
  40511. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40512. if (this.shadowFrustumSize > 0) {
  40513. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  40514. }
  40515. else {
  40516. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  40517. }
  40518. };
  40519. /**
  40520. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  40521. * Returns the DirectionalLight Shadow projection matrix.
  40522. */
  40523. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  40524. var activeCamera = this.getScene().activeCamera;
  40525. if (!activeCamera) {
  40526. return;
  40527. }
  40528. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  40529. };
  40530. /**
  40531. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  40532. * Returns the DirectionalLight Shadow projection matrix.
  40533. */
  40534. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40535. var activeCamera = this.getScene().activeCamera;
  40536. if (!activeCamera) {
  40537. return;
  40538. }
  40539. // Check extends
  40540. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  40541. var tempVector3 = BABYLON.Vector3.Zero();
  40542. this._orthoLeft = Number.MAX_VALUE;
  40543. this._orthoRight = Number.MIN_VALUE;
  40544. this._orthoTop = Number.MIN_VALUE;
  40545. this._orthoBottom = Number.MAX_VALUE;
  40546. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  40547. var mesh = renderList[meshIndex];
  40548. if (!mesh) {
  40549. continue;
  40550. }
  40551. var boundingInfo = mesh.getBoundingInfo();
  40552. var boundingBox = boundingInfo.boundingBox;
  40553. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  40554. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  40555. if (tempVector3.x < this._orthoLeft)
  40556. this._orthoLeft = tempVector3.x;
  40557. if (tempVector3.y < this._orthoBottom)
  40558. this._orthoBottom = tempVector3.y;
  40559. if (tempVector3.x > this._orthoRight)
  40560. this._orthoRight = tempVector3.x;
  40561. if (tempVector3.y > this._orthoTop)
  40562. this._orthoTop = tempVector3.y;
  40563. }
  40564. }
  40565. }
  40566. var xOffset = this._orthoRight - this._orthoLeft;
  40567. var yOffset = this._orthoTop - this._orthoBottom;
  40568. 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);
  40569. };
  40570. DirectionalLight.prototype._buildUniformLayout = function () {
  40571. this._uniformBuffer.addUniform("vLightData", 4);
  40572. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40573. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40574. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40575. this._uniformBuffer.addUniform("depthValues", 2);
  40576. this._uniformBuffer.create();
  40577. };
  40578. /**
  40579. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  40580. * Returns the DirectionalLight.
  40581. */
  40582. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  40583. if (this.computeTransformedInformation()) {
  40584. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  40585. return this;
  40586. }
  40587. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  40588. return this;
  40589. };
  40590. /**
  40591. * Gets the minZ used for shadow according to both the scene and the light.
  40592. *
  40593. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  40594. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  40595. * @param activeCamera
  40596. */
  40597. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  40598. return 1;
  40599. };
  40600. /**
  40601. * Gets the maxZ used for shadow according to both the scene and the light.
  40602. *
  40603. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  40604. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  40605. * @param activeCamera
  40606. */
  40607. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  40608. return 1;
  40609. };
  40610. __decorate([
  40611. BABYLON.serialize()
  40612. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  40613. __decorate([
  40614. BABYLON.serialize()
  40615. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  40616. __decorate([
  40617. BABYLON.serialize()
  40618. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  40619. return DirectionalLight;
  40620. }(BABYLON.ShadowLight));
  40621. BABYLON.DirectionalLight = DirectionalLight;
  40622. })(BABYLON || (BABYLON = {}));
  40623. //# sourceMappingURL=babylon.directionalLight.js.map
  40624. var BABYLON;
  40625. (function (BABYLON) {
  40626. var SpotLight = /** @class */ (function (_super) {
  40627. __extends(SpotLight, _super);
  40628. /**
  40629. * Creates a SpotLight object in the scene with the passed parameters :
  40630. * - `position` (Vector3) is the initial SpotLight position,
  40631. * - `direction` (Vector3) is the initial SpotLight direction,
  40632. * - `angle` (float, in radians) is the spot light cone angle,
  40633. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  40634. * A spot light is a simply light oriented cone.
  40635. * It can cast shadows.
  40636. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40637. */
  40638. function SpotLight(name, position, direction, angle, exponent, scene) {
  40639. var _this = _super.call(this, name, scene) || this;
  40640. _this.position = position;
  40641. _this.direction = direction;
  40642. _this.angle = angle;
  40643. _this.exponent = exponent;
  40644. return _this;
  40645. }
  40646. Object.defineProperty(SpotLight.prototype, "angle", {
  40647. get: function () {
  40648. return this._angle;
  40649. },
  40650. set: function (value) {
  40651. this._angle = value;
  40652. this.forceProjectionMatrixCompute();
  40653. },
  40654. enumerable: true,
  40655. configurable: true
  40656. });
  40657. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  40658. get: function () {
  40659. return this._shadowAngleScale;
  40660. },
  40661. /**
  40662. * Allows scaling the angle of the light for shadow generation only.
  40663. */
  40664. set: function (value) {
  40665. this._shadowAngleScale = value;
  40666. this.forceProjectionMatrixCompute();
  40667. },
  40668. enumerable: true,
  40669. configurable: true
  40670. });
  40671. /**
  40672. * Returns the string "SpotLight".
  40673. */
  40674. SpotLight.prototype.getClassName = function () {
  40675. return "SpotLight";
  40676. };
  40677. /**
  40678. * Returns the integer 2.
  40679. */
  40680. SpotLight.prototype.getTypeID = function () {
  40681. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  40682. };
  40683. /**
  40684. * 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.
  40685. * Returns the SpotLight.
  40686. */
  40687. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40688. var activeCamera = this.getScene().activeCamera;
  40689. if (!activeCamera) {
  40690. return;
  40691. }
  40692. this._shadowAngleScale = this._shadowAngleScale || 1;
  40693. var angle = this._shadowAngleScale * this._angle;
  40694. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  40695. };
  40696. SpotLight.prototype._buildUniformLayout = function () {
  40697. this._uniformBuffer.addUniform("vLightData", 4);
  40698. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40699. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40700. this._uniformBuffer.addUniform("vLightDirection", 3);
  40701. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40702. this._uniformBuffer.addUniform("depthValues", 2);
  40703. this._uniformBuffer.create();
  40704. };
  40705. /**
  40706. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  40707. * Return the SpotLight.
  40708. */
  40709. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  40710. var normalizeDirection;
  40711. if (this.computeTransformedInformation()) {
  40712. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  40713. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  40714. }
  40715. else {
  40716. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  40717. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  40718. }
  40719. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  40720. return this;
  40721. };
  40722. __decorate([
  40723. BABYLON.serialize()
  40724. ], SpotLight.prototype, "angle", null);
  40725. __decorate([
  40726. BABYLON.serialize()
  40727. /**
  40728. * Allows scaling the angle of the light for shadow generation only.
  40729. */
  40730. ], SpotLight.prototype, "shadowAngleScale", null);
  40731. __decorate([
  40732. BABYLON.serialize()
  40733. ], SpotLight.prototype, "exponent", void 0);
  40734. return SpotLight;
  40735. }(BABYLON.ShadowLight));
  40736. BABYLON.SpotLight = SpotLight;
  40737. })(BABYLON || (BABYLON = {}));
  40738. //# sourceMappingURL=babylon.spotLight.js.map
  40739. var BABYLON;
  40740. (function (BABYLON) {
  40741. var AnimationRange = /** @class */ (function () {
  40742. function AnimationRange(name, from, to) {
  40743. this.name = name;
  40744. this.from = from;
  40745. this.to = to;
  40746. }
  40747. AnimationRange.prototype.clone = function () {
  40748. return new AnimationRange(this.name, this.from, this.to);
  40749. };
  40750. return AnimationRange;
  40751. }());
  40752. BABYLON.AnimationRange = AnimationRange;
  40753. /**
  40754. * Composed of a frame, and an action function
  40755. */
  40756. var AnimationEvent = /** @class */ (function () {
  40757. function AnimationEvent(frame, action, onlyOnce) {
  40758. this.frame = frame;
  40759. this.action = action;
  40760. this.onlyOnce = onlyOnce;
  40761. this.isDone = false;
  40762. }
  40763. return AnimationEvent;
  40764. }());
  40765. BABYLON.AnimationEvent = AnimationEvent;
  40766. var PathCursor = /** @class */ (function () {
  40767. function PathCursor(path) {
  40768. this.path = path;
  40769. this._onchange = new Array();
  40770. this.value = 0;
  40771. this.animations = new Array();
  40772. }
  40773. PathCursor.prototype.getPoint = function () {
  40774. var point = this.path.getPointAtLengthPosition(this.value);
  40775. return new BABYLON.Vector3(point.x, 0, point.y);
  40776. };
  40777. PathCursor.prototype.moveAhead = function (step) {
  40778. if (step === void 0) { step = 0.002; }
  40779. this.move(step);
  40780. return this;
  40781. };
  40782. PathCursor.prototype.moveBack = function (step) {
  40783. if (step === void 0) { step = 0.002; }
  40784. this.move(-step);
  40785. return this;
  40786. };
  40787. PathCursor.prototype.move = function (step) {
  40788. if (Math.abs(step) > 1) {
  40789. throw "step size should be less than 1.";
  40790. }
  40791. this.value += step;
  40792. this.ensureLimits();
  40793. this.raiseOnChange();
  40794. return this;
  40795. };
  40796. PathCursor.prototype.ensureLimits = function () {
  40797. while (this.value > 1) {
  40798. this.value -= 1;
  40799. }
  40800. while (this.value < 0) {
  40801. this.value += 1;
  40802. }
  40803. return this;
  40804. };
  40805. // used by animation engine
  40806. PathCursor.prototype.raiseOnChange = function () {
  40807. var _this = this;
  40808. this._onchange.forEach(function (f) { return f(_this); });
  40809. return this;
  40810. };
  40811. PathCursor.prototype.onchange = function (f) {
  40812. this._onchange.push(f);
  40813. return this;
  40814. };
  40815. return PathCursor;
  40816. }());
  40817. BABYLON.PathCursor = PathCursor;
  40818. var Animation = /** @class */ (function () {
  40819. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  40820. this.name = name;
  40821. this.targetProperty = targetProperty;
  40822. this.framePerSecond = framePerSecond;
  40823. this.dataType = dataType;
  40824. this.loopMode = loopMode;
  40825. this.enableBlending = enableBlending;
  40826. this._runtimeAnimations = new Array();
  40827. // The set of event that will be linked to this animation
  40828. this._events = new Array();
  40829. this.blendingSpeed = 0.01;
  40830. this._ranges = {};
  40831. this.targetPropertyPath = targetProperty.split(".");
  40832. this.dataType = dataType;
  40833. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  40834. }
  40835. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  40836. var dataType = undefined;
  40837. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  40838. dataType = Animation.ANIMATIONTYPE_FLOAT;
  40839. }
  40840. else if (from instanceof BABYLON.Quaternion) {
  40841. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  40842. }
  40843. else if (from instanceof BABYLON.Vector3) {
  40844. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  40845. }
  40846. else if (from instanceof BABYLON.Vector2) {
  40847. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  40848. }
  40849. else if (from instanceof BABYLON.Color3) {
  40850. dataType = Animation.ANIMATIONTYPE_COLOR3;
  40851. }
  40852. else if (from instanceof BABYLON.Size) {
  40853. dataType = Animation.ANIMATIONTYPE_SIZE;
  40854. }
  40855. if (dataType == undefined) {
  40856. return null;
  40857. }
  40858. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  40859. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  40860. animation.setKeys(keys);
  40861. if (easingFunction !== undefined) {
  40862. animation.setEasingFunction(easingFunction);
  40863. }
  40864. return animation;
  40865. };
  40866. /**
  40867. * Sets up an animation.
  40868. * @param property the property to animate
  40869. * @param animationType the animation type to apply
  40870. * @param easingFunction the easing function used in the animation
  40871. * @returns The created animation
  40872. */
  40873. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  40874. var animation = new BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  40875. animation.setEasingFunction(easingFunction);
  40876. return animation;
  40877. };
  40878. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  40879. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  40880. if (!animation) {
  40881. return null;
  40882. }
  40883. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  40884. };
  40885. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  40886. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  40887. if (!animation) {
  40888. return null;
  40889. }
  40890. node.animations.push(animation);
  40891. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  40892. };
  40893. /**
  40894. * Transition property of the Camera to the target Value.
  40895. * @param property The property to transition
  40896. * @param targetValue The target Value of the property
  40897. * @param host The object where the property to animate belongs
  40898. * @param scene Scene used to run the animation
  40899. * @param frameRate Framerate (in frame/s) to use
  40900. * @param transition The transition type we want to use
  40901. * @param duration The duration of the animation, in milliseconds
  40902. * @param onAnimationEnd Call back trigger at the end of the animation.
  40903. */
  40904. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  40905. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  40906. if (duration <= 0) {
  40907. host[property] = targetValue;
  40908. if (onAnimationEnd) {
  40909. onAnimationEnd();
  40910. }
  40911. return null;
  40912. }
  40913. var endFrame = frameRate * (duration / 1000);
  40914. transition.setKeys([{
  40915. frame: 0,
  40916. value: host[property].clone ? host[property].clone() : host[property]
  40917. },
  40918. {
  40919. frame: endFrame,
  40920. value: targetValue
  40921. }]);
  40922. if (!host.animations) {
  40923. host.animations = [];
  40924. }
  40925. host.animations.push(transition);
  40926. var animation = scene.beginAnimation(host, 0, endFrame, false);
  40927. animation.onAnimationEnd = onAnimationEnd;
  40928. return animation;
  40929. };
  40930. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  40931. /**
  40932. * Return the array of runtime animations currently using this animation
  40933. */
  40934. get: function () {
  40935. return this._runtimeAnimations;
  40936. },
  40937. enumerable: true,
  40938. configurable: true
  40939. });
  40940. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  40941. get: function () {
  40942. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  40943. var runtimeAnimation = _a[_i];
  40944. if (!runtimeAnimation.isStopped) {
  40945. return true;
  40946. }
  40947. }
  40948. return false;
  40949. },
  40950. enumerable: true,
  40951. configurable: true
  40952. });
  40953. // Methods
  40954. /**
  40955. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  40956. */
  40957. Animation.prototype.toString = function (fullDetails) {
  40958. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  40959. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  40960. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  40961. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  40962. if (fullDetails) {
  40963. ret += ", Ranges: {";
  40964. var first = true;
  40965. for (var name in this._ranges) {
  40966. if (first) {
  40967. ret += ", ";
  40968. first = false;
  40969. }
  40970. ret += name;
  40971. }
  40972. ret += "}";
  40973. }
  40974. return ret;
  40975. };
  40976. /**
  40977. * Add an event to this animation.
  40978. */
  40979. Animation.prototype.addEvent = function (event) {
  40980. this._events.push(event);
  40981. };
  40982. /**
  40983. * Remove all events found at the given frame
  40984. * @param frame
  40985. */
  40986. Animation.prototype.removeEvents = function (frame) {
  40987. for (var index = 0; index < this._events.length; index++) {
  40988. if (this._events[index].frame === frame) {
  40989. this._events.splice(index, 1);
  40990. index--;
  40991. }
  40992. }
  40993. };
  40994. Animation.prototype.getEvents = function () {
  40995. return this._events;
  40996. };
  40997. Animation.prototype.createRange = function (name, from, to) {
  40998. // check name not already in use; could happen for bones after serialized
  40999. if (!this._ranges[name]) {
  41000. this._ranges[name] = new AnimationRange(name, from, to);
  41001. }
  41002. };
  41003. Animation.prototype.deleteRange = function (name, deleteFrames) {
  41004. if (deleteFrames === void 0) { deleteFrames = true; }
  41005. var range = this._ranges[name];
  41006. if (!range) {
  41007. return;
  41008. }
  41009. if (deleteFrames) {
  41010. var from = range.from;
  41011. var to = range.to;
  41012. // this loop MUST go high to low for multiple splices to work
  41013. for (var key = this._keys.length - 1; key >= 0; key--) {
  41014. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  41015. this._keys.splice(key, 1);
  41016. }
  41017. }
  41018. }
  41019. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  41020. };
  41021. Animation.prototype.getRange = function (name) {
  41022. return this._ranges[name];
  41023. };
  41024. Animation.prototype.getKeys = function () {
  41025. return this._keys;
  41026. };
  41027. Animation.prototype.getHighestFrame = function () {
  41028. var ret = 0;
  41029. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  41030. if (ret < this._keys[key].frame) {
  41031. ret = this._keys[key].frame;
  41032. }
  41033. }
  41034. return ret;
  41035. };
  41036. Animation.prototype.getEasingFunction = function () {
  41037. return this._easingFunction;
  41038. };
  41039. Animation.prototype.setEasingFunction = function (easingFunction) {
  41040. this._easingFunction = easingFunction;
  41041. };
  41042. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  41043. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  41044. };
  41045. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  41046. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  41047. };
  41048. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  41049. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  41050. };
  41051. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  41052. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  41053. };
  41054. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  41055. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  41056. };
  41057. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  41058. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  41059. };
  41060. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  41061. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  41062. };
  41063. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  41064. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  41065. };
  41066. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  41067. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  41068. };
  41069. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  41070. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  41071. };
  41072. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  41073. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  41074. };
  41075. Animation.prototype.clone = function () {
  41076. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  41077. clone.enableBlending = this.enableBlending;
  41078. clone.blendingSpeed = this.blendingSpeed;
  41079. if (this._keys) {
  41080. clone.setKeys(this._keys);
  41081. }
  41082. if (this._ranges) {
  41083. clone._ranges = {};
  41084. for (var name in this._ranges) {
  41085. var range = this._ranges[name];
  41086. if (!range) {
  41087. continue;
  41088. }
  41089. clone._ranges[name] = range.clone();
  41090. }
  41091. }
  41092. return clone;
  41093. };
  41094. Animation.prototype.setKeys = function (values) {
  41095. this._keys = values.slice(0);
  41096. };
  41097. Animation.prototype.serialize = function () {
  41098. var serializationObject = {};
  41099. serializationObject.name = this.name;
  41100. serializationObject.property = this.targetProperty;
  41101. serializationObject.framePerSecond = this.framePerSecond;
  41102. serializationObject.dataType = this.dataType;
  41103. serializationObject.loopBehavior = this.loopMode;
  41104. serializationObject.enableBlending = this.enableBlending;
  41105. serializationObject.blendingSpeed = this.blendingSpeed;
  41106. var dataType = this.dataType;
  41107. serializationObject.keys = [];
  41108. var keys = this.getKeys();
  41109. for (var index = 0; index < keys.length; index++) {
  41110. var animationKey = keys[index];
  41111. var key = {};
  41112. key.frame = animationKey.frame;
  41113. switch (dataType) {
  41114. case Animation.ANIMATIONTYPE_FLOAT:
  41115. key.values = [animationKey.value];
  41116. break;
  41117. case Animation.ANIMATIONTYPE_QUATERNION:
  41118. case Animation.ANIMATIONTYPE_MATRIX:
  41119. case Animation.ANIMATIONTYPE_VECTOR3:
  41120. case Animation.ANIMATIONTYPE_COLOR3:
  41121. key.values = animationKey.value.asArray();
  41122. break;
  41123. }
  41124. serializationObject.keys.push(key);
  41125. }
  41126. serializationObject.ranges = [];
  41127. for (var name in this._ranges) {
  41128. var source = this._ranges[name];
  41129. if (!source) {
  41130. continue;
  41131. }
  41132. var range = {};
  41133. range.name = name;
  41134. range.from = source.from;
  41135. range.to = source.to;
  41136. serializationObject.ranges.push(range);
  41137. }
  41138. return serializationObject;
  41139. };
  41140. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  41141. get: function () {
  41142. return Animation._ANIMATIONTYPE_FLOAT;
  41143. },
  41144. enumerable: true,
  41145. configurable: true
  41146. });
  41147. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  41148. get: function () {
  41149. return Animation._ANIMATIONTYPE_VECTOR3;
  41150. },
  41151. enumerable: true,
  41152. configurable: true
  41153. });
  41154. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  41155. get: function () {
  41156. return Animation._ANIMATIONTYPE_VECTOR2;
  41157. },
  41158. enumerable: true,
  41159. configurable: true
  41160. });
  41161. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  41162. get: function () {
  41163. return Animation._ANIMATIONTYPE_SIZE;
  41164. },
  41165. enumerable: true,
  41166. configurable: true
  41167. });
  41168. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  41169. get: function () {
  41170. return Animation._ANIMATIONTYPE_QUATERNION;
  41171. },
  41172. enumerable: true,
  41173. configurable: true
  41174. });
  41175. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  41176. get: function () {
  41177. return Animation._ANIMATIONTYPE_MATRIX;
  41178. },
  41179. enumerable: true,
  41180. configurable: true
  41181. });
  41182. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  41183. get: function () {
  41184. return Animation._ANIMATIONTYPE_COLOR3;
  41185. },
  41186. enumerable: true,
  41187. configurable: true
  41188. });
  41189. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  41190. get: function () {
  41191. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  41192. },
  41193. enumerable: true,
  41194. configurable: true
  41195. });
  41196. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  41197. get: function () {
  41198. return Animation._ANIMATIONLOOPMODE_CYCLE;
  41199. },
  41200. enumerable: true,
  41201. configurable: true
  41202. });
  41203. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  41204. get: function () {
  41205. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  41206. },
  41207. enumerable: true,
  41208. configurable: true
  41209. });
  41210. Animation.Parse = function (parsedAnimation) {
  41211. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  41212. var dataType = parsedAnimation.dataType;
  41213. var keys = [];
  41214. var data;
  41215. var index;
  41216. if (parsedAnimation.enableBlending) {
  41217. animation.enableBlending = parsedAnimation.enableBlending;
  41218. }
  41219. if (parsedAnimation.blendingSpeed) {
  41220. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  41221. }
  41222. for (index = 0; index < parsedAnimation.keys.length; index++) {
  41223. var key = parsedAnimation.keys[index];
  41224. var inTangent;
  41225. var outTangent;
  41226. switch (dataType) {
  41227. case Animation.ANIMATIONTYPE_FLOAT:
  41228. data = key.values[0];
  41229. if (key.values.length >= 1) {
  41230. inTangent = key.values[1];
  41231. }
  41232. if (key.values.length >= 2) {
  41233. outTangent = key.values[2];
  41234. }
  41235. break;
  41236. case Animation.ANIMATIONTYPE_QUATERNION:
  41237. data = BABYLON.Quaternion.FromArray(key.values);
  41238. if (key.values.length >= 8) {
  41239. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  41240. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  41241. inTangent = _inTangent;
  41242. }
  41243. }
  41244. if (key.values.length >= 12) {
  41245. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  41246. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  41247. outTangent = _outTangent;
  41248. }
  41249. }
  41250. break;
  41251. case Animation.ANIMATIONTYPE_MATRIX:
  41252. data = BABYLON.Matrix.FromArray(key.values);
  41253. break;
  41254. case Animation.ANIMATIONTYPE_COLOR3:
  41255. data = BABYLON.Color3.FromArray(key.values);
  41256. break;
  41257. case Animation.ANIMATIONTYPE_VECTOR3:
  41258. default:
  41259. data = BABYLON.Vector3.FromArray(key.values);
  41260. break;
  41261. }
  41262. var keyData = {};
  41263. keyData.frame = key.frame;
  41264. keyData.value = data;
  41265. if (inTangent != undefined) {
  41266. keyData.inTangent = inTangent;
  41267. }
  41268. if (outTangent != undefined) {
  41269. keyData.outTangent = outTangent;
  41270. }
  41271. keys.push(keyData);
  41272. }
  41273. animation.setKeys(keys);
  41274. if (parsedAnimation.ranges) {
  41275. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  41276. data = parsedAnimation.ranges[index];
  41277. animation.createRange(data.name, data.from, data.to);
  41278. }
  41279. }
  41280. return animation;
  41281. };
  41282. Animation.AppendSerializedAnimations = function (source, destination) {
  41283. if (source.animations) {
  41284. destination.animations = [];
  41285. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  41286. var animation = source.animations[animationIndex];
  41287. destination.animations.push(animation.serialize());
  41288. }
  41289. }
  41290. };
  41291. Animation.AllowMatricesInterpolation = false;
  41292. // Statics
  41293. Animation._ANIMATIONTYPE_FLOAT = 0;
  41294. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  41295. Animation._ANIMATIONTYPE_QUATERNION = 2;
  41296. Animation._ANIMATIONTYPE_MATRIX = 3;
  41297. Animation._ANIMATIONTYPE_COLOR3 = 4;
  41298. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  41299. Animation._ANIMATIONTYPE_SIZE = 6;
  41300. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  41301. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  41302. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  41303. return Animation;
  41304. }());
  41305. BABYLON.Animation = Animation;
  41306. })(BABYLON || (BABYLON = {}));
  41307. //# sourceMappingURL=babylon.animation.js.map
  41308. var BABYLON;
  41309. (function (BABYLON) {
  41310. var RuntimeAnimation = /** @class */ (function () {
  41311. function RuntimeAnimation(target, animation) {
  41312. this._offsetsCache = {};
  41313. this._highLimitsCache = {};
  41314. this._stopped = false;
  41315. this._blendingFactor = 0;
  41316. this._ratioOffset = 0;
  41317. this._animation = animation;
  41318. this._target = target;
  41319. animation._runtimeAnimations.push(this);
  41320. }
  41321. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  41322. get: function () {
  41323. return this._animation;
  41324. },
  41325. enumerable: true,
  41326. configurable: true
  41327. });
  41328. RuntimeAnimation.prototype.reset = function () {
  41329. this._offsetsCache = {};
  41330. this._highLimitsCache = {};
  41331. this.currentFrame = 0;
  41332. this._blendingFactor = 0;
  41333. this._originalBlendValue = null;
  41334. };
  41335. RuntimeAnimation.prototype.isStopped = function () {
  41336. return this._stopped;
  41337. };
  41338. RuntimeAnimation.prototype.dispose = function () {
  41339. var index = this._animation.runtimeAnimations.indexOf(this);
  41340. if (index > -1) {
  41341. this._animation.runtimeAnimations.splice(index, 1);
  41342. }
  41343. };
  41344. RuntimeAnimation.prototype._getKeyValue = function (value) {
  41345. if (typeof value === "function") {
  41346. return value();
  41347. }
  41348. return value;
  41349. };
  41350. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  41351. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  41352. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  41353. }
  41354. this.currentFrame = currentFrame;
  41355. var keys = this._animation.getKeys();
  41356. // Try to get a hash to find the right key
  41357. 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));
  41358. if (keys[startKeyIndex].frame >= currentFrame) {
  41359. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  41360. startKeyIndex--;
  41361. }
  41362. }
  41363. for (var key = startKeyIndex; key < keys.length; key++) {
  41364. var endKey = keys[key + 1];
  41365. if (endKey.frame >= currentFrame) {
  41366. var startKey = keys[key];
  41367. var startValue = this._getKeyValue(startKey.value);
  41368. var endValue = this._getKeyValue(endKey.value);
  41369. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  41370. var frameDelta = endKey.frame - startKey.frame;
  41371. // gradient : percent of currentFrame between the frame inf and the frame sup
  41372. var gradient = (currentFrame - startKey.frame) / frameDelta;
  41373. // check for easingFunction and correction of gradient
  41374. var easingFunction = this._animation.getEasingFunction();
  41375. if (easingFunction != null) {
  41376. gradient = easingFunction.ease(gradient);
  41377. }
  41378. switch (this._animation.dataType) {
  41379. // Float
  41380. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  41381. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  41382. switch (loopMode) {
  41383. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41384. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41385. return floatValue;
  41386. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41387. return offsetValue * repeatCount + floatValue;
  41388. }
  41389. break;
  41390. // Quaternion
  41391. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  41392. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  41393. switch (loopMode) {
  41394. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41395. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41396. return quatValue;
  41397. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41398. return quatValue.add(offsetValue.scale(repeatCount));
  41399. }
  41400. return quatValue;
  41401. // Vector3
  41402. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  41403. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  41404. switch (loopMode) {
  41405. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41406. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41407. return vec3Value;
  41408. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41409. return vec3Value.add(offsetValue.scale(repeatCount));
  41410. }
  41411. // Vector2
  41412. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  41413. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  41414. switch (loopMode) {
  41415. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41416. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41417. return vec2Value;
  41418. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41419. return vec2Value.add(offsetValue.scale(repeatCount));
  41420. }
  41421. // Size
  41422. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  41423. switch (loopMode) {
  41424. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41425. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41426. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  41427. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41428. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  41429. }
  41430. // Color3
  41431. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  41432. switch (loopMode) {
  41433. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41434. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41435. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  41436. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41437. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  41438. }
  41439. // Matrix
  41440. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  41441. switch (loopMode) {
  41442. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41443. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41444. if (BABYLON.Animation.AllowMatricesInterpolation) {
  41445. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  41446. }
  41447. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41448. return startValue;
  41449. }
  41450. default:
  41451. break;
  41452. }
  41453. break;
  41454. }
  41455. }
  41456. return this._getKeyValue(keys[keys.length - 1].value);
  41457. };
  41458. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  41459. if (blend === void 0) { blend = false; }
  41460. // Set value
  41461. var path;
  41462. var destination;
  41463. var targetPropertyPath = this._animation.targetPropertyPath;
  41464. if (targetPropertyPath.length > 1) {
  41465. var property = this._target[targetPropertyPath[0]];
  41466. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  41467. property = property[targetPropertyPath[index]];
  41468. }
  41469. path = targetPropertyPath[targetPropertyPath.length - 1];
  41470. destination = property;
  41471. }
  41472. else {
  41473. path = targetPropertyPath[0];
  41474. destination = this._target;
  41475. }
  41476. // Blending
  41477. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  41478. if (!this._originalBlendValue) {
  41479. if (destination[path].clone) {
  41480. this._originalBlendValue = destination[path].clone();
  41481. }
  41482. else {
  41483. this._originalBlendValue = destination[path];
  41484. }
  41485. }
  41486. if (this._originalBlendValue.prototype) {
  41487. if (this._originalBlendValue.prototype.Lerp) {
  41488. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  41489. }
  41490. else {
  41491. destination[path] = currentValue;
  41492. }
  41493. }
  41494. else if (this._originalBlendValue.m) {
  41495. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  41496. }
  41497. else {
  41498. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  41499. }
  41500. this._blendingFactor += this._animation.blendingSpeed;
  41501. }
  41502. else {
  41503. destination[path] = currentValue;
  41504. }
  41505. if (this._target.markAsDirty) {
  41506. this._target.markAsDirty(this._animation.targetProperty);
  41507. }
  41508. };
  41509. RuntimeAnimation.prototype.goToFrame = function (frame) {
  41510. var keys = this._animation.getKeys();
  41511. if (frame < keys[0].frame) {
  41512. frame = keys[0].frame;
  41513. }
  41514. else if (frame > keys[keys.length - 1].frame) {
  41515. frame = keys[keys.length - 1].frame;
  41516. }
  41517. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  41518. this.setValue(currentValue);
  41519. };
  41520. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  41521. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  41522. this._ratioOffset = this._previousRatio - newRatio;
  41523. };
  41524. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  41525. if (blend === void 0) { blend = false; }
  41526. var targetPropertyPath = this._animation.targetPropertyPath;
  41527. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  41528. this._stopped = true;
  41529. return false;
  41530. }
  41531. var returnValue = true;
  41532. var keys = this._animation.getKeys();
  41533. // Adding a start key at frame 0 if missing
  41534. if (keys[0].frame !== 0) {
  41535. var newKey = { frame: 0, value: keys[0].value };
  41536. keys.splice(0, 0, newKey);
  41537. }
  41538. // Check limits
  41539. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  41540. from = keys[0].frame;
  41541. }
  41542. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  41543. to = keys[keys.length - 1].frame;
  41544. }
  41545. //to and from cannot be the same key
  41546. if (from === to) {
  41547. if (from > keys[0].frame) {
  41548. from--;
  41549. }
  41550. else if (to < keys[keys.length - 1].frame) {
  41551. to++;
  41552. }
  41553. }
  41554. // Compute ratio
  41555. var range = to - from;
  41556. var offsetValue;
  41557. // ratio represents the frame delta between from and to
  41558. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  41559. var highLimitValue = 0;
  41560. this._previousDelay = delay;
  41561. this._previousRatio = ratio;
  41562. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  41563. returnValue = false;
  41564. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  41565. }
  41566. else {
  41567. // Get max value if required
  41568. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  41569. var keyOffset = to.toString() + from.toString();
  41570. if (!this._offsetsCache[keyOffset]) {
  41571. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  41572. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  41573. switch (this._animation.dataType) {
  41574. // Float
  41575. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  41576. this._offsetsCache[keyOffset] = toValue - fromValue;
  41577. break;
  41578. // Quaternion
  41579. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  41580. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  41581. break;
  41582. // Vector3
  41583. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  41584. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  41585. // Vector2
  41586. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  41587. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  41588. // Size
  41589. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  41590. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  41591. // Color3
  41592. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  41593. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  41594. default:
  41595. break;
  41596. }
  41597. this._highLimitsCache[keyOffset] = toValue;
  41598. }
  41599. highLimitValue = this._highLimitsCache[keyOffset];
  41600. offsetValue = this._offsetsCache[keyOffset];
  41601. }
  41602. }
  41603. if (offsetValue === undefined) {
  41604. switch (this._animation.dataType) {
  41605. // Float
  41606. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  41607. offsetValue = 0;
  41608. break;
  41609. // Quaternion
  41610. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  41611. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  41612. break;
  41613. // Vector3
  41614. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  41615. offsetValue = BABYLON.Vector3.Zero();
  41616. break;
  41617. // Vector2
  41618. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  41619. offsetValue = BABYLON.Vector2.Zero();
  41620. break;
  41621. // Size
  41622. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  41623. offsetValue = BABYLON.Size.Zero();
  41624. break;
  41625. // Color3
  41626. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  41627. offsetValue = BABYLON.Color3.Black();
  41628. }
  41629. }
  41630. // Compute value
  41631. var repeatCount = (ratio / range) >> 0;
  41632. var currentFrame = returnValue ? from + ratio % range : to;
  41633. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  41634. // Set value
  41635. this.setValue(currentValue);
  41636. // Check events
  41637. var events = this._animation.getEvents();
  41638. for (var index = 0; index < events.length; index++) {
  41639. // Make sure current frame has passed event frame and that event frame is within the current range
  41640. // Also, handle both forward and reverse animations
  41641. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  41642. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  41643. var event = events[index];
  41644. if (!event.isDone) {
  41645. // If event should be done only once, remove it.
  41646. if (event.onlyOnce) {
  41647. events.splice(index, 1);
  41648. index--;
  41649. }
  41650. event.isDone = true;
  41651. event.action();
  41652. } // Don't do anything if the event has already be done.
  41653. }
  41654. else if (events[index].isDone && !events[index].onlyOnce) {
  41655. // reset event, the animation is looping
  41656. events[index].isDone = false;
  41657. }
  41658. }
  41659. if (!returnValue) {
  41660. this._stopped = true;
  41661. }
  41662. return returnValue;
  41663. };
  41664. return RuntimeAnimation;
  41665. }());
  41666. BABYLON.RuntimeAnimation = RuntimeAnimation;
  41667. })(BABYLON || (BABYLON = {}));
  41668. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  41669. var BABYLON;
  41670. (function (BABYLON) {
  41671. var Animatable = /** @class */ (function () {
  41672. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  41673. if (fromFrame === void 0) { fromFrame = 0; }
  41674. if (toFrame === void 0) { toFrame = 100; }
  41675. if (loopAnimation === void 0) { loopAnimation = false; }
  41676. if (speedRatio === void 0) { speedRatio = 1.0; }
  41677. this.target = target;
  41678. this.fromFrame = fromFrame;
  41679. this.toFrame = toFrame;
  41680. this.loopAnimation = loopAnimation;
  41681. this.onAnimationEnd = onAnimationEnd;
  41682. this._localDelayOffset = null;
  41683. this._pausedDelay = null;
  41684. this._runtimeAnimations = new Array();
  41685. this._paused = false;
  41686. this._speedRatio = 1;
  41687. this.animationStarted = false;
  41688. if (animations) {
  41689. this.appendAnimations(target, animations);
  41690. }
  41691. this._speedRatio = speedRatio;
  41692. this._scene = scene;
  41693. scene._activeAnimatables.push(this);
  41694. }
  41695. Object.defineProperty(Animatable.prototype, "speedRatio", {
  41696. get: function () {
  41697. return this._speedRatio;
  41698. },
  41699. set: function (value) {
  41700. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  41701. var animation = this._runtimeAnimations[index];
  41702. animation._prepareForSpeedRatioChange(value);
  41703. }
  41704. this._speedRatio = value;
  41705. },
  41706. enumerable: true,
  41707. configurable: true
  41708. });
  41709. // Methods
  41710. Animatable.prototype.getAnimations = function () {
  41711. return this._runtimeAnimations;
  41712. };
  41713. Animatable.prototype.appendAnimations = function (target, animations) {
  41714. for (var index = 0; index < animations.length; index++) {
  41715. var animation = animations[index];
  41716. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  41717. }
  41718. };
  41719. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  41720. var runtimeAnimations = this._runtimeAnimations;
  41721. for (var index = 0; index < runtimeAnimations.length; index++) {
  41722. if (runtimeAnimations[index].animation.targetProperty === property) {
  41723. return runtimeAnimations[index].animation;
  41724. }
  41725. }
  41726. return null;
  41727. };
  41728. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  41729. var runtimeAnimations = this._runtimeAnimations;
  41730. for (var index = 0; index < runtimeAnimations.length; index++) {
  41731. if (runtimeAnimations[index].animation.targetProperty === property) {
  41732. return runtimeAnimations[index];
  41733. }
  41734. }
  41735. return null;
  41736. };
  41737. Animatable.prototype.reset = function () {
  41738. var runtimeAnimations = this._runtimeAnimations;
  41739. for (var index = 0; index < runtimeAnimations.length; index++) {
  41740. runtimeAnimations[index].reset();
  41741. }
  41742. this._localDelayOffset = null;
  41743. this._pausedDelay = null;
  41744. };
  41745. Animatable.prototype.enableBlending = function (blendingSpeed) {
  41746. var runtimeAnimations = this._runtimeAnimations;
  41747. for (var index = 0; index < runtimeAnimations.length; index++) {
  41748. runtimeAnimations[index].animation.enableBlending = true;
  41749. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  41750. }
  41751. };
  41752. Animatable.prototype.disableBlending = function () {
  41753. var runtimeAnimations = this._runtimeAnimations;
  41754. for (var index = 0; index < runtimeAnimations.length; index++) {
  41755. runtimeAnimations[index].animation.enableBlending = false;
  41756. }
  41757. };
  41758. Animatable.prototype.goToFrame = function (frame) {
  41759. var runtimeAnimations = this._runtimeAnimations;
  41760. if (runtimeAnimations[0]) {
  41761. var fps = runtimeAnimations[0].animation.framePerSecond;
  41762. var currentFrame = runtimeAnimations[0].currentFrame;
  41763. var adjustTime = frame - currentFrame;
  41764. var delay = adjustTime * 1000 / fps;
  41765. if (this._localDelayOffset === null) {
  41766. this._localDelayOffset = 0;
  41767. }
  41768. this._localDelayOffset -= delay;
  41769. }
  41770. for (var index = 0; index < runtimeAnimations.length; index++) {
  41771. runtimeAnimations[index].goToFrame(frame);
  41772. }
  41773. };
  41774. Animatable.prototype.pause = function () {
  41775. if (this._paused) {
  41776. return;
  41777. }
  41778. this._paused = true;
  41779. };
  41780. Animatable.prototype.restart = function () {
  41781. this._paused = false;
  41782. };
  41783. Animatable.prototype.stop = function (animationName) {
  41784. if (animationName) {
  41785. var idx = this._scene._activeAnimatables.indexOf(this);
  41786. if (idx > -1) {
  41787. var runtimeAnimations = this._runtimeAnimations;
  41788. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  41789. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  41790. continue;
  41791. }
  41792. runtimeAnimations[index].dispose();
  41793. runtimeAnimations.splice(index, 1);
  41794. }
  41795. if (runtimeAnimations.length == 0) {
  41796. this._scene._activeAnimatables.splice(idx, 1);
  41797. if (this.onAnimationEnd) {
  41798. this.onAnimationEnd();
  41799. }
  41800. }
  41801. }
  41802. }
  41803. else {
  41804. var index = this._scene._activeAnimatables.indexOf(this);
  41805. if (index > -1) {
  41806. this._scene._activeAnimatables.splice(index, 1);
  41807. var runtimeAnimations = this._runtimeAnimations;
  41808. for (var index = 0; index < runtimeAnimations.length; index++) {
  41809. runtimeAnimations[index].dispose();
  41810. }
  41811. if (this.onAnimationEnd) {
  41812. this.onAnimationEnd();
  41813. }
  41814. }
  41815. }
  41816. };
  41817. Animatable.prototype._animate = function (delay) {
  41818. if (this._paused) {
  41819. this.animationStarted = false;
  41820. if (this._pausedDelay === null) {
  41821. this._pausedDelay = delay;
  41822. }
  41823. return true;
  41824. }
  41825. if (this._localDelayOffset === null) {
  41826. this._localDelayOffset = delay;
  41827. }
  41828. else if (this._pausedDelay !== null) {
  41829. this._localDelayOffset += delay - this._pausedDelay;
  41830. this._pausedDelay = null;
  41831. }
  41832. // Animating
  41833. var running = false;
  41834. var runtimeAnimations = this._runtimeAnimations;
  41835. var index;
  41836. for (index = 0; index < runtimeAnimations.length; index++) {
  41837. var animation = runtimeAnimations[index];
  41838. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  41839. running = running || isRunning;
  41840. }
  41841. this.animationStarted = running;
  41842. if (!running) {
  41843. // Remove from active animatables
  41844. index = this._scene._activeAnimatables.indexOf(this);
  41845. this._scene._activeAnimatables.splice(index, 1);
  41846. // Dispose all runtime animations
  41847. for (index = 0; index < runtimeAnimations.length; index++) {
  41848. runtimeAnimations[index].dispose();
  41849. }
  41850. }
  41851. if (!running && this.onAnimationEnd) {
  41852. this.onAnimationEnd();
  41853. this.onAnimationEnd = null;
  41854. }
  41855. return running;
  41856. };
  41857. return Animatable;
  41858. }());
  41859. BABYLON.Animatable = Animatable;
  41860. })(BABYLON || (BABYLON = {}));
  41861. //# sourceMappingURL=babylon.animatable.js.map
  41862. var BABYLON;
  41863. (function (BABYLON) {
  41864. var EasingFunction = /** @class */ (function () {
  41865. function EasingFunction() {
  41866. // Properties
  41867. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  41868. }
  41869. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  41870. get: function () {
  41871. return EasingFunction._EASINGMODE_EASEIN;
  41872. },
  41873. enumerable: true,
  41874. configurable: true
  41875. });
  41876. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  41877. get: function () {
  41878. return EasingFunction._EASINGMODE_EASEOUT;
  41879. },
  41880. enumerable: true,
  41881. configurable: true
  41882. });
  41883. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  41884. get: function () {
  41885. return EasingFunction._EASINGMODE_EASEINOUT;
  41886. },
  41887. enumerable: true,
  41888. configurable: true
  41889. });
  41890. EasingFunction.prototype.setEasingMode = function (easingMode) {
  41891. var n = Math.min(Math.max(easingMode, 0), 2);
  41892. this._easingMode = n;
  41893. };
  41894. EasingFunction.prototype.getEasingMode = function () {
  41895. return this._easingMode;
  41896. };
  41897. EasingFunction.prototype.easeInCore = function (gradient) {
  41898. throw new Error('You must implement this method');
  41899. };
  41900. EasingFunction.prototype.ease = function (gradient) {
  41901. switch (this._easingMode) {
  41902. case EasingFunction.EASINGMODE_EASEIN:
  41903. return this.easeInCore(gradient);
  41904. case EasingFunction.EASINGMODE_EASEOUT:
  41905. return (1 - this.easeInCore(1 - gradient));
  41906. }
  41907. if (gradient >= 0.5) {
  41908. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  41909. }
  41910. return (this.easeInCore(gradient * 2) * 0.5);
  41911. };
  41912. //Statics
  41913. EasingFunction._EASINGMODE_EASEIN = 0;
  41914. EasingFunction._EASINGMODE_EASEOUT = 1;
  41915. EasingFunction._EASINGMODE_EASEINOUT = 2;
  41916. return EasingFunction;
  41917. }());
  41918. BABYLON.EasingFunction = EasingFunction;
  41919. var CircleEase = /** @class */ (function (_super) {
  41920. __extends(CircleEase, _super);
  41921. function CircleEase() {
  41922. return _super !== null && _super.apply(this, arguments) || this;
  41923. }
  41924. CircleEase.prototype.easeInCore = function (gradient) {
  41925. gradient = Math.max(0, Math.min(1, gradient));
  41926. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  41927. };
  41928. return CircleEase;
  41929. }(EasingFunction));
  41930. BABYLON.CircleEase = CircleEase;
  41931. var BackEase = /** @class */ (function (_super) {
  41932. __extends(BackEase, _super);
  41933. function BackEase(amplitude) {
  41934. if (amplitude === void 0) { amplitude = 1; }
  41935. var _this = _super.call(this) || this;
  41936. _this.amplitude = amplitude;
  41937. return _this;
  41938. }
  41939. BackEase.prototype.easeInCore = function (gradient) {
  41940. var num = Math.max(0, this.amplitude);
  41941. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  41942. };
  41943. return BackEase;
  41944. }(EasingFunction));
  41945. BABYLON.BackEase = BackEase;
  41946. var BounceEase = /** @class */ (function (_super) {
  41947. __extends(BounceEase, _super);
  41948. function BounceEase(bounces, bounciness) {
  41949. if (bounces === void 0) { bounces = 3; }
  41950. if (bounciness === void 0) { bounciness = 2; }
  41951. var _this = _super.call(this) || this;
  41952. _this.bounces = bounces;
  41953. _this.bounciness = bounciness;
  41954. return _this;
  41955. }
  41956. BounceEase.prototype.easeInCore = function (gradient) {
  41957. var y = Math.max(0.0, this.bounces);
  41958. var bounciness = this.bounciness;
  41959. if (bounciness <= 1.0) {
  41960. bounciness = 1.001;
  41961. }
  41962. var num9 = Math.pow(bounciness, y);
  41963. var num5 = 1.0 - bounciness;
  41964. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  41965. var num15 = gradient * num4;
  41966. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  41967. var num3 = Math.floor(num65);
  41968. var num13 = num3 + 1.0;
  41969. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  41970. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  41971. var num7 = (num8 + num12) * 0.5;
  41972. var num6 = gradient - num7;
  41973. var num2 = num7 - num8;
  41974. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  41975. };
  41976. return BounceEase;
  41977. }(EasingFunction));
  41978. BABYLON.BounceEase = BounceEase;
  41979. var CubicEase = /** @class */ (function (_super) {
  41980. __extends(CubicEase, _super);
  41981. function CubicEase() {
  41982. return _super !== null && _super.apply(this, arguments) || this;
  41983. }
  41984. CubicEase.prototype.easeInCore = function (gradient) {
  41985. return (gradient * gradient * gradient);
  41986. };
  41987. return CubicEase;
  41988. }(EasingFunction));
  41989. BABYLON.CubicEase = CubicEase;
  41990. var ElasticEase = /** @class */ (function (_super) {
  41991. __extends(ElasticEase, _super);
  41992. function ElasticEase(oscillations, springiness) {
  41993. if (oscillations === void 0) { oscillations = 3; }
  41994. if (springiness === void 0) { springiness = 3; }
  41995. var _this = _super.call(this) || this;
  41996. _this.oscillations = oscillations;
  41997. _this.springiness = springiness;
  41998. return _this;
  41999. }
  42000. ElasticEase.prototype.easeInCore = function (gradient) {
  42001. var num2;
  42002. var num3 = Math.max(0.0, this.oscillations);
  42003. var num = Math.max(0.0, this.springiness);
  42004. if (num == 0) {
  42005. num2 = gradient;
  42006. }
  42007. else {
  42008. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  42009. }
  42010. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  42011. };
  42012. return ElasticEase;
  42013. }(EasingFunction));
  42014. BABYLON.ElasticEase = ElasticEase;
  42015. var ExponentialEase = /** @class */ (function (_super) {
  42016. __extends(ExponentialEase, _super);
  42017. function ExponentialEase(exponent) {
  42018. if (exponent === void 0) { exponent = 2; }
  42019. var _this = _super.call(this) || this;
  42020. _this.exponent = exponent;
  42021. return _this;
  42022. }
  42023. ExponentialEase.prototype.easeInCore = function (gradient) {
  42024. if (this.exponent <= 0) {
  42025. return gradient;
  42026. }
  42027. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  42028. };
  42029. return ExponentialEase;
  42030. }(EasingFunction));
  42031. BABYLON.ExponentialEase = ExponentialEase;
  42032. var PowerEase = /** @class */ (function (_super) {
  42033. __extends(PowerEase, _super);
  42034. function PowerEase(power) {
  42035. if (power === void 0) { power = 2; }
  42036. var _this = _super.call(this) || this;
  42037. _this.power = power;
  42038. return _this;
  42039. }
  42040. PowerEase.prototype.easeInCore = function (gradient) {
  42041. var y = Math.max(0.0, this.power);
  42042. return Math.pow(gradient, y);
  42043. };
  42044. return PowerEase;
  42045. }(EasingFunction));
  42046. BABYLON.PowerEase = PowerEase;
  42047. var QuadraticEase = /** @class */ (function (_super) {
  42048. __extends(QuadraticEase, _super);
  42049. function QuadraticEase() {
  42050. return _super !== null && _super.apply(this, arguments) || this;
  42051. }
  42052. QuadraticEase.prototype.easeInCore = function (gradient) {
  42053. return (gradient * gradient);
  42054. };
  42055. return QuadraticEase;
  42056. }(EasingFunction));
  42057. BABYLON.QuadraticEase = QuadraticEase;
  42058. var QuarticEase = /** @class */ (function (_super) {
  42059. __extends(QuarticEase, _super);
  42060. function QuarticEase() {
  42061. return _super !== null && _super.apply(this, arguments) || this;
  42062. }
  42063. QuarticEase.prototype.easeInCore = function (gradient) {
  42064. return (gradient * gradient * gradient * gradient);
  42065. };
  42066. return QuarticEase;
  42067. }(EasingFunction));
  42068. BABYLON.QuarticEase = QuarticEase;
  42069. var QuinticEase = /** @class */ (function (_super) {
  42070. __extends(QuinticEase, _super);
  42071. function QuinticEase() {
  42072. return _super !== null && _super.apply(this, arguments) || this;
  42073. }
  42074. QuinticEase.prototype.easeInCore = function (gradient) {
  42075. return (gradient * gradient * gradient * gradient * gradient);
  42076. };
  42077. return QuinticEase;
  42078. }(EasingFunction));
  42079. BABYLON.QuinticEase = QuinticEase;
  42080. var SineEase = /** @class */ (function (_super) {
  42081. __extends(SineEase, _super);
  42082. function SineEase() {
  42083. return _super !== null && _super.apply(this, arguments) || this;
  42084. }
  42085. SineEase.prototype.easeInCore = function (gradient) {
  42086. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  42087. };
  42088. return SineEase;
  42089. }(EasingFunction));
  42090. BABYLON.SineEase = SineEase;
  42091. var BezierCurveEase = /** @class */ (function (_super) {
  42092. __extends(BezierCurveEase, _super);
  42093. function BezierCurveEase(x1, y1, x2, y2) {
  42094. if (x1 === void 0) { x1 = 0; }
  42095. if (y1 === void 0) { y1 = 0; }
  42096. if (x2 === void 0) { x2 = 1; }
  42097. if (y2 === void 0) { y2 = 1; }
  42098. var _this = _super.call(this) || this;
  42099. _this.x1 = x1;
  42100. _this.y1 = y1;
  42101. _this.x2 = x2;
  42102. _this.y2 = y2;
  42103. return _this;
  42104. }
  42105. BezierCurveEase.prototype.easeInCore = function (gradient) {
  42106. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  42107. };
  42108. return BezierCurveEase;
  42109. }(EasingFunction));
  42110. BABYLON.BezierCurveEase = BezierCurveEase;
  42111. })(BABYLON || (BABYLON = {}));
  42112. //# sourceMappingURL=babylon.easing.js.map
  42113. var BABYLON;
  42114. (function (BABYLON) {
  42115. var Condition = /** @class */ (function () {
  42116. function Condition(actionManager) {
  42117. this._actionManager = actionManager;
  42118. }
  42119. Condition.prototype.isValid = function () {
  42120. return true;
  42121. };
  42122. Condition.prototype._getProperty = function (propertyPath) {
  42123. return this._actionManager._getProperty(propertyPath);
  42124. };
  42125. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  42126. return this._actionManager._getEffectiveTarget(target, propertyPath);
  42127. };
  42128. Condition.prototype.serialize = function () {
  42129. };
  42130. Condition.prototype._serialize = function (serializedCondition) {
  42131. return {
  42132. type: 2,
  42133. children: [],
  42134. name: serializedCondition.name,
  42135. properties: serializedCondition.properties
  42136. };
  42137. };
  42138. return Condition;
  42139. }());
  42140. BABYLON.Condition = Condition;
  42141. var ValueCondition = /** @class */ (function (_super) {
  42142. __extends(ValueCondition, _super);
  42143. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  42144. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  42145. var _this = _super.call(this, actionManager) || this;
  42146. _this.propertyPath = propertyPath;
  42147. _this.value = value;
  42148. _this.operator = operator;
  42149. _this._target = target;
  42150. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  42151. _this._property = _this._getProperty(_this.propertyPath);
  42152. return _this;
  42153. }
  42154. Object.defineProperty(ValueCondition, "IsEqual", {
  42155. get: function () {
  42156. return ValueCondition._IsEqual;
  42157. },
  42158. enumerable: true,
  42159. configurable: true
  42160. });
  42161. Object.defineProperty(ValueCondition, "IsDifferent", {
  42162. get: function () {
  42163. return ValueCondition._IsDifferent;
  42164. },
  42165. enumerable: true,
  42166. configurable: true
  42167. });
  42168. Object.defineProperty(ValueCondition, "IsGreater", {
  42169. get: function () {
  42170. return ValueCondition._IsGreater;
  42171. },
  42172. enumerable: true,
  42173. configurable: true
  42174. });
  42175. Object.defineProperty(ValueCondition, "IsLesser", {
  42176. get: function () {
  42177. return ValueCondition._IsLesser;
  42178. },
  42179. enumerable: true,
  42180. configurable: true
  42181. });
  42182. // Methods
  42183. ValueCondition.prototype.isValid = function () {
  42184. switch (this.operator) {
  42185. case ValueCondition.IsGreater:
  42186. return this._effectiveTarget[this._property] > this.value;
  42187. case ValueCondition.IsLesser:
  42188. return this._effectiveTarget[this._property] < this.value;
  42189. case ValueCondition.IsEqual:
  42190. case ValueCondition.IsDifferent:
  42191. var check;
  42192. if (this.value.equals) {
  42193. check = this.value.equals(this._effectiveTarget[this._property]);
  42194. }
  42195. else {
  42196. check = this.value === this._effectiveTarget[this._property];
  42197. }
  42198. return this.operator === ValueCondition.IsEqual ? check : !check;
  42199. }
  42200. return false;
  42201. };
  42202. ValueCondition.prototype.serialize = function () {
  42203. return this._serialize({
  42204. name: "ValueCondition",
  42205. properties: [
  42206. BABYLON.Action._GetTargetProperty(this._target),
  42207. { name: "propertyPath", value: this.propertyPath },
  42208. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  42209. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  42210. ]
  42211. });
  42212. };
  42213. ValueCondition.GetOperatorName = function (operator) {
  42214. switch (operator) {
  42215. case ValueCondition._IsEqual: return "IsEqual";
  42216. case ValueCondition._IsDifferent: return "IsDifferent";
  42217. case ValueCondition._IsGreater: return "IsGreater";
  42218. case ValueCondition._IsLesser: return "IsLesser";
  42219. default: return "";
  42220. }
  42221. };
  42222. // Statics
  42223. ValueCondition._IsEqual = 0;
  42224. ValueCondition._IsDifferent = 1;
  42225. ValueCondition._IsGreater = 2;
  42226. ValueCondition._IsLesser = 3;
  42227. return ValueCondition;
  42228. }(Condition));
  42229. BABYLON.ValueCondition = ValueCondition;
  42230. var PredicateCondition = /** @class */ (function (_super) {
  42231. __extends(PredicateCondition, _super);
  42232. function PredicateCondition(actionManager, predicate) {
  42233. var _this = _super.call(this, actionManager) || this;
  42234. _this.predicate = predicate;
  42235. return _this;
  42236. }
  42237. PredicateCondition.prototype.isValid = function () {
  42238. return this.predicate();
  42239. };
  42240. return PredicateCondition;
  42241. }(Condition));
  42242. BABYLON.PredicateCondition = PredicateCondition;
  42243. var StateCondition = /** @class */ (function (_super) {
  42244. __extends(StateCondition, _super);
  42245. function StateCondition(actionManager, target, value) {
  42246. var _this = _super.call(this, actionManager) || this;
  42247. _this.value = value;
  42248. _this._target = target;
  42249. return _this;
  42250. }
  42251. // Methods
  42252. StateCondition.prototype.isValid = function () {
  42253. return this._target.state === this.value;
  42254. };
  42255. StateCondition.prototype.serialize = function () {
  42256. return this._serialize({
  42257. name: "StateCondition",
  42258. properties: [
  42259. BABYLON.Action._GetTargetProperty(this._target),
  42260. { name: "value", value: this.value }
  42261. ]
  42262. });
  42263. };
  42264. return StateCondition;
  42265. }(Condition));
  42266. BABYLON.StateCondition = StateCondition;
  42267. })(BABYLON || (BABYLON = {}));
  42268. //# sourceMappingURL=babylon.condition.js.map
  42269. var BABYLON;
  42270. (function (BABYLON) {
  42271. var Action = /** @class */ (function () {
  42272. function Action(triggerOptions, condition) {
  42273. this.triggerOptions = triggerOptions;
  42274. this.onBeforeExecuteObservable = new BABYLON.Observable();
  42275. if (triggerOptions.parameter) {
  42276. this.trigger = triggerOptions.trigger;
  42277. this._triggerParameter = triggerOptions.parameter;
  42278. }
  42279. else {
  42280. this.trigger = triggerOptions;
  42281. }
  42282. this._nextActiveAction = this;
  42283. this._condition = condition;
  42284. }
  42285. // Methods
  42286. Action.prototype._prepare = function () {
  42287. };
  42288. Action.prototype.getTriggerParameter = function () {
  42289. return this._triggerParameter;
  42290. };
  42291. Action.prototype._executeCurrent = function (evt) {
  42292. if (this._nextActiveAction._condition) {
  42293. var condition = this._nextActiveAction._condition;
  42294. var currentRenderId = this._actionManager.getScene().getRenderId();
  42295. // We cache the current evaluation for the current frame
  42296. if (condition._evaluationId === currentRenderId) {
  42297. if (!condition._currentResult) {
  42298. return;
  42299. }
  42300. }
  42301. else {
  42302. condition._evaluationId = currentRenderId;
  42303. if (!condition.isValid()) {
  42304. condition._currentResult = false;
  42305. return;
  42306. }
  42307. condition._currentResult = true;
  42308. }
  42309. }
  42310. this.onBeforeExecuteObservable.notifyObservers(this);
  42311. this._nextActiveAction.execute(evt);
  42312. this.skipToNextActiveAction();
  42313. };
  42314. Action.prototype.execute = function (evt) {
  42315. };
  42316. Action.prototype.skipToNextActiveAction = function () {
  42317. if (this._nextActiveAction._child) {
  42318. if (!this._nextActiveAction._child._actionManager) {
  42319. this._nextActiveAction._child._actionManager = this._actionManager;
  42320. }
  42321. this._nextActiveAction = this._nextActiveAction._child;
  42322. }
  42323. else {
  42324. this._nextActiveAction = this;
  42325. }
  42326. };
  42327. Action.prototype.then = function (action) {
  42328. this._child = action;
  42329. action._actionManager = this._actionManager;
  42330. action._prepare();
  42331. return action;
  42332. };
  42333. Action.prototype._getProperty = function (propertyPath) {
  42334. return this._actionManager._getProperty(propertyPath);
  42335. };
  42336. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  42337. return this._actionManager._getEffectiveTarget(target, propertyPath);
  42338. };
  42339. Action.prototype.serialize = function (parent) {
  42340. };
  42341. // Called by BABYLON.Action objects in serialize(...). Internal use
  42342. Action.prototype._serialize = function (serializedAction, parent) {
  42343. var serializationObject = {
  42344. type: 1,
  42345. children: [],
  42346. name: serializedAction.name,
  42347. properties: serializedAction.properties || []
  42348. };
  42349. // Serialize child
  42350. if (this._child) {
  42351. this._child.serialize(serializationObject);
  42352. }
  42353. // Check if "this" has a condition
  42354. if (this._condition) {
  42355. var serializedCondition = this._condition.serialize();
  42356. serializedCondition.children.push(serializationObject);
  42357. if (parent) {
  42358. parent.children.push(serializedCondition);
  42359. }
  42360. return serializedCondition;
  42361. }
  42362. if (parent) {
  42363. parent.children.push(serializationObject);
  42364. }
  42365. return serializationObject;
  42366. };
  42367. Action._SerializeValueAsString = function (value) {
  42368. if (typeof value === "number") {
  42369. return value.toString();
  42370. }
  42371. if (typeof value === "boolean") {
  42372. return value ? "true" : "false";
  42373. }
  42374. if (value instanceof BABYLON.Vector2) {
  42375. return value.x + ", " + value.y;
  42376. }
  42377. if (value instanceof BABYLON.Vector3) {
  42378. return value.x + ", " + value.y + ", " + value.z;
  42379. }
  42380. if (value instanceof BABYLON.Color3) {
  42381. return value.r + ", " + value.g + ", " + value.b;
  42382. }
  42383. if (value instanceof BABYLON.Color4) {
  42384. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  42385. }
  42386. return value; // string
  42387. };
  42388. Action._GetTargetProperty = function (target) {
  42389. return {
  42390. name: "target",
  42391. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  42392. : target instanceof BABYLON.Light ? "LightProperties"
  42393. : target instanceof BABYLON.Camera ? "CameraProperties"
  42394. : "SceneProperties",
  42395. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  42396. };
  42397. };
  42398. return Action;
  42399. }());
  42400. BABYLON.Action = Action;
  42401. })(BABYLON || (BABYLON = {}));
  42402. //# sourceMappingURL=babylon.action.js.map
  42403. var BABYLON;
  42404. (function (BABYLON) {
  42405. /**
  42406. * ActionEvent is the event beint sent when an action is triggered.
  42407. */
  42408. var ActionEvent = /** @class */ (function () {
  42409. /**
  42410. * @param source The mesh or sprite that triggered the action.
  42411. * @param pointerX The X mouse cursor position at the time of the event
  42412. * @param pointerY The Y mouse cursor position at the time of the event
  42413. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  42414. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  42415. */
  42416. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  42417. this.source = source;
  42418. this.pointerX = pointerX;
  42419. this.pointerY = pointerY;
  42420. this.meshUnderPointer = meshUnderPointer;
  42421. this.sourceEvent = sourceEvent;
  42422. this.additionalData = additionalData;
  42423. }
  42424. /**
  42425. * Helper function to auto-create an ActionEvent from a source mesh.
  42426. * @param source The source mesh that triggered the event
  42427. * @param evt {Event} The original (browser) event
  42428. */
  42429. ActionEvent.CreateNew = function (source, evt, additionalData) {
  42430. var scene = source.getScene();
  42431. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  42432. };
  42433. /**
  42434. * Helper function to auto-create an ActionEvent from a source mesh.
  42435. * @param source The source sprite that triggered the event
  42436. * @param scene Scene associated with the sprite
  42437. * @param evt {Event} The original (browser) event
  42438. */
  42439. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  42440. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  42441. };
  42442. /**
  42443. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  42444. * @param scene the scene where the event occurred
  42445. * @param evt {Event} The original (browser) event
  42446. */
  42447. ActionEvent.CreateNewFromScene = function (scene, evt) {
  42448. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  42449. };
  42450. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  42451. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  42452. };
  42453. return ActionEvent;
  42454. }());
  42455. BABYLON.ActionEvent = ActionEvent;
  42456. /**
  42457. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  42458. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  42459. */
  42460. var ActionManager = /** @class */ (function () {
  42461. function ActionManager(scene) {
  42462. // Members
  42463. this.actions = new Array();
  42464. this.hoverCursor = '';
  42465. this._scene = scene;
  42466. scene._actionManagers.push(this);
  42467. }
  42468. Object.defineProperty(ActionManager, "NothingTrigger", {
  42469. get: function () {
  42470. return ActionManager._NothingTrigger;
  42471. },
  42472. enumerable: true,
  42473. configurable: true
  42474. });
  42475. Object.defineProperty(ActionManager, "OnPickTrigger", {
  42476. get: function () {
  42477. return ActionManager._OnPickTrigger;
  42478. },
  42479. enumerable: true,
  42480. configurable: true
  42481. });
  42482. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  42483. get: function () {
  42484. return ActionManager._OnLeftPickTrigger;
  42485. },
  42486. enumerable: true,
  42487. configurable: true
  42488. });
  42489. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  42490. get: function () {
  42491. return ActionManager._OnRightPickTrigger;
  42492. },
  42493. enumerable: true,
  42494. configurable: true
  42495. });
  42496. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  42497. get: function () {
  42498. return ActionManager._OnCenterPickTrigger;
  42499. },
  42500. enumerable: true,
  42501. configurable: true
  42502. });
  42503. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  42504. get: function () {
  42505. return ActionManager._OnPickDownTrigger;
  42506. },
  42507. enumerable: true,
  42508. configurable: true
  42509. });
  42510. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  42511. get: function () {
  42512. return ActionManager._OnDoublePickTrigger;
  42513. },
  42514. enumerable: true,
  42515. configurable: true
  42516. });
  42517. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  42518. get: function () {
  42519. return ActionManager._OnPickUpTrigger;
  42520. },
  42521. enumerable: true,
  42522. configurable: true
  42523. });
  42524. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  42525. /// This trigger will only be raised if you also declared a OnPickDown
  42526. get: function () {
  42527. return ActionManager._OnPickOutTrigger;
  42528. },
  42529. enumerable: true,
  42530. configurable: true
  42531. });
  42532. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  42533. get: function () {
  42534. return ActionManager._OnLongPressTrigger;
  42535. },
  42536. enumerable: true,
  42537. configurable: true
  42538. });
  42539. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  42540. get: function () {
  42541. return ActionManager._OnPointerOverTrigger;
  42542. },
  42543. enumerable: true,
  42544. configurable: true
  42545. });
  42546. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  42547. get: function () {
  42548. return ActionManager._OnPointerOutTrigger;
  42549. },
  42550. enumerable: true,
  42551. configurable: true
  42552. });
  42553. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  42554. get: function () {
  42555. return ActionManager._OnEveryFrameTrigger;
  42556. },
  42557. enumerable: true,
  42558. configurable: true
  42559. });
  42560. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  42561. get: function () {
  42562. return ActionManager._OnIntersectionEnterTrigger;
  42563. },
  42564. enumerable: true,
  42565. configurable: true
  42566. });
  42567. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  42568. get: function () {
  42569. return ActionManager._OnIntersectionExitTrigger;
  42570. },
  42571. enumerable: true,
  42572. configurable: true
  42573. });
  42574. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  42575. get: function () {
  42576. return ActionManager._OnKeyDownTrigger;
  42577. },
  42578. enumerable: true,
  42579. configurable: true
  42580. });
  42581. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  42582. get: function () {
  42583. return ActionManager._OnKeyUpTrigger;
  42584. },
  42585. enumerable: true,
  42586. configurable: true
  42587. });
  42588. // Methods
  42589. ActionManager.prototype.dispose = function () {
  42590. var index = this._scene._actionManagers.indexOf(this);
  42591. for (var i = 0; i < this.actions.length; i++) {
  42592. var action = this.actions[i];
  42593. ActionManager.Triggers[action.trigger]--;
  42594. if (ActionManager.Triggers[action.trigger] === 0) {
  42595. delete ActionManager.Triggers[action.trigger];
  42596. }
  42597. }
  42598. if (index > -1) {
  42599. this._scene._actionManagers.splice(index, 1);
  42600. }
  42601. };
  42602. ActionManager.prototype.getScene = function () {
  42603. return this._scene;
  42604. };
  42605. /**
  42606. * Does this action manager handles actions of any of the given triggers
  42607. * @param {number[]} triggers - the triggers to be tested
  42608. * @return {boolean} whether one (or more) of the triggers is handeled
  42609. */
  42610. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  42611. for (var index = 0; index < this.actions.length; index++) {
  42612. var action = this.actions[index];
  42613. if (triggers.indexOf(action.trigger) > -1) {
  42614. return true;
  42615. }
  42616. }
  42617. return false;
  42618. };
  42619. /**
  42620. * Does this action manager handles actions of a given trigger
  42621. * @param {number} trigger - the trigger to be tested
  42622. * @return {boolean} whether the trigger is handeled
  42623. */
  42624. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  42625. for (var index = 0; index < this.actions.length; index++) {
  42626. var action = this.actions[index];
  42627. if (action.trigger === trigger) {
  42628. return true;
  42629. }
  42630. }
  42631. return false;
  42632. };
  42633. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  42634. /**
  42635. * Does this action manager has pointer triggers
  42636. * @return {boolean} whether or not it has pointer triggers
  42637. */
  42638. get: function () {
  42639. for (var index = 0; index < this.actions.length; index++) {
  42640. var action = this.actions[index];
  42641. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  42642. return true;
  42643. }
  42644. }
  42645. return false;
  42646. },
  42647. enumerable: true,
  42648. configurable: true
  42649. });
  42650. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  42651. /**
  42652. * Does this action manager has pick triggers
  42653. * @return {boolean} whether or not it has pick triggers
  42654. */
  42655. get: function () {
  42656. for (var index = 0; index < this.actions.length; index++) {
  42657. var action = this.actions[index];
  42658. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  42659. return true;
  42660. }
  42661. }
  42662. return false;
  42663. },
  42664. enumerable: true,
  42665. configurable: true
  42666. });
  42667. Object.defineProperty(ActionManager, "HasTriggers", {
  42668. /**
  42669. * Does exist one action manager with at least one trigger
  42670. * @return {boolean} whether or not it exists one action manager with one trigger
  42671. **/
  42672. get: function () {
  42673. for (var t in ActionManager.Triggers) {
  42674. if (ActionManager.Triggers.hasOwnProperty(t)) {
  42675. return true;
  42676. }
  42677. }
  42678. return false;
  42679. },
  42680. enumerable: true,
  42681. configurable: true
  42682. });
  42683. Object.defineProperty(ActionManager, "HasPickTriggers", {
  42684. /**
  42685. * Does exist one action manager with at least one pick trigger
  42686. * @return {boolean} whether or not it exists one action manager with one pick trigger
  42687. **/
  42688. get: function () {
  42689. for (var t in ActionManager.Triggers) {
  42690. if (ActionManager.Triggers.hasOwnProperty(t)) {
  42691. var t_int = parseInt(t);
  42692. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  42693. return true;
  42694. }
  42695. }
  42696. }
  42697. return false;
  42698. },
  42699. enumerable: true,
  42700. configurable: true
  42701. });
  42702. /**
  42703. * Does exist one action manager that handles actions of a given trigger
  42704. * @param {number} trigger - the trigger to be tested
  42705. * @return {boolean} whether the trigger is handeled by at least one action manager
  42706. **/
  42707. ActionManager.HasSpecificTrigger = function (trigger) {
  42708. for (var t in ActionManager.Triggers) {
  42709. if (ActionManager.Triggers.hasOwnProperty(t)) {
  42710. var t_int = parseInt(t);
  42711. if (t_int === trigger) {
  42712. return true;
  42713. }
  42714. }
  42715. }
  42716. return false;
  42717. };
  42718. /**
  42719. * Registers an action to this action manager
  42720. * @param {BABYLON.Action} action - the action to be registered
  42721. * @return {BABYLON.Action} the action amended (prepared) after registration
  42722. */
  42723. ActionManager.prototype.registerAction = function (action) {
  42724. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  42725. if (this.getScene().actionManager !== this) {
  42726. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  42727. return null;
  42728. }
  42729. }
  42730. this.actions.push(action);
  42731. if (ActionManager.Triggers[action.trigger]) {
  42732. ActionManager.Triggers[action.trigger]++;
  42733. }
  42734. else {
  42735. ActionManager.Triggers[action.trigger] = 1;
  42736. }
  42737. action._actionManager = this;
  42738. action._prepare();
  42739. return action;
  42740. };
  42741. /**
  42742. * Process a specific trigger
  42743. * @param {number} trigger - the trigger to process
  42744. * @param evt {BABYLON.ActionEvent} the event details to be processed
  42745. */
  42746. ActionManager.prototype.processTrigger = function (trigger, evt) {
  42747. for (var index = 0; index < this.actions.length; index++) {
  42748. var action = this.actions[index];
  42749. if (action.trigger === trigger) {
  42750. if (evt) {
  42751. if (trigger === ActionManager.OnKeyUpTrigger
  42752. || trigger === ActionManager.OnKeyDownTrigger) {
  42753. var parameter = action.getTriggerParameter();
  42754. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  42755. if (!parameter.toLowerCase) {
  42756. continue;
  42757. }
  42758. var lowerCase = parameter.toLowerCase();
  42759. if (lowerCase !== evt.sourceEvent.key) {
  42760. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  42761. var actualkey = String.fromCharCode(unicode).toLowerCase();
  42762. if (actualkey !== lowerCase) {
  42763. continue;
  42764. }
  42765. }
  42766. }
  42767. }
  42768. }
  42769. action._executeCurrent(evt);
  42770. }
  42771. }
  42772. };
  42773. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  42774. var properties = propertyPath.split(".");
  42775. for (var index = 0; index < properties.length - 1; index++) {
  42776. target = target[properties[index]];
  42777. }
  42778. return target;
  42779. };
  42780. ActionManager.prototype._getProperty = function (propertyPath) {
  42781. var properties = propertyPath.split(".");
  42782. return properties[properties.length - 1];
  42783. };
  42784. ActionManager.prototype.serialize = function (name) {
  42785. var root = {
  42786. children: new Array(),
  42787. name: name,
  42788. type: 3,
  42789. properties: new Array() // Empty for root but required
  42790. };
  42791. for (var i = 0; i < this.actions.length; i++) {
  42792. var triggerObject = {
  42793. type: 0,
  42794. children: new Array(),
  42795. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  42796. properties: new Array()
  42797. };
  42798. var triggerOptions = this.actions[i].triggerOptions;
  42799. if (triggerOptions && typeof triggerOptions !== "number") {
  42800. if (triggerOptions.parameter instanceof BABYLON.Node) {
  42801. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  42802. }
  42803. else {
  42804. var parameter = {};
  42805. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  42806. if (triggerOptions.parameter.mesh) {
  42807. parameter._meshId = triggerOptions.parameter.mesh.id;
  42808. }
  42809. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  42810. }
  42811. }
  42812. // Serialize child action, recursively
  42813. this.actions[i].serialize(triggerObject);
  42814. // Add serialized trigger
  42815. root.children.push(triggerObject);
  42816. }
  42817. return root;
  42818. };
  42819. ActionManager.Parse = function (parsedActions, object, scene) {
  42820. var actionManager = new BABYLON.ActionManager(scene);
  42821. if (object === null)
  42822. scene.actionManager = actionManager;
  42823. else
  42824. object.actionManager = actionManager;
  42825. // instanciate a new object
  42826. var instanciate = function (name, params) {
  42827. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  42828. newInstance.constructor.apply(newInstance, params);
  42829. return newInstance;
  42830. };
  42831. var parseParameter = function (name, value, target, propertyPath) {
  42832. if (propertyPath === null) {
  42833. // String, boolean or float
  42834. var floatValue = parseFloat(value);
  42835. if (value === "true" || value === "false")
  42836. return value === "true";
  42837. else
  42838. return isNaN(floatValue) ? value : floatValue;
  42839. }
  42840. var effectiveTarget = propertyPath.split(".");
  42841. var values = value.split(",");
  42842. // Get effective Target
  42843. for (var i = 0; i < effectiveTarget.length; i++) {
  42844. target = target[effectiveTarget[i]];
  42845. }
  42846. // Return appropriate value with its type
  42847. if (typeof (target) === "boolean")
  42848. return values[0] === "true";
  42849. if (typeof (target) === "string")
  42850. return values[0];
  42851. // Parameters with multiple values such as Vector3 etc.
  42852. var split = new Array();
  42853. for (var i = 0; i < values.length; i++)
  42854. split.push(parseFloat(values[i]));
  42855. if (target instanceof BABYLON.Vector3)
  42856. return BABYLON.Vector3.FromArray(split);
  42857. if (target instanceof BABYLON.Vector4)
  42858. return BABYLON.Vector4.FromArray(split);
  42859. if (target instanceof BABYLON.Color3)
  42860. return BABYLON.Color3.FromArray(split);
  42861. if (target instanceof BABYLON.Color4)
  42862. return BABYLON.Color4.FromArray(split);
  42863. return parseFloat(values[0]);
  42864. };
  42865. // traverse graph per trigger
  42866. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  42867. if (combineArray === void 0) { combineArray = null; }
  42868. if (parsedAction.detached)
  42869. return;
  42870. var parameters = new Array();
  42871. var target = null;
  42872. var propertyPath = null;
  42873. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  42874. // Parameters
  42875. if (parsedAction.type === 2)
  42876. parameters.push(actionManager);
  42877. else
  42878. parameters.push(trigger);
  42879. if (combine) {
  42880. var actions = new Array();
  42881. for (var j = 0; j < parsedAction.combine.length; j++) {
  42882. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  42883. }
  42884. parameters.push(actions);
  42885. }
  42886. else {
  42887. for (var i = 0; i < parsedAction.properties.length; i++) {
  42888. var value = parsedAction.properties[i].value;
  42889. var name = parsedAction.properties[i].name;
  42890. var targetType = parsedAction.properties[i].targetType;
  42891. if (name === "target")
  42892. if (targetType !== null && targetType === "SceneProperties")
  42893. value = target = scene;
  42894. else
  42895. value = target = scene.getNodeByName(value);
  42896. else if (name === "parent")
  42897. value = scene.getNodeByName(value);
  42898. else if (name === "sound")
  42899. value = scene.getSoundByName(value);
  42900. else if (name !== "propertyPath") {
  42901. if (parsedAction.type === 2 && name === "operator")
  42902. value = BABYLON.ValueCondition[value];
  42903. else
  42904. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  42905. }
  42906. else {
  42907. propertyPath = value;
  42908. }
  42909. parameters.push(value);
  42910. }
  42911. }
  42912. if (combineArray === null) {
  42913. parameters.push(condition);
  42914. }
  42915. else {
  42916. parameters.push(null);
  42917. }
  42918. // If interpolate value action
  42919. if (parsedAction.name === "InterpolateValueAction") {
  42920. var param = parameters[parameters.length - 2];
  42921. parameters[parameters.length - 1] = param;
  42922. parameters[parameters.length - 2] = condition;
  42923. }
  42924. // Action or condition(s) and not CombineAction
  42925. var newAction = instanciate(parsedAction.name, parameters);
  42926. if (newAction instanceof BABYLON.Condition && condition !== null) {
  42927. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  42928. if (action)
  42929. action.then(nothing);
  42930. else
  42931. actionManager.registerAction(nothing);
  42932. action = nothing;
  42933. }
  42934. if (combineArray === null) {
  42935. if (newAction instanceof BABYLON.Condition) {
  42936. condition = newAction;
  42937. newAction = action;
  42938. }
  42939. else {
  42940. condition = null;
  42941. if (action)
  42942. action.then(newAction);
  42943. else
  42944. actionManager.registerAction(newAction);
  42945. }
  42946. }
  42947. else {
  42948. combineArray.push(newAction);
  42949. }
  42950. for (var i = 0; i < parsedAction.children.length; i++)
  42951. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  42952. };
  42953. // triggers
  42954. for (var i = 0; i < parsedActions.children.length; i++) {
  42955. var triggerParams;
  42956. var trigger = parsedActions.children[i];
  42957. if (trigger.properties.length > 0) {
  42958. var param = trigger.properties[0].value;
  42959. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  42960. if (value._meshId) {
  42961. value.mesh = scene.getMeshByID(value._meshId);
  42962. }
  42963. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  42964. }
  42965. else
  42966. triggerParams = ActionManager[trigger.name];
  42967. for (var j = 0; j < trigger.children.length; j++) {
  42968. if (!trigger.detached)
  42969. traverse(trigger.children[j], triggerParams, null, null);
  42970. }
  42971. }
  42972. };
  42973. ActionManager.GetTriggerName = function (trigger) {
  42974. switch (trigger) {
  42975. case 0: return "NothingTrigger";
  42976. case 1: return "OnPickTrigger";
  42977. case 2: return "OnLeftPickTrigger";
  42978. case 3: return "OnRightPickTrigger";
  42979. case 4: return "OnCenterPickTrigger";
  42980. case 5: return "OnPickDownTrigger";
  42981. case 6: return "OnPickUpTrigger";
  42982. case 7: return "OnLongPressTrigger";
  42983. case 8: return "OnPointerOverTrigger";
  42984. case 9: return "OnPointerOutTrigger";
  42985. case 10: return "OnEveryFrameTrigger";
  42986. case 11: return "OnIntersectionEnterTrigger";
  42987. case 12: return "OnIntersectionExitTrigger";
  42988. case 13: return "OnKeyDownTrigger";
  42989. case 14: return "OnKeyUpTrigger";
  42990. case 15: return "OnPickOutTrigger";
  42991. default: return "";
  42992. }
  42993. };
  42994. // Statics
  42995. ActionManager._NothingTrigger = 0;
  42996. ActionManager._OnPickTrigger = 1;
  42997. ActionManager._OnLeftPickTrigger = 2;
  42998. ActionManager._OnRightPickTrigger = 3;
  42999. ActionManager._OnCenterPickTrigger = 4;
  43000. ActionManager._OnPickDownTrigger = 5;
  43001. ActionManager._OnDoublePickTrigger = 6;
  43002. ActionManager._OnPickUpTrigger = 7;
  43003. ActionManager._OnLongPressTrigger = 8;
  43004. ActionManager._OnPointerOverTrigger = 9;
  43005. ActionManager._OnPointerOutTrigger = 10;
  43006. ActionManager._OnEveryFrameTrigger = 11;
  43007. ActionManager._OnIntersectionEnterTrigger = 12;
  43008. ActionManager._OnIntersectionExitTrigger = 13;
  43009. ActionManager._OnKeyDownTrigger = 14;
  43010. ActionManager._OnKeyUpTrigger = 15;
  43011. ActionManager._OnPickOutTrigger = 16;
  43012. ActionManager.Triggers = {};
  43013. return ActionManager;
  43014. }());
  43015. BABYLON.ActionManager = ActionManager;
  43016. })(BABYLON || (BABYLON = {}));
  43017. //# sourceMappingURL=babylon.actionManager.js.map
  43018. var BABYLON;
  43019. (function (BABYLON) {
  43020. var InterpolateValueAction = /** @class */ (function (_super) {
  43021. __extends(InterpolateValueAction, _super);
  43022. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  43023. if (duration === void 0) { duration = 1000; }
  43024. var _this = _super.call(this, triggerOptions, condition) || this;
  43025. _this.propertyPath = propertyPath;
  43026. _this.value = value;
  43027. _this.duration = duration;
  43028. _this.stopOtherAnimations = stopOtherAnimations;
  43029. _this.onInterpolationDone = onInterpolationDone;
  43030. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  43031. _this._target = _this._effectiveTarget = target;
  43032. return _this;
  43033. }
  43034. InterpolateValueAction.prototype._prepare = function () {
  43035. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  43036. this._property = this._getProperty(this.propertyPath);
  43037. };
  43038. InterpolateValueAction.prototype.execute = function () {
  43039. var _this = this;
  43040. var scene = this._actionManager.getScene();
  43041. var keys = [
  43042. {
  43043. frame: 0,
  43044. value: this._effectiveTarget[this._property]
  43045. }, {
  43046. frame: 100,
  43047. value: this.value
  43048. }
  43049. ];
  43050. var dataType;
  43051. if (typeof this.value === "number") {
  43052. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  43053. }
  43054. else if (this.value instanceof BABYLON.Color3) {
  43055. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  43056. }
  43057. else if (this.value instanceof BABYLON.Vector3) {
  43058. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  43059. }
  43060. else if (this.value instanceof BABYLON.Matrix) {
  43061. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  43062. }
  43063. else if (this.value instanceof BABYLON.Quaternion) {
  43064. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  43065. }
  43066. else {
  43067. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  43068. return;
  43069. }
  43070. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  43071. animation.setKeys(keys);
  43072. if (this.stopOtherAnimations) {
  43073. scene.stopAnimation(this._effectiveTarget);
  43074. }
  43075. var wrapper = function () {
  43076. _this.onInterpolationDoneObservable.notifyObservers(_this);
  43077. if (_this.onInterpolationDone) {
  43078. _this.onInterpolationDone();
  43079. }
  43080. };
  43081. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  43082. };
  43083. InterpolateValueAction.prototype.serialize = function (parent) {
  43084. return _super.prototype._serialize.call(this, {
  43085. name: "InterpolateValueAction",
  43086. properties: [
  43087. BABYLON.Action._GetTargetProperty(this._target),
  43088. { name: "propertyPath", value: this.propertyPath },
  43089. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  43090. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  43091. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  43092. ]
  43093. }, parent);
  43094. };
  43095. return InterpolateValueAction;
  43096. }(BABYLON.Action));
  43097. BABYLON.InterpolateValueAction = InterpolateValueAction;
  43098. })(BABYLON || (BABYLON = {}));
  43099. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  43100. var BABYLON;
  43101. (function (BABYLON) {
  43102. var SwitchBooleanAction = /** @class */ (function (_super) {
  43103. __extends(SwitchBooleanAction, _super);
  43104. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  43105. var _this = _super.call(this, triggerOptions, condition) || this;
  43106. _this.propertyPath = propertyPath;
  43107. _this._target = _this._effectiveTarget = target;
  43108. return _this;
  43109. }
  43110. SwitchBooleanAction.prototype._prepare = function () {
  43111. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  43112. this._property = this._getProperty(this.propertyPath);
  43113. };
  43114. SwitchBooleanAction.prototype.execute = function () {
  43115. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  43116. };
  43117. SwitchBooleanAction.prototype.serialize = function (parent) {
  43118. return _super.prototype._serialize.call(this, {
  43119. name: "SwitchBooleanAction",
  43120. properties: [
  43121. BABYLON.Action._GetTargetProperty(this._target),
  43122. { name: "propertyPath", value: this.propertyPath }
  43123. ]
  43124. }, parent);
  43125. };
  43126. return SwitchBooleanAction;
  43127. }(BABYLON.Action));
  43128. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  43129. var SetStateAction = /** @class */ (function (_super) {
  43130. __extends(SetStateAction, _super);
  43131. function SetStateAction(triggerOptions, target, value, condition) {
  43132. var _this = _super.call(this, triggerOptions, condition) || this;
  43133. _this.value = value;
  43134. _this._target = target;
  43135. return _this;
  43136. }
  43137. SetStateAction.prototype.execute = function () {
  43138. this._target.state = this.value;
  43139. };
  43140. SetStateAction.prototype.serialize = function (parent) {
  43141. return _super.prototype._serialize.call(this, {
  43142. name: "SetStateAction",
  43143. properties: [
  43144. BABYLON.Action._GetTargetProperty(this._target),
  43145. { name: "value", value: this.value }
  43146. ]
  43147. }, parent);
  43148. };
  43149. return SetStateAction;
  43150. }(BABYLON.Action));
  43151. BABYLON.SetStateAction = SetStateAction;
  43152. var SetValueAction = /** @class */ (function (_super) {
  43153. __extends(SetValueAction, _super);
  43154. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  43155. var _this = _super.call(this, triggerOptions, condition) || this;
  43156. _this.propertyPath = propertyPath;
  43157. _this.value = value;
  43158. _this._target = _this._effectiveTarget = target;
  43159. return _this;
  43160. }
  43161. SetValueAction.prototype._prepare = function () {
  43162. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  43163. this._property = this._getProperty(this.propertyPath);
  43164. };
  43165. SetValueAction.prototype.execute = function () {
  43166. this._effectiveTarget[this._property] = this.value;
  43167. if (this._target.markAsDirty) {
  43168. this._target.markAsDirty(this._property);
  43169. }
  43170. };
  43171. SetValueAction.prototype.serialize = function (parent) {
  43172. return _super.prototype._serialize.call(this, {
  43173. name: "SetValueAction",
  43174. properties: [
  43175. BABYLON.Action._GetTargetProperty(this._target),
  43176. { name: "propertyPath", value: this.propertyPath },
  43177. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  43178. ]
  43179. }, parent);
  43180. };
  43181. return SetValueAction;
  43182. }(BABYLON.Action));
  43183. BABYLON.SetValueAction = SetValueAction;
  43184. var IncrementValueAction = /** @class */ (function (_super) {
  43185. __extends(IncrementValueAction, _super);
  43186. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  43187. var _this = _super.call(this, triggerOptions, condition) || this;
  43188. _this.propertyPath = propertyPath;
  43189. _this.value = value;
  43190. _this._target = _this._effectiveTarget = target;
  43191. return _this;
  43192. }
  43193. IncrementValueAction.prototype._prepare = function () {
  43194. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  43195. this._property = this._getProperty(this.propertyPath);
  43196. if (typeof this._effectiveTarget[this._property] !== "number") {
  43197. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  43198. }
  43199. };
  43200. IncrementValueAction.prototype.execute = function () {
  43201. this._effectiveTarget[this._property] += this.value;
  43202. if (this._target.markAsDirty) {
  43203. this._target.markAsDirty(this._property);
  43204. }
  43205. };
  43206. IncrementValueAction.prototype.serialize = function (parent) {
  43207. return _super.prototype._serialize.call(this, {
  43208. name: "IncrementValueAction",
  43209. properties: [
  43210. BABYLON.Action._GetTargetProperty(this._target),
  43211. { name: "propertyPath", value: this.propertyPath },
  43212. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  43213. ]
  43214. }, parent);
  43215. };
  43216. return IncrementValueAction;
  43217. }(BABYLON.Action));
  43218. BABYLON.IncrementValueAction = IncrementValueAction;
  43219. var PlayAnimationAction = /** @class */ (function (_super) {
  43220. __extends(PlayAnimationAction, _super);
  43221. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  43222. var _this = _super.call(this, triggerOptions, condition) || this;
  43223. _this.from = from;
  43224. _this.to = to;
  43225. _this.loop = loop;
  43226. _this._target = target;
  43227. return _this;
  43228. }
  43229. PlayAnimationAction.prototype._prepare = function () {
  43230. };
  43231. PlayAnimationAction.prototype.execute = function () {
  43232. var scene = this._actionManager.getScene();
  43233. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  43234. };
  43235. PlayAnimationAction.prototype.serialize = function (parent) {
  43236. return _super.prototype._serialize.call(this, {
  43237. name: "PlayAnimationAction",
  43238. properties: [
  43239. BABYLON.Action._GetTargetProperty(this._target),
  43240. { name: "from", value: String(this.from) },
  43241. { name: "to", value: String(this.to) },
  43242. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  43243. ]
  43244. }, parent);
  43245. };
  43246. return PlayAnimationAction;
  43247. }(BABYLON.Action));
  43248. BABYLON.PlayAnimationAction = PlayAnimationAction;
  43249. var StopAnimationAction = /** @class */ (function (_super) {
  43250. __extends(StopAnimationAction, _super);
  43251. function StopAnimationAction(triggerOptions, target, condition) {
  43252. var _this = _super.call(this, triggerOptions, condition) || this;
  43253. _this._target = target;
  43254. return _this;
  43255. }
  43256. StopAnimationAction.prototype._prepare = function () {
  43257. };
  43258. StopAnimationAction.prototype.execute = function () {
  43259. var scene = this._actionManager.getScene();
  43260. scene.stopAnimation(this._target);
  43261. };
  43262. StopAnimationAction.prototype.serialize = function (parent) {
  43263. return _super.prototype._serialize.call(this, {
  43264. name: "StopAnimationAction",
  43265. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  43266. }, parent);
  43267. };
  43268. return StopAnimationAction;
  43269. }(BABYLON.Action));
  43270. BABYLON.StopAnimationAction = StopAnimationAction;
  43271. var DoNothingAction = /** @class */ (function (_super) {
  43272. __extends(DoNothingAction, _super);
  43273. function DoNothingAction(triggerOptions, condition) {
  43274. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  43275. return _super.call(this, triggerOptions, condition) || this;
  43276. }
  43277. DoNothingAction.prototype.execute = function () {
  43278. };
  43279. DoNothingAction.prototype.serialize = function (parent) {
  43280. return _super.prototype._serialize.call(this, {
  43281. name: "DoNothingAction",
  43282. properties: []
  43283. }, parent);
  43284. };
  43285. return DoNothingAction;
  43286. }(BABYLON.Action));
  43287. BABYLON.DoNothingAction = DoNothingAction;
  43288. var CombineAction = /** @class */ (function (_super) {
  43289. __extends(CombineAction, _super);
  43290. function CombineAction(triggerOptions, children, condition) {
  43291. var _this = _super.call(this, triggerOptions, condition) || this;
  43292. _this.children = children;
  43293. return _this;
  43294. }
  43295. CombineAction.prototype._prepare = function () {
  43296. for (var index = 0; index < this.children.length; index++) {
  43297. this.children[index]._actionManager = this._actionManager;
  43298. this.children[index]._prepare();
  43299. }
  43300. };
  43301. CombineAction.prototype.execute = function (evt) {
  43302. for (var index = 0; index < this.children.length; index++) {
  43303. this.children[index].execute(evt);
  43304. }
  43305. };
  43306. CombineAction.prototype.serialize = function (parent) {
  43307. var serializationObject = _super.prototype._serialize.call(this, {
  43308. name: "CombineAction",
  43309. properties: [],
  43310. combine: []
  43311. }, parent);
  43312. for (var i = 0; i < this.children.length; i++) {
  43313. serializationObject.combine.push(this.children[i].serialize(null));
  43314. }
  43315. return serializationObject;
  43316. };
  43317. return CombineAction;
  43318. }(BABYLON.Action));
  43319. BABYLON.CombineAction = CombineAction;
  43320. var ExecuteCodeAction = /** @class */ (function (_super) {
  43321. __extends(ExecuteCodeAction, _super);
  43322. function ExecuteCodeAction(triggerOptions, func, condition) {
  43323. var _this = _super.call(this, triggerOptions, condition) || this;
  43324. _this.func = func;
  43325. return _this;
  43326. }
  43327. ExecuteCodeAction.prototype.execute = function (evt) {
  43328. this.func(evt);
  43329. };
  43330. return ExecuteCodeAction;
  43331. }(BABYLON.Action));
  43332. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  43333. var SetParentAction = /** @class */ (function (_super) {
  43334. __extends(SetParentAction, _super);
  43335. function SetParentAction(triggerOptions, target, parent, condition) {
  43336. var _this = _super.call(this, triggerOptions, condition) || this;
  43337. _this._target = target;
  43338. _this._parent = parent;
  43339. return _this;
  43340. }
  43341. SetParentAction.prototype._prepare = function () {
  43342. };
  43343. SetParentAction.prototype.execute = function () {
  43344. if (this._target.parent === this._parent) {
  43345. return;
  43346. }
  43347. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  43348. invertParentWorldMatrix.invert();
  43349. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  43350. this._target.parent = this._parent;
  43351. };
  43352. SetParentAction.prototype.serialize = function (parent) {
  43353. return _super.prototype._serialize.call(this, {
  43354. name: "SetParentAction",
  43355. properties: [
  43356. BABYLON.Action._GetTargetProperty(this._target),
  43357. BABYLON.Action._GetTargetProperty(this._parent),
  43358. ]
  43359. }, parent);
  43360. };
  43361. return SetParentAction;
  43362. }(BABYLON.Action));
  43363. BABYLON.SetParentAction = SetParentAction;
  43364. var PlaySoundAction = /** @class */ (function (_super) {
  43365. __extends(PlaySoundAction, _super);
  43366. function PlaySoundAction(triggerOptions, sound, condition) {
  43367. var _this = _super.call(this, triggerOptions, condition) || this;
  43368. _this._sound = sound;
  43369. return _this;
  43370. }
  43371. PlaySoundAction.prototype._prepare = function () {
  43372. };
  43373. PlaySoundAction.prototype.execute = function () {
  43374. if (this._sound !== undefined)
  43375. this._sound.play();
  43376. };
  43377. PlaySoundAction.prototype.serialize = function (parent) {
  43378. return _super.prototype._serialize.call(this, {
  43379. name: "PlaySoundAction",
  43380. properties: [{ name: "sound", value: this._sound.name }]
  43381. }, parent);
  43382. };
  43383. return PlaySoundAction;
  43384. }(BABYLON.Action));
  43385. BABYLON.PlaySoundAction = PlaySoundAction;
  43386. var StopSoundAction = /** @class */ (function (_super) {
  43387. __extends(StopSoundAction, _super);
  43388. function StopSoundAction(triggerOptions, sound, condition) {
  43389. var _this = _super.call(this, triggerOptions, condition) || this;
  43390. _this._sound = sound;
  43391. return _this;
  43392. }
  43393. StopSoundAction.prototype._prepare = function () {
  43394. };
  43395. StopSoundAction.prototype.execute = function () {
  43396. if (this._sound !== undefined)
  43397. this._sound.stop();
  43398. };
  43399. StopSoundAction.prototype.serialize = function (parent) {
  43400. return _super.prototype._serialize.call(this, {
  43401. name: "StopSoundAction",
  43402. properties: [{ name: "sound", value: this._sound.name }]
  43403. }, parent);
  43404. };
  43405. return StopSoundAction;
  43406. }(BABYLON.Action));
  43407. BABYLON.StopSoundAction = StopSoundAction;
  43408. })(BABYLON || (BABYLON = {}));
  43409. //# sourceMappingURL=babylon.directActions.js.map
  43410. var BABYLON;
  43411. (function (BABYLON) {
  43412. var SpriteManager = /** @class */ (function () {
  43413. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  43414. if (epsilon === void 0) { epsilon = 0.01; }
  43415. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43416. this.name = name;
  43417. this.sprites = new Array();
  43418. this.renderingGroupId = 0;
  43419. this.layerMask = 0x0FFFFFFF;
  43420. this.fogEnabled = true;
  43421. this.isPickable = false;
  43422. /**
  43423. * An event triggered when the manager is disposed.
  43424. * @type {BABYLON.Observable}
  43425. */
  43426. this.onDisposeObservable = new BABYLON.Observable();
  43427. this._vertexBuffers = {};
  43428. this._capacity = capacity;
  43429. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  43430. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43431. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43432. if (cellSize.width && cellSize.height) {
  43433. this.cellWidth = cellSize.width;
  43434. this.cellHeight = cellSize.height;
  43435. }
  43436. else if (cellSize !== undefined) {
  43437. this.cellWidth = cellSize;
  43438. this.cellHeight = cellSize;
  43439. }
  43440. else {
  43441. return;
  43442. }
  43443. this._epsilon = epsilon;
  43444. this._scene = scene;
  43445. this._scene.spriteManagers.push(this);
  43446. var indices = [];
  43447. var index = 0;
  43448. for (var count = 0; count < capacity; count++) {
  43449. indices.push(index);
  43450. indices.push(index + 1);
  43451. indices.push(index + 2);
  43452. indices.push(index);
  43453. indices.push(index + 2);
  43454. indices.push(index + 3);
  43455. index += 4;
  43456. }
  43457. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  43458. // VBO
  43459. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  43460. this._vertexData = new Float32Array(capacity * 16 * 4);
  43461. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  43462. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  43463. var options = this._buffer.createVertexBuffer("options", 4, 4);
  43464. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  43465. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  43466. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  43467. this._vertexBuffers["options"] = options;
  43468. this._vertexBuffers["cellInfo"] = cellInfo;
  43469. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  43470. // Effects
  43471. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  43472. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  43473. }
  43474. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  43475. set: function (callback) {
  43476. if (this._onDisposeObserver) {
  43477. this.onDisposeObservable.remove(this._onDisposeObserver);
  43478. }
  43479. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  43480. },
  43481. enumerable: true,
  43482. configurable: true
  43483. });
  43484. Object.defineProperty(SpriteManager.prototype, "texture", {
  43485. get: function () {
  43486. return this._spriteTexture;
  43487. },
  43488. set: function (value) {
  43489. this._spriteTexture = value;
  43490. },
  43491. enumerable: true,
  43492. configurable: true
  43493. });
  43494. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  43495. var arrayOffset = index * 16;
  43496. if (offsetX === 0)
  43497. offsetX = this._epsilon;
  43498. else if (offsetX === 1)
  43499. offsetX = 1 - this._epsilon;
  43500. if (offsetY === 0)
  43501. offsetY = this._epsilon;
  43502. else if (offsetY === 1)
  43503. offsetY = 1 - this._epsilon;
  43504. this._vertexData[arrayOffset] = sprite.position.x;
  43505. this._vertexData[arrayOffset + 1] = sprite.position.y;
  43506. this._vertexData[arrayOffset + 2] = sprite.position.z;
  43507. this._vertexData[arrayOffset + 3] = sprite.angle;
  43508. this._vertexData[arrayOffset + 4] = sprite.width;
  43509. this._vertexData[arrayOffset + 5] = sprite.height;
  43510. this._vertexData[arrayOffset + 6] = offsetX;
  43511. this._vertexData[arrayOffset + 7] = offsetY;
  43512. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  43513. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  43514. var offset = (sprite.cellIndex / rowSize) >> 0;
  43515. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  43516. this._vertexData[arrayOffset + 11] = offset;
  43517. // Color
  43518. this._vertexData[arrayOffset + 12] = sprite.color.r;
  43519. this._vertexData[arrayOffset + 13] = sprite.color.g;
  43520. this._vertexData[arrayOffset + 14] = sprite.color.b;
  43521. this._vertexData[arrayOffset + 15] = sprite.color.a;
  43522. };
  43523. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  43524. var count = Math.min(this._capacity, this.sprites.length);
  43525. var min = BABYLON.Vector3.Zero();
  43526. var max = BABYLON.Vector3.Zero();
  43527. var distance = Number.MAX_VALUE;
  43528. var currentSprite = null;
  43529. var cameraSpacePosition = BABYLON.Vector3.Zero();
  43530. var cameraView = camera.getViewMatrix();
  43531. for (var index = 0; index < count; index++) {
  43532. var sprite = this.sprites[index];
  43533. if (!sprite) {
  43534. continue;
  43535. }
  43536. if (predicate) {
  43537. if (!predicate(sprite)) {
  43538. continue;
  43539. }
  43540. }
  43541. else if (!sprite.isPickable) {
  43542. continue;
  43543. }
  43544. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  43545. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  43546. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  43547. if (ray.intersectsBoxMinMax(min, max)) {
  43548. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  43549. if (distance > currentDistance) {
  43550. distance = currentDistance;
  43551. currentSprite = sprite;
  43552. if (fastCheck) {
  43553. break;
  43554. }
  43555. }
  43556. }
  43557. }
  43558. if (currentSprite) {
  43559. var result = new BABYLON.PickingInfo();
  43560. result.hit = true;
  43561. result.pickedSprite = currentSprite;
  43562. result.distance = distance;
  43563. return result;
  43564. }
  43565. return null;
  43566. };
  43567. SpriteManager.prototype.render = function () {
  43568. // Check
  43569. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  43570. return;
  43571. var engine = this._scene.getEngine();
  43572. var baseSize = this._spriteTexture.getBaseSize();
  43573. // Sprites
  43574. var deltaTime = engine.getDeltaTime();
  43575. var max = Math.min(this._capacity, this.sprites.length);
  43576. var rowSize = baseSize.width / this.cellWidth;
  43577. var offset = 0;
  43578. for (var index = 0; index < max; index++) {
  43579. var sprite = this.sprites[index];
  43580. if (!sprite) {
  43581. continue;
  43582. }
  43583. sprite._animate(deltaTime);
  43584. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  43585. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  43586. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  43587. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  43588. }
  43589. this._buffer.update(this._vertexData);
  43590. // Render
  43591. var effect = this._effectBase;
  43592. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  43593. effect = this._effectFog;
  43594. }
  43595. engine.enableEffect(effect);
  43596. var viewMatrix = this._scene.getViewMatrix();
  43597. effect.setTexture("diffuseSampler", this._spriteTexture);
  43598. effect.setMatrix("view", viewMatrix);
  43599. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  43600. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  43601. // Fog
  43602. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  43603. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  43604. effect.setColor3("vFogColor", this._scene.fogColor);
  43605. }
  43606. // VBOs
  43607. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  43608. // Draw order
  43609. engine.setDepthFunctionToLessOrEqual();
  43610. effect.setBool("alphaTest", true);
  43611. engine.setColorWrite(false);
  43612. engine.draw(true, 0, max * 6);
  43613. engine.setColorWrite(true);
  43614. effect.setBool("alphaTest", false);
  43615. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  43616. engine.draw(true, 0, max * 6);
  43617. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  43618. };
  43619. SpriteManager.prototype.dispose = function () {
  43620. if (this._buffer) {
  43621. this._buffer.dispose();
  43622. this._buffer = null;
  43623. }
  43624. if (this._indexBuffer) {
  43625. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  43626. this._indexBuffer = null;
  43627. }
  43628. if (this._spriteTexture) {
  43629. this._spriteTexture.dispose();
  43630. this._spriteTexture = null;
  43631. }
  43632. // Remove from scene
  43633. var index = this._scene.spriteManagers.indexOf(this);
  43634. this._scene.spriteManagers.splice(index, 1);
  43635. // Callback
  43636. this.onDisposeObservable.notifyObservers(this);
  43637. this.onDisposeObservable.clear();
  43638. };
  43639. return SpriteManager;
  43640. }());
  43641. BABYLON.SpriteManager = SpriteManager;
  43642. })(BABYLON || (BABYLON = {}));
  43643. //# sourceMappingURL=babylon.spriteManager.js.map
  43644. var BABYLON;
  43645. (function (BABYLON) {
  43646. var Sprite = /** @class */ (function () {
  43647. function Sprite(name, manager) {
  43648. this.name = name;
  43649. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  43650. this.width = 1.0;
  43651. this.height = 1.0;
  43652. this.angle = 0;
  43653. this.cellIndex = 0;
  43654. this.invertU = 0;
  43655. this.invertV = 0;
  43656. this.animations = new Array();
  43657. this.isPickable = false;
  43658. this._animationStarted = false;
  43659. this._loopAnimation = false;
  43660. this._fromIndex = 0;
  43661. this._toIndex = 0;
  43662. this._delay = 0;
  43663. this._direction = 1;
  43664. this._time = 0;
  43665. this._manager = manager;
  43666. this._manager.sprites.push(this);
  43667. this.position = BABYLON.Vector3.Zero();
  43668. }
  43669. Object.defineProperty(Sprite.prototype, "size", {
  43670. get: function () {
  43671. return this.width;
  43672. },
  43673. set: function (value) {
  43674. this.width = value;
  43675. this.height = value;
  43676. },
  43677. enumerable: true,
  43678. configurable: true
  43679. });
  43680. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  43681. this._fromIndex = from;
  43682. this._toIndex = to;
  43683. this._loopAnimation = loop;
  43684. this._delay = delay;
  43685. this._animationStarted = true;
  43686. this._direction = from < to ? 1 : -1;
  43687. this.cellIndex = from;
  43688. this._time = 0;
  43689. this._onAnimationEnd = onAnimationEnd;
  43690. };
  43691. Sprite.prototype.stopAnimation = function () {
  43692. this._animationStarted = false;
  43693. };
  43694. Sprite.prototype._animate = function (deltaTime) {
  43695. if (!this._animationStarted)
  43696. return;
  43697. this._time += deltaTime;
  43698. if (this._time > this._delay) {
  43699. this._time = this._time % this._delay;
  43700. this.cellIndex += this._direction;
  43701. if (this.cellIndex > this._toIndex) {
  43702. if (this._loopAnimation) {
  43703. this.cellIndex = this._fromIndex;
  43704. }
  43705. else {
  43706. this.cellIndex = this._toIndex;
  43707. this._animationStarted = false;
  43708. if (this._onAnimationEnd) {
  43709. this._onAnimationEnd();
  43710. }
  43711. if (this.disposeWhenFinishedAnimating) {
  43712. this.dispose();
  43713. }
  43714. }
  43715. }
  43716. }
  43717. };
  43718. Sprite.prototype.dispose = function () {
  43719. for (var i = 0; i < this._manager.sprites.length; i++) {
  43720. if (this._manager.sprites[i] == this) {
  43721. this._manager.sprites.splice(i, 1);
  43722. }
  43723. }
  43724. };
  43725. return Sprite;
  43726. }());
  43727. BABYLON.Sprite = Sprite;
  43728. })(BABYLON || (BABYLON = {}));
  43729. //# sourceMappingURL=babylon.sprite.js.map
  43730. var BABYLON;
  43731. (function (BABYLON) {
  43732. var IntersectionInfo = /** @class */ (function () {
  43733. function IntersectionInfo(bu, bv, distance) {
  43734. this.bu = bu;
  43735. this.bv = bv;
  43736. this.distance = distance;
  43737. this.faceId = 0;
  43738. this.subMeshId = 0;
  43739. }
  43740. return IntersectionInfo;
  43741. }());
  43742. BABYLON.IntersectionInfo = IntersectionInfo;
  43743. var PickingInfo = /** @class */ (function () {
  43744. function PickingInfo() {
  43745. this.hit = false;
  43746. this.distance = 0;
  43747. this.pickedPoint = null;
  43748. this.pickedMesh = null;
  43749. this.bu = 0;
  43750. this.bv = 0;
  43751. this.faceId = -1;
  43752. this.subMeshId = 0;
  43753. this.pickedSprite = null;
  43754. }
  43755. // Methods
  43756. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  43757. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  43758. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  43759. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43760. return null;
  43761. }
  43762. var indices = this.pickedMesh.getIndices();
  43763. if (!indices) {
  43764. return null;
  43765. }
  43766. var result;
  43767. if (useVerticesNormals) {
  43768. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  43769. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  43770. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  43771. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  43772. normal0 = normal0.scale(this.bu);
  43773. normal1 = normal1.scale(this.bv);
  43774. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  43775. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  43776. }
  43777. else {
  43778. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  43779. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  43780. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  43781. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  43782. var p1p2 = vertex1.subtract(vertex2);
  43783. var p3p2 = vertex3.subtract(vertex2);
  43784. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  43785. }
  43786. if (useWorldCoordinates) {
  43787. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  43788. }
  43789. return BABYLON.Vector3.Normalize(result);
  43790. };
  43791. PickingInfo.prototype.getTextureCoordinates = function () {
  43792. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  43793. return null;
  43794. }
  43795. var indices = this.pickedMesh.getIndices();
  43796. if (!indices) {
  43797. return null;
  43798. }
  43799. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  43800. if (!uvs) {
  43801. return null;
  43802. }
  43803. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  43804. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  43805. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  43806. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  43807. uv1 = uv1.scale(this.bu);
  43808. uv2 = uv2.scale(this.bv);
  43809. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  43810. };
  43811. return PickingInfo;
  43812. }());
  43813. BABYLON.PickingInfo = PickingInfo;
  43814. })(BABYLON || (BABYLON = {}));
  43815. //# sourceMappingURL=babylon.pickingInfo.js.map
  43816. var BABYLON;
  43817. (function (BABYLON) {
  43818. var Ray = /** @class */ (function () {
  43819. function Ray(origin, direction, length) {
  43820. if (length === void 0) { length = Number.MAX_VALUE; }
  43821. this.origin = origin;
  43822. this.direction = direction;
  43823. this.length = length;
  43824. }
  43825. // Methods
  43826. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  43827. var d = 0.0;
  43828. var maxValue = Number.MAX_VALUE;
  43829. var inv;
  43830. var min;
  43831. var max;
  43832. var temp;
  43833. if (Math.abs(this.direction.x) < 0.0000001) {
  43834. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  43835. return false;
  43836. }
  43837. }
  43838. else {
  43839. inv = 1.0 / this.direction.x;
  43840. min = (minimum.x - this.origin.x) * inv;
  43841. max = (maximum.x - this.origin.x) * inv;
  43842. if (max === -Infinity) {
  43843. max = Infinity;
  43844. }
  43845. if (min > max) {
  43846. temp = min;
  43847. min = max;
  43848. max = temp;
  43849. }
  43850. d = Math.max(min, d);
  43851. maxValue = Math.min(max, maxValue);
  43852. if (d > maxValue) {
  43853. return false;
  43854. }
  43855. }
  43856. if (Math.abs(this.direction.y) < 0.0000001) {
  43857. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  43858. return false;
  43859. }
  43860. }
  43861. else {
  43862. inv = 1.0 / this.direction.y;
  43863. min = (minimum.y - this.origin.y) * inv;
  43864. max = (maximum.y - this.origin.y) * inv;
  43865. if (max === -Infinity) {
  43866. max = Infinity;
  43867. }
  43868. if (min > max) {
  43869. temp = min;
  43870. min = max;
  43871. max = temp;
  43872. }
  43873. d = Math.max(min, d);
  43874. maxValue = Math.min(max, maxValue);
  43875. if (d > maxValue) {
  43876. return false;
  43877. }
  43878. }
  43879. if (Math.abs(this.direction.z) < 0.0000001) {
  43880. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  43881. return false;
  43882. }
  43883. }
  43884. else {
  43885. inv = 1.0 / this.direction.z;
  43886. min = (minimum.z - this.origin.z) * inv;
  43887. max = (maximum.z - this.origin.z) * inv;
  43888. if (max === -Infinity) {
  43889. max = Infinity;
  43890. }
  43891. if (min > max) {
  43892. temp = min;
  43893. min = max;
  43894. max = temp;
  43895. }
  43896. d = Math.max(min, d);
  43897. maxValue = Math.min(max, maxValue);
  43898. if (d > maxValue) {
  43899. return false;
  43900. }
  43901. }
  43902. return true;
  43903. };
  43904. Ray.prototype.intersectsBox = function (box) {
  43905. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  43906. };
  43907. Ray.prototype.intersectsSphere = function (sphere) {
  43908. var x = sphere.center.x - this.origin.x;
  43909. var y = sphere.center.y - this.origin.y;
  43910. var z = sphere.center.z - this.origin.z;
  43911. var pyth = (x * x) + (y * y) + (z * z);
  43912. var rr = sphere.radius * sphere.radius;
  43913. if (pyth <= rr) {
  43914. return true;
  43915. }
  43916. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  43917. if (dot < 0.0) {
  43918. return false;
  43919. }
  43920. var temp = pyth - (dot * dot);
  43921. return temp <= rr;
  43922. };
  43923. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  43924. if (!this._edge1) {
  43925. this._edge1 = BABYLON.Vector3.Zero();
  43926. this._edge2 = BABYLON.Vector3.Zero();
  43927. this._pvec = BABYLON.Vector3.Zero();
  43928. this._tvec = BABYLON.Vector3.Zero();
  43929. this._qvec = BABYLON.Vector3.Zero();
  43930. }
  43931. vertex1.subtractToRef(vertex0, this._edge1);
  43932. vertex2.subtractToRef(vertex0, this._edge2);
  43933. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  43934. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  43935. if (det === 0) {
  43936. return null;
  43937. }
  43938. var invdet = 1 / det;
  43939. this.origin.subtractToRef(vertex0, this._tvec);
  43940. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  43941. if (bu < 0 || bu > 1.0) {
  43942. return null;
  43943. }
  43944. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  43945. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  43946. if (bv < 0 || bu + bv > 1.0) {
  43947. return null;
  43948. }
  43949. //check if the distance is longer than the predefined length.
  43950. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  43951. if (distance > this.length) {
  43952. return null;
  43953. }
  43954. return new BABYLON.IntersectionInfo(bu, bv, distance);
  43955. };
  43956. Ray.prototype.intersectsPlane = function (plane) {
  43957. var distance;
  43958. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  43959. if (Math.abs(result1) < 9.99999997475243E-07) {
  43960. return null;
  43961. }
  43962. else {
  43963. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  43964. distance = (-plane.d - result2) / result1;
  43965. if (distance < 0.0) {
  43966. if (distance < -9.99999997475243E-07) {
  43967. return null;
  43968. }
  43969. else {
  43970. return 0;
  43971. }
  43972. }
  43973. return distance;
  43974. }
  43975. };
  43976. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  43977. var tm = BABYLON.Tmp.Matrix[0];
  43978. mesh.getWorldMatrix().invertToRef(tm);
  43979. if (this._tmpRay) {
  43980. Ray.TransformToRef(this, tm, this._tmpRay);
  43981. }
  43982. else {
  43983. this._tmpRay = Ray.Transform(this, tm);
  43984. }
  43985. return mesh.intersects(this._tmpRay, fastCheck);
  43986. };
  43987. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  43988. if (results) {
  43989. results.length = 0;
  43990. }
  43991. else {
  43992. results = [];
  43993. }
  43994. for (var i = 0; i < meshes.length; i++) {
  43995. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  43996. if (pickInfo.hit) {
  43997. results.push(pickInfo);
  43998. }
  43999. }
  44000. results.sort(this._comparePickingInfo);
  44001. return results;
  44002. };
  44003. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  44004. if (pickingInfoA.distance < pickingInfoB.distance) {
  44005. return -1;
  44006. }
  44007. else if (pickingInfoA.distance > pickingInfoB.distance) {
  44008. return 1;
  44009. }
  44010. else {
  44011. return 0;
  44012. }
  44013. };
  44014. /**
  44015. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  44016. * @param sega the first point of the segment to test the intersection against
  44017. * @param segb the second point of the segment to test the intersection against
  44018. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  44019. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  44020. */
  44021. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  44022. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  44023. var u = segb.subtract(sega);
  44024. var v = rsegb.subtract(this.origin);
  44025. var w = sega.subtract(this.origin);
  44026. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  44027. var b = BABYLON.Vector3.Dot(u, v);
  44028. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  44029. var d = BABYLON.Vector3.Dot(u, w);
  44030. var e = BABYLON.Vector3.Dot(v, w);
  44031. var D = a * c - b * b; // always >= 0
  44032. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  44033. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  44034. // compute the line parameters of the two closest points
  44035. if (D < Ray.smallnum) {
  44036. sN = 0.0; // force using point P0 on segment S1
  44037. sD = 1.0; // to prevent possible division by 0.0 later
  44038. tN = e;
  44039. tD = c;
  44040. }
  44041. else {
  44042. sN = (b * e - c * d);
  44043. tN = (a * e - b * d);
  44044. if (sN < 0.0) {
  44045. sN = 0.0;
  44046. tN = e;
  44047. tD = c;
  44048. }
  44049. else if (sN > sD) {
  44050. sN = sD;
  44051. tN = e + b;
  44052. tD = c;
  44053. }
  44054. }
  44055. if (tN < 0.0) {
  44056. tN = 0.0;
  44057. // recompute sc for this edge
  44058. if (-d < 0.0) {
  44059. sN = 0.0;
  44060. }
  44061. else if (-d > a)
  44062. sN = sD;
  44063. else {
  44064. sN = -d;
  44065. sD = a;
  44066. }
  44067. }
  44068. else if (tN > tD) {
  44069. tN = tD;
  44070. // recompute sc for this edge
  44071. if ((-d + b) < 0.0) {
  44072. sN = 0;
  44073. }
  44074. else if ((-d + b) > a) {
  44075. sN = sD;
  44076. }
  44077. else {
  44078. sN = (-d + b);
  44079. sD = a;
  44080. }
  44081. }
  44082. // finally do the division to get sc and tc
  44083. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  44084. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  44085. // get the difference of the two closest points
  44086. var qtc = v.multiplyByFloats(tc, tc, tc);
  44087. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  44088. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  44089. if (isIntersected) {
  44090. return qtc.length();
  44091. }
  44092. return -1;
  44093. };
  44094. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  44095. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  44096. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  44097. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  44098. this.direction.normalize();
  44099. return this;
  44100. };
  44101. // Statics
  44102. Ray.Zero = function () {
  44103. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  44104. };
  44105. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  44106. var result = Ray.Zero();
  44107. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  44108. };
  44109. /**
  44110. * 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
  44111. * transformed to the given world matrix.
  44112. * @param origin The origin point
  44113. * @param end The end point
  44114. * @param world a matrix to transform the ray to. Default is the identity matrix.
  44115. */
  44116. Ray.CreateNewFromTo = function (origin, end, world) {
  44117. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  44118. var direction = end.subtract(origin);
  44119. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  44120. direction.normalize();
  44121. return Ray.Transform(new Ray(origin, direction, length), world);
  44122. };
  44123. Ray.Transform = function (ray, matrix) {
  44124. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  44125. Ray.TransformToRef(ray, matrix, result);
  44126. return result;
  44127. };
  44128. Ray.TransformToRef = function (ray, matrix, result) {
  44129. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  44130. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  44131. result.length = ray.length;
  44132. var dir = result.direction;
  44133. var len = dir.length();
  44134. if (!(len === 0 || len === 1)) {
  44135. var num = 1.0 / len;
  44136. dir.x *= num;
  44137. dir.y *= num;
  44138. dir.z *= num;
  44139. result.length *= len;
  44140. }
  44141. };
  44142. Ray.smallnum = 0.00000001;
  44143. Ray.rayl = 10e8;
  44144. return Ray;
  44145. }());
  44146. BABYLON.Ray = Ray;
  44147. })(BABYLON || (BABYLON = {}));
  44148. //# sourceMappingURL=babylon.ray.js.map
  44149. var BABYLON;
  44150. (function (BABYLON) {
  44151. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  44152. if (boxMin.x > sphereCenter.x + sphereRadius)
  44153. return false;
  44154. if (sphereCenter.x - sphereRadius > boxMax.x)
  44155. return false;
  44156. if (boxMin.y > sphereCenter.y + sphereRadius)
  44157. return false;
  44158. if (sphereCenter.y - sphereRadius > boxMax.y)
  44159. return false;
  44160. if (boxMin.z > sphereCenter.z + sphereRadius)
  44161. return false;
  44162. if (sphereCenter.z - sphereRadius > boxMax.z)
  44163. return false;
  44164. return true;
  44165. };
  44166. var getLowestRoot = (function () {
  44167. var result = { root: 0, found: false };
  44168. return function (a, b, c, maxR) {
  44169. result.root = 0;
  44170. result.found = false;
  44171. var determinant = b * b - 4.0 * a * c;
  44172. if (determinant < 0)
  44173. return result;
  44174. var sqrtD = Math.sqrt(determinant);
  44175. var r1 = (-b - sqrtD) / (2.0 * a);
  44176. var r2 = (-b + sqrtD) / (2.0 * a);
  44177. if (r1 > r2) {
  44178. var temp = r2;
  44179. r2 = r1;
  44180. r1 = temp;
  44181. }
  44182. if (r1 > 0 && r1 < maxR) {
  44183. result.root = r1;
  44184. result.found = true;
  44185. return result;
  44186. }
  44187. if (r2 > 0 && r2 < maxR) {
  44188. result.root = r2;
  44189. result.found = true;
  44190. return result;
  44191. }
  44192. return result;
  44193. };
  44194. })();
  44195. var Collider = /** @class */ (function () {
  44196. function Collider() {
  44197. this.radius = BABYLON.Vector3.One();
  44198. this.retry = 0;
  44199. this.basePointWorld = BABYLON.Vector3.Zero();
  44200. this.velocityWorld = BABYLON.Vector3.Zero();
  44201. this.normalizedVelocity = BABYLON.Vector3.Zero();
  44202. this._collisionPoint = BABYLON.Vector3.Zero();
  44203. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  44204. this._tempVector = BABYLON.Vector3.Zero();
  44205. this._tempVector2 = BABYLON.Vector3.Zero();
  44206. this._tempVector3 = BABYLON.Vector3.Zero();
  44207. this._tempVector4 = BABYLON.Vector3.Zero();
  44208. this._edge = BABYLON.Vector3.Zero();
  44209. this._baseToVertex = BABYLON.Vector3.Zero();
  44210. this._destinationPoint = BABYLON.Vector3.Zero();
  44211. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  44212. this._displacementVector = BABYLON.Vector3.Zero();
  44213. this._collisionMask = -1;
  44214. }
  44215. Object.defineProperty(Collider.prototype, "collisionMask", {
  44216. get: function () {
  44217. return this._collisionMask;
  44218. },
  44219. set: function (mask) {
  44220. this._collisionMask = !isNaN(mask) ? mask : -1;
  44221. },
  44222. enumerable: true,
  44223. configurable: true
  44224. });
  44225. // Methods
  44226. Collider.prototype._initialize = function (source, dir, e) {
  44227. this.velocity = dir;
  44228. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  44229. this.basePoint = source;
  44230. source.multiplyToRef(this.radius, this.basePointWorld);
  44231. dir.multiplyToRef(this.radius, this.velocityWorld);
  44232. this.velocityWorldLength = this.velocityWorld.length();
  44233. this.epsilon = e;
  44234. this.collisionFound = false;
  44235. };
  44236. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  44237. pa.subtractToRef(point, this._tempVector);
  44238. pb.subtractToRef(point, this._tempVector2);
  44239. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  44240. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  44241. if (d < 0)
  44242. return false;
  44243. pc.subtractToRef(point, this._tempVector3);
  44244. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  44245. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  44246. if (d < 0)
  44247. return false;
  44248. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  44249. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  44250. return d >= 0;
  44251. };
  44252. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  44253. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  44254. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  44255. if (distance > this.velocityWorldLength + max + sphereRadius) {
  44256. return false;
  44257. }
  44258. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  44259. return false;
  44260. return true;
  44261. };
  44262. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  44263. var t0;
  44264. var embeddedInPlane = false;
  44265. //defensive programming, actually not needed.
  44266. if (!trianglePlaneArray) {
  44267. trianglePlaneArray = [];
  44268. }
  44269. if (!trianglePlaneArray[faceIndex]) {
  44270. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  44271. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  44272. }
  44273. var trianglePlane = trianglePlaneArray[faceIndex];
  44274. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  44275. return;
  44276. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  44277. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  44278. if (normalDotVelocity == 0) {
  44279. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  44280. return;
  44281. embeddedInPlane = true;
  44282. t0 = 0;
  44283. }
  44284. else {
  44285. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  44286. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  44287. if (t0 > t1) {
  44288. var temp = t1;
  44289. t1 = t0;
  44290. t0 = temp;
  44291. }
  44292. if (t0 > 1.0 || t1 < 0.0)
  44293. return;
  44294. if (t0 < 0)
  44295. t0 = 0;
  44296. if (t0 > 1.0)
  44297. t0 = 1.0;
  44298. }
  44299. this._collisionPoint.copyFromFloats(0, 0, 0);
  44300. var found = false;
  44301. var t = 1.0;
  44302. if (!embeddedInPlane) {
  44303. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  44304. this.velocity.scaleToRef(t0, this._tempVector);
  44305. this._planeIntersectionPoint.addInPlace(this._tempVector);
  44306. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  44307. found = true;
  44308. t = t0;
  44309. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  44310. }
  44311. }
  44312. if (!found) {
  44313. var velocitySquaredLength = this.velocity.lengthSquared();
  44314. var a = velocitySquaredLength;
  44315. this.basePoint.subtractToRef(p1, this._tempVector);
  44316. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  44317. var c = this._tempVector.lengthSquared() - 1.0;
  44318. var lowestRoot = getLowestRoot(a, b, c, t);
  44319. if (lowestRoot.found) {
  44320. t = lowestRoot.root;
  44321. found = true;
  44322. this._collisionPoint.copyFrom(p1);
  44323. }
  44324. this.basePoint.subtractToRef(p2, this._tempVector);
  44325. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  44326. c = this._tempVector.lengthSquared() - 1.0;
  44327. lowestRoot = getLowestRoot(a, b, c, t);
  44328. if (lowestRoot.found) {
  44329. t = lowestRoot.root;
  44330. found = true;
  44331. this._collisionPoint.copyFrom(p2);
  44332. }
  44333. this.basePoint.subtractToRef(p3, this._tempVector);
  44334. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  44335. c = this._tempVector.lengthSquared() - 1.0;
  44336. lowestRoot = getLowestRoot(a, b, c, t);
  44337. if (lowestRoot.found) {
  44338. t = lowestRoot.root;
  44339. found = true;
  44340. this._collisionPoint.copyFrom(p3);
  44341. }
  44342. p2.subtractToRef(p1, this._edge);
  44343. p1.subtractToRef(this.basePoint, this._baseToVertex);
  44344. var edgeSquaredLength = this._edge.lengthSquared();
  44345. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  44346. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  44347. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  44348. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  44349. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  44350. lowestRoot = getLowestRoot(a, b, c, t);
  44351. if (lowestRoot.found) {
  44352. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  44353. if (f >= 0.0 && f <= 1.0) {
  44354. t = lowestRoot.root;
  44355. found = true;
  44356. this._edge.scaleInPlace(f);
  44357. p1.addToRef(this._edge, this._collisionPoint);
  44358. }
  44359. }
  44360. p3.subtractToRef(p2, this._edge);
  44361. p2.subtractToRef(this.basePoint, this._baseToVertex);
  44362. edgeSquaredLength = this._edge.lengthSquared();
  44363. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  44364. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  44365. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  44366. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  44367. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  44368. lowestRoot = getLowestRoot(a, b, c, t);
  44369. if (lowestRoot.found) {
  44370. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  44371. if (f >= 0.0 && f <= 1.0) {
  44372. t = lowestRoot.root;
  44373. found = true;
  44374. this._edge.scaleInPlace(f);
  44375. p2.addToRef(this._edge, this._collisionPoint);
  44376. }
  44377. }
  44378. p1.subtractToRef(p3, this._edge);
  44379. p3.subtractToRef(this.basePoint, this._baseToVertex);
  44380. edgeSquaredLength = this._edge.lengthSquared();
  44381. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  44382. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  44383. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  44384. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  44385. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  44386. lowestRoot = getLowestRoot(a, b, c, t);
  44387. if (lowestRoot.found) {
  44388. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  44389. if (f >= 0.0 && f <= 1.0) {
  44390. t = lowestRoot.root;
  44391. found = true;
  44392. this._edge.scaleInPlace(f);
  44393. p3.addToRef(this._edge, this._collisionPoint);
  44394. }
  44395. }
  44396. }
  44397. if (found) {
  44398. var distToCollision = t * this.velocity.length();
  44399. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  44400. if (!this.intersectionPoint) {
  44401. this.intersectionPoint = this._collisionPoint.clone();
  44402. }
  44403. else {
  44404. this.intersectionPoint.copyFrom(this._collisionPoint);
  44405. }
  44406. this.nearestDistance = distToCollision;
  44407. this.collisionFound = true;
  44408. }
  44409. }
  44410. };
  44411. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  44412. for (var i = indexStart; i < indexEnd; i += 3) {
  44413. var p1 = pts[indices[i] - decal];
  44414. var p2 = pts[indices[i + 1] - decal];
  44415. var p3 = pts[indices[i + 2] - decal];
  44416. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  44417. }
  44418. };
  44419. Collider.prototype._getResponse = function (pos, vel) {
  44420. pos.addToRef(vel, this._destinationPoint);
  44421. vel.scaleInPlace((this.nearestDistance / vel.length()));
  44422. this.basePoint.addToRef(vel, pos);
  44423. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  44424. this._slidePlaneNormal.normalize();
  44425. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  44426. pos.addInPlace(this._displacementVector);
  44427. this.intersectionPoint.addInPlace(this._displacementVector);
  44428. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  44429. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  44430. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  44431. };
  44432. return Collider;
  44433. }());
  44434. BABYLON.Collider = Collider;
  44435. })(BABYLON || (BABYLON = {}));
  44436. //# sourceMappingURL=babylon.collider.js.map
  44437. var BABYLON;
  44438. (function (BABYLON) {
  44439. //WebWorker code will be inserted to this variable.
  44440. BABYLON.CollisionWorker = "";
  44441. var WorkerTaskType;
  44442. (function (WorkerTaskType) {
  44443. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  44444. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  44445. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  44446. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  44447. var WorkerReplyType;
  44448. (function (WorkerReplyType) {
  44449. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  44450. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  44451. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  44452. var CollisionCoordinatorWorker = /** @class */ (function () {
  44453. function CollisionCoordinatorWorker() {
  44454. var _this = this;
  44455. this._scaledPosition = BABYLON.Vector3.Zero();
  44456. this._scaledVelocity = BABYLON.Vector3.Zero();
  44457. this.onMeshUpdated = function (transformNode) {
  44458. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  44459. };
  44460. this.onGeometryUpdated = function (geometry) {
  44461. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  44462. };
  44463. this._afterRender = function () {
  44464. if (!_this._init)
  44465. return;
  44466. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  44467. return;
  44468. }
  44469. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  44470. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  44471. if (_this._runningUpdated > 4) {
  44472. return;
  44473. }
  44474. ++_this._runningUpdated;
  44475. var payload = {
  44476. updatedMeshes: _this._addUpdateMeshesList,
  44477. updatedGeometries: _this._addUpdateGeometriesList,
  44478. removedGeometries: _this._toRemoveGeometryArray,
  44479. removedMeshes: _this._toRemoveMeshesArray
  44480. };
  44481. var message = {
  44482. payload: payload,
  44483. taskType: WorkerTaskType.UPDATE
  44484. };
  44485. var serializable = [];
  44486. for (var id in payload.updatedGeometries) {
  44487. if (payload.updatedGeometries.hasOwnProperty(id)) {
  44488. //prepare transferables
  44489. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  44490. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  44491. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  44492. }
  44493. }
  44494. _this._worker.postMessage(message, serializable);
  44495. _this._addUpdateMeshesList = {};
  44496. _this._addUpdateGeometriesList = {};
  44497. _this._toRemoveGeometryArray = [];
  44498. _this._toRemoveMeshesArray = [];
  44499. };
  44500. this._onMessageFromWorker = function (e) {
  44501. var returnData = e.data;
  44502. if (returnData.error != WorkerReplyType.SUCCESS) {
  44503. //TODO what errors can be returned from the worker?
  44504. BABYLON.Tools.Warn("error returned from worker!");
  44505. return;
  44506. }
  44507. switch (returnData.taskType) {
  44508. case WorkerTaskType.INIT:
  44509. _this._init = true;
  44510. //Update the worked with ALL of the scene's current state
  44511. _this._scene.meshes.forEach(function (mesh) {
  44512. _this.onMeshAdded(mesh);
  44513. });
  44514. _this._scene.getGeometries().forEach(function (geometry) {
  44515. _this.onGeometryAdded(geometry);
  44516. });
  44517. break;
  44518. case WorkerTaskType.UPDATE:
  44519. _this._runningUpdated--;
  44520. break;
  44521. case WorkerTaskType.COLLIDE:
  44522. var returnPayload = returnData.payload;
  44523. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  44524. return;
  44525. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  44526. if (callback) {
  44527. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  44528. if (mesh) {
  44529. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  44530. }
  44531. }
  44532. //cleanup
  44533. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  44534. break;
  44535. }
  44536. };
  44537. this._collisionsCallbackArray = [];
  44538. this._init = false;
  44539. this._runningUpdated = 0;
  44540. this._addUpdateMeshesList = {};
  44541. this._addUpdateGeometriesList = {};
  44542. this._toRemoveGeometryArray = [];
  44543. this._toRemoveMeshesArray = [];
  44544. }
  44545. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  44546. if (!this._init)
  44547. return;
  44548. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  44549. return;
  44550. position.divideToRef(collider.radius, this._scaledPosition);
  44551. displacement.divideToRef(collider.radius, this._scaledVelocity);
  44552. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  44553. var payload = {
  44554. collider: {
  44555. position: this._scaledPosition.asArray(),
  44556. velocity: this._scaledVelocity.asArray(),
  44557. radius: collider.radius.asArray()
  44558. },
  44559. collisionId: collisionIndex,
  44560. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  44561. maximumRetry: maximumRetry
  44562. };
  44563. var message = {
  44564. payload: payload,
  44565. taskType: WorkerTaskType.COLLIDE
  44566. };
  44567. this._worker.postMessage(message);
  44568. };
  44569. CollisionCoordinatorWorker.prototype.init = function (scene) {
  44570. this._scene = scene;
  44571. this._scene.registerAfterRender(this._afterRender);
  44572. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  44573. this._worker = new Worker(workerUrl);
  44574. this._worker.onmessage = this._onMessageFromWorker;
  44575. var message = {
  44576. payload: {},
  44577. taskType: WorkerTaskType.INIT
  44578. };
  44579. this._worker.postMessage(message);
  44580. };
  44581. CollisionCoordinatorWorker.prototype.destroy = function () {
  44582. this._scene.unregisterAfterRender(this._afterRender);
  44583. this._worker.terminate();
  44584. };
  44585. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  44586. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  44587. this.onMeshUpdated(mesh);
  44588. };
  44589. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  44590. this._toRemoveMeshesArray.push(mesh.uniqueId);
  44591. };
  44592. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  44593. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  44594. geometry.onGeometryUpdated = this.onGeometryUpdated;
  44595. this.onGeometryUpdated(geometry);
  44596. };
  44597. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  44598. this._toRemoveGeometryArray.push(geometry.id);
  44599. };
  44600. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  44601. var submeshes = [];
  44602. if (mesh.subMeshes) {
  44603. submeshes = mesh.subMeshes.map(function (sm, idx) {
  44604. var boundingInfo = sm.getBoundingInfo();
  44605. return {
  44606. position: idx,
  44607. verticesStart: sm.verticesStart,
  44608. verticesCount: sm.verticesCount,
  44609. indexStart: sm.indexStart,
  44610. indexCount: sm.indexCount,
  44611. hasMaterial: !!sm.getMaterial(),
  44612. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  44613. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  44614. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  44615. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  44616. };
  44617. });
  44618. }
  44619. var geometryId = null;
  44620. if (mesh instanceof BABYLON.Mesh) {
  44621. var geometry = mesh.geometry;
  44622. geometryId = geometry ? geometry.id : null;
  44623. }
  44624. else if (mesh instanceof BABYLON.InstancedMesh) {
  44625. var geometry = mesh.sourceMesh.geometry;
  44626. geometryId = geometry ? geometry.id : null;
  44627. }
  44628. var boundingInfo = mesh.getBoundingInfo();
  44629. return {
  44630. uniqueId: mesh.uniqueId,
  44631. id: mesh.id,
  44632. name: mesh.name,
  44633. geometryId: geometryId,
  44634. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  44635. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  44636. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  44637. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  44638. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  44639. subMeshes: submeshes,
  44640. checkCollisions: mesh.checkCollisions
  44641. };
  44642. };
  44643. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  44644. return {
  44645. id: geometry.id,
  44646. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  44647. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  44648. indices: new Uint32Array(geometry.getIndices() || []),
  44649. };
  44650. };
  44651. return CollisionCoordinatorWorker;
  44652. }());
  44653. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  44654. var CollisionCoordinatorLegacy = /** @class */ (function () {
  44655. function CollisionCoordinatorLegacy() {
  44656. this._scaledPosition = BABYLON.Vector3.Zero();
  44657. this._scaledVelocity = BABYLON.Vector3.Zero();
  44658. this._finalPosition = BABYLON.Vector3.Zero();
  44659. }
  44660. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  44661. position.divideToRef(collider.radius, this._scaledPosition);
  44662. displacement.divideToRef(collider.radius, this._scaledVelocity);
  44663. collider.collidedMesh = null;
  44664. collider.retry = 0;
  44665. collider.initialVelocity = this._scaledVelocity;
  44666. collider.initialPosition = this._scaledPosition;
  44667. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  44668. this._finalPosition.multiplyInPlace(collider.radius);
  44669. //run the callback
  44670. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  44671. };
  44672. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  44673. this._scene = scene;
  44674. };
  44675. CollisionCoordinatorLegacy.prototype.destroy = function () {
  44676. //Legacy need no destruction method.
  44677. };
  44678. //No update in legacy mode
  44679. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  44680. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  44681. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  44682. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  44683. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  44684. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  44685. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  44686. if (excludedMesh === void 0) { excludedMesh = null; }
  44687. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  44688. if (collider.retry >= maximumRetry) {
  44689. finalPosition.copyFrom(position);
  44690. return;
  44691. }
  44692. // Check if this is a mesh else camera or -1
  44693. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  44694. collider._initialize(position, velocity, closeDistance);
  44695. // Check all meshes
  44696. for (var index = 0; index < this._scene.meshes.length; index++) {
  44697. var mesh = this._scene.meshes[index];
  44698. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  44699. mesh._checkCollision(collider);
  44700. }
  44701. }
  44702. if (!collider.collisionFound) {
  44703. position.addToRef(velocity, finalPosition);
  44704. return;
  44705. }
  44706. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  44707. collider._getResponse(position, velocity);
  44708. }
  44709. if (velocity.length() <= closeDistance) {
  44710. finalPosition.copyFrom(position);
  44711. return;
  44712. }
  44713. collider.retry++;
  44714. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  44715. };
  44716. return CollisionCoordinatorLegacy;
  44717. }());
  44718. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  44719. })(BABYLON || (BABYLON = {}));
  44720. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  44721. var BABYLON;
  44722. (function (BABYLON) {
  44723. var Particle = /** @class */ (function () {
  44724. function Particle(particleSystem) {
  44725. this.particleSystem = particleSystem;
  44726. this.position = BABYLON.Vector3.Zero();
  44727. this.direction = BABYLON.Vector3.Zero();
  44728. this.color = new BABYLON.Color4(0, 0, 0, 0);
  44729. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  44730. this.lifeTime = 1.0;
  44731. this.age = 0;
  44732. this.size = 0;
  44733. this.angle = 0;
  44734. this.angularSpeed = 0;
  44735. this._currentFrameCounter = 0;
  44736. this.cellIndex = 0;
  44737. if (!this.particleSystem.isAnimationSheetEnabled) {
  44738. return;
  44739. }
  44740. this.cellIndex = this.particleSystem.startSpriteCellID;
  44741. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  44742. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  44743. }
  44744. else {
  44745. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  44746. }
  44747. }
  44748. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  44749. // (ageOffset / scaledUpdateSpeed) / available cells
  44750. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  44751. this._currentFrameCounter += scaledUpdateSpeed;
  44752. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  44753. this._currentFrameCounter = 0;
  44754. this.cellIndex++;
  44755. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  44756. this.cellIndex = this.particleSystem.endSpriteCellID;
  44757. }
  44758. }
  44759. };
  44760. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  44761. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  44762. this.cellIndex++;
  44763. this._currentFrameCounter = 0;
  44764. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  44765. if (this.particleSystem.spriteCellLoop) {
  44766. this.cellIndex = this.particleSystem.startSpriteCellID;
  44767. }
  44768. else {
  44769. this.cellIndex = this.particleSystem.endSpriteCellID;
  44770. }
  44771. }
  44772. }
  44773. else {
  44774. this._currentFrameCounter++;
  44775. }
  44776. };
  44777. Particle.prototype.copyTo = function (other) {
  44778. other.position.copyFrom(this.position);
  44779. other.direction.copyFrom(this.direction);
  44780. other.color.copyFrom(this.color);
  44781. other.colorStep.copyFrom(this.colorStep);
  44782. other.lifeTime = this.lifeTime;
  44783. other.age = this.age;
  44784. other.size = this.size;
  44785. other.angle = this.angle;
  44786. other.angularSpeed = this.angularSpeed;
  44787. other.particleSystem = this.particleSystem;
  44788. other.cellIndex = this.cellIndex;
  44789. };
  44790. return Particle;
  44791. }());
  44792. BABYLON.Particle = Particle;
  44793. })(BABYLON || (BABYLON = {}));
  44794. //# sourceMappingURL=babylon.particle.js.map
  44795. var BABYLON;
  44796. (function (BABYLON) {
  44797. var randomNumber = function (min, max) {
  44798. if (min === max) {
  44799. return (min);
  44800. }
  44801. var random = Math.random();
  44802. return ((random * (max - min)) + min);
  44803. };
  44804. var ParticleSystem = /** @class */ (function () {
  44805. // end of sheet animation
  44806. function ParticleSystem(name, capacity, scene, customEffect, _isAnimationSheetEnabled, epsilon) {
  44807. if (customEffect === void 0) { customEffect = null; }
  44808. if (_isAnimationSheetEnabled === void 0) { _isAnimationSheetEnabled = false; }
  44809. if (epsilon === void 0) { epsilon = 0.01; }
  44810. var _this = this;
  44811. this.name = name;
  44812. this._isAnimationSheetEnabled = _isAnimationSheetEnabled;
  44813. // Members
  44814. this.animations = [];
  44815. this.renderingGroupId = 0;
  44816. this.emitter = null;
  44817. this.emitRate = 10;
  44818. this.manualEmitCount = -1;
  44819. this.updateSpeed = 0.01;
  44820. this.targetStopDuration = 0;
  44821. this.disposeOnStop = false;
  44822. this.minEmitPower = 1;
  44823. this.maxEmitPower = 1;
  44824. this.minLifeTime = 1;
  44825. this.maxLifeTime = 1;
  44826. this.minSize = 1;
  44827. this.maxSize = 1;
  44828. this.minAngularSpeed = 0;
  44829. this.maxAngularSpeed = 0;
  44830. this.layerMask = 0x0FFFFFFF;
  44831. this.customShader = null;
  44832. this.preventAutoStart = false;
  44833. /**
  44834. * An event triggered when the system is disposed.
  44835. * @type {BABYLON.Observable}
  44836. */
  44837. this.onDisposeObservable = new BABYLON.Observable();
  44838. this.onAnimationEnd = null;
  44839. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  44840. this.forceDepthWrite = false;
  44841. this.gravity = BABYLON.Vector3.Zero();
  44842. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  44843. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  44844. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  44845. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  44846. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44847. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44848. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  44849. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44850. this.particles = new Array();
  44851. this._stockParticles = new Array();
  44852. this._newPartsExcess = 0;
  44853. this._vertexBuffers = {};
  44854. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  44855. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  44856. this._scaledDirection = BABYLON.Vector3.Zero();
  44857. this._scaledGravity = BABYLON.Vector3.Zero();
  44858. this._currentRenderId = -1;
  44859. this._started = false;
  44860. this._stopped = false;
  44861. this._actualFrame = 0;
  44862. // sheet animation
  44863. this.startSpriteCellID = 0;
  44864. this.endSpriteCellID = 0;
  44865. this.spriteCellLoop = true;
  44866. this.spriteCellChangeSpeed = 0;
  44867. this.spriteCellWidth = 0;
  44868. this.spriteCellHeight = 0;
  44869. this._vertexBufferSize = 11;
  44870. this.appendParticleVertexes = null;
  44871. this.id = name;
  44872. this._capacity = capacity;
  44873. this._epsilon = epsilon;
  44874. if (_isAnimationSheetEnabled) {
  44875. this._vertexBufferSize = 12;
  44876. }
  44877. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  44878. this._customEffect = customEffect;
  44879. scene.particleSystems.push(this);
  44880. this._createIndexBuffer();
  44881. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  44882. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  44883. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  44884. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  44885. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  44886. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  44887. if (this._isAnimationSheetEnabled) {
  44888. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  44889. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  44890. }
  44891. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  44892. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  44893. this._vertexBuffers["options"] = options;
  44894. // Default behaviors
  44895. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  44896. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  44897. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  44898. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  44899. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  44900. };
  44901. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  44902. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  44903. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  44904. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  44905. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  44906. };
  44907. this.updateFunction = function (particles) {
  44908. for (var index = 0; index < particles.length; index++) {
  44909. var particle = particles[index];
  44910. particle.age += _this._scaledUpdateSpeed;
  44911. if (particle.age >= particle.lifeTime) {
  44912. _this.recycleParticle(particle);
  44913. index--;
  44914. continue;
  44915. }
  44916. else {
  44917. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  44918. particle.color.addInPlace(_this._scaledColorStep);
  44919. if (particle.color.a < 0)
  44920. particle.color.a = 0;
  44921. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  44922. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  44923. particle.position.addInPlace(_this._scaledDirection);
  44924. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  44925. particle.direction.addInPlace(_this._scaledGravity);
  44926. if (_this._isAnimationSheetEnabled) {
  44927. particle.updateCellIndex(_this._scaledUpdateSpeed);
  44928. }
  44929. }
  44930. }
  44931. };
  44932. }
  44933. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  44934. set: function (callback) {
  44935. if (this._onDisposeObserver) {
  44936. this.onDisposeObservable.remove(this._onDisposeObserver);
  44937. }
  44938. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  44939. },
  44940. enumerable: true,
  44941. configurable: true
  44942. });
  44943. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  44944. get: function () {
  44945. return this._isAnimationSheetEnabled;
  44946. },
  44947. enumerable: true,
  44948. configurable: true
  44949. });
  44950. ParticleSystem.prototype._createIndexBuffer = function () {
  44951. var indices = [];
  44952. var index = 0;
  44953. for (var count = 0; count < this._capacity; count++) {
  44954. indices.push(index);
  44955. indices.push(index + 1);
  44956. indices.push(index + 2);
  44957. indices.push(index);
  44958. indices.push(index + 2);
  44959. indices.push(index + 3);
  44960. index += 4;
  44961. }
  44962. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  44963. };
  44964. ParticleSystem.prototype.recycleParticle = function (particle) {
  44965. var lastParticle = this.particles.pop();
  44966. if (lastParticle !== particle) {
  44967. lastParticle.copyTo(particle);
  44968. this._stockParticles.push(lastParticle);
  44969. }
  44970. };
  44971. ParticleSystem.prototype.getCapacity = function () {
  44972. return this._capacity;
  44973. };
  44974. ParticleSystem.prototype.isAlive = function () {
  44975. return this._alive;
  44976. };
  44977. ParticleSystem.prototype.isStarted = function () {
  44978. return this._started;
  44979. };
  44980. ParticleSystem.prototype.start = function () {
  44981. this._started = true;
  44982. this._stopped = false;
  44983. this._actualFrame = 0;
  44984. };
  44985. ParticleSystem.prototype.stop = function () {
  44986. this._stopped = true;
  44987. };
  44988. // animation sheet
  44989. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  44990. var offset = index * this._vertexBufferSize;
  44991. this._vertexData[offset] = particle.position.x;
  44992. this._vertexData[offset + 1] = particle.position.y;
  44993. this._vertexData[offset + 2] = particle.position.z;
  44994. this._vertexData[offset + 3] = particle.color.r;
  44995. this._vertexData[offset + 4] = particle.color.g;
  44996. this._vertexData[offset + 5] = particle.color.b;
  44997. this._vertexData[offset + 6] = particle.color.a;
  44998. this._vertexData[offset + 7] = particle.angle;
  44999. this._vertexData[offset + 8] = particle.size;
  45000. this._vertexData[offset + 9] = offsetX;
  45001. this._vertexData[offset + 10] = offsetY;
  45002. };
  45003. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  45004. if (offsetX === 0)
  45005. offsetX = this._epsilon;
  45006. else if (offsetX === 1)
  45007. offsetX = 1 - this._epsilon;
  45008. if (offsetY === 0)
  45009. offsetY = this._epsilon;
  45010. else if (offsetY === 1)
  45011. offsetY = 1 - this._epsilon;
  45012. var offset = index * this._vertexBufferSize;
  45013. this._vertexData[offset] = particle.position.x;
  45014. this._vertexData[offset + 1] = particle.position.y;
  45015. this._vertexData[offset + 2] = particle.position.z;
  45016. this._vertexData[offset + 3] = particle.color.r;
  45017. this._vertexData[offset + 4] = particle.color.g;
  45018. this._vertexData[offset + 5] = particle.color.b;
  45019. this._vertexData[offset + 6] = particle.color.a;
  45020. this._vertexData[offset + 7] = particle.angle;
  45021. this._vertexData[offset + 8] = particle.size;
  45022. this._vertexData[offset + 9] = offsetX;
  45023. this._vertexData[offset + 10] = offsetY;
  45024. this._vertexData[offset + 11] = particle.cellIndex;
  45025. };
  45026. ParticleSystem.prototype._update = function (newParticles) {
  45027. // Update current
  45028. this._alive = this.particles.length > 0;
  45029. this.updateFunction(this.particles);
  45030. // Add new ones
  45031. var worldMatrix;
  45032. if (this.emitter.position) {
  45033. var emitterMesh = this.emitter;
  45034. worldMatrix = emitterMesh.getWorldMatrix();
  45035. }
  45036. else {
  45037. var emitterPosition = this.emitter;
  45038. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  45039. }
  45040. var particle;
  45041. for (var index = 0; index < newParticles; index++) {
  45042. if (this.particles.length === this._capacity) {
  45043. break;
  45044. }
  45045. if (this._stockParticles.length !== 0) {
  45046. particle = this._stockParticles.pop();
  45047. particle.age = 0;
  45048. particle.cellIndex = this.startSpriteCellID;
  45049. }
  45050. else {
  45051. particle = new BABYLON.Particle(this);
  45052. }
  45053. this.particles.push(particle);
  45054. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  45055. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  45056. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  45057. particle.size = randomNumber(this.minSize, this.maxSize);
  45058. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  45059. this.startPositionFunction(worldMatrix, particle.position, particle);
  45060. var step = randomNumber(0, 1.0);
  45061. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  45062. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  45063. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  45064. }
  45065. };
  45066. ParticleSystem.prototype._getEffect = function () {
  45067. if (this._customEffect) {
  45068. return this._customEffect;
  45069. }
  45070. ;
  45071. var defines = [];
  45072. if (this._scene.clipPlane) {
  45073. defines.push("#define CLIPPLANE");
  45074. }
  45075. if (this._isAnimationSheetEnabled) {
  45076. defines.push("#define ANIMATESHEET");
  45077. }
  45078. // Effect
  45079. var join = defines.join("\n");
  45080. if (this._cachedDefines !== join) {
  45081. this._cachedDefines = join;
  45082. var attributesNamesOrOptions;
  45083. var effectCreationOption;
  45084. if (this._isAnimationSheetEnabled) {
  45085. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  45086. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  45087. }
  45088. else {
  45089. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  45090. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  45091. }
  45092. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  45093. }
  45094. return this._effect;
  45095. };
  45096. ParticleSystem.prototype.animate = function () {
  45097. if (!this._started)
  45098. return;
  45099. var effect = this._getEffect();
  45100. // Check
  45101. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  45102. return;
  45103. if (this._currentRenderId === this._scene.getRenderId()) {
  45104. return;
  45105. }
  45106. this._currentRenderId = this._scene.getRenderId();
  45107. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  45108. // determine the number of particles we need to create
  45109. var newParticles;
  45110. if (this.manualEmitCount > -1) {
  45111. newParticles = this.manualEmitCount;
  45112. this._newPartsExcess = 0;
  45113. this.manualEmitCount = 0;
  45114. }
  45115. else {
  45116. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  45117. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  45118. }
  45119. if (this._newPartsExcess > 1.0) {
  45120. newParticles += this._newPartsExcess >> 0;
  45121. this._newPartsExcess -= this._newPartsExcess >> 0;
  45122. }
  45123. this._alive = false;
  45124. if (!this._stopped) {
  45125. this._actualFrame += this._scaledUpdateSpeed;
  45126. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  45127. this.stop();
  45128. }
  45129. else {
  45130. newParticles = 0;
  45131. }
  45132. this._update(newParticles);
  45133. // Stopped?
  45134. if (this._stopped) {
  45135. if (!this._alive) {
  45136. this._started = false;
  45137. if (this.onAnimationEnd) {
  45138. this.onAnimationEnd();
  45139. }
  45140. if (this.disposeOnStop) {
  45141. this._scene._toBeDisposed.push(this);
  45142. }
  45143. }
  45144. }
  45145. // Animation sheet
  45146. if (this._isAnimationSheetEnabled) {
  45147. this.appendParticleVertexes = this.appenedParticleVertexesWithSheet;
  45148. }
  45149. else {
  45150. this.appendParticleVertexes = this.appenedParticleVertexesNoSheet;
  45151. }
  45152. // Update VBO
  45153. var offset = 0;
  45154. for (var index = 0; index < this.particles.length; index++) {
  45155. var particle = this.particles[index];
  45156. this.appendParticleVertexes(offset, particle);
  45157. offset += 4;
  45158. }
  45159. if (this._vertexBuffer) {
  45160. this._vertexBuffer.update(this._vertexData);
  45161. }
  45162. };
  45163. ParticleSystem.prototype.appenedParticleVertexesWithSheet = function (offset, particle) {
  45164. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  45165. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  45166. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  45167. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  45168. };
  45169. ParticleSystem.prototype.appenedParticleVertexesNoSheet = function (offset, particle) {
  45170. this._appendParticleVertex(offset++, particle, 0, 0);
  45171. this._appendParticleVertex(offset++, particle, 1, 0);
  45172. this._appendParticleVertex(offset++, particle, 1, 1);
  45173. this._appendParticleVertex(offset++, particle, 0, 1);
  45174. };
  45175. ParticleSystem.prototype.rebuild = function () {
  45176. this._createIndexBuffer();
  45177. if (this._vertexBuffer) {
  45178. this._vertexBuffer._rebuild();
  45179. }
  45180. };
  45181. ParticleSystem.prototype.render = function () {
  45182. var effect = this._getEffect();
  45183. // Check
  45184. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  45185. return 0;
  45186. var engine = this._scene.getEngine();
  45187. // Render
  45188. engine.enableEffect(effect);
  45189. engine.setState(false);
  45190. var viewMatrix = this._scene.getViewMatrix();
  45191. effect.setTexture("diffuseSampler", this.particleTexture);
  45192. effect.setMatrix("view", viewMatrix);
  45193. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  45194. if (this._isAnimationSheetEnabled) {
  45195. var baseSize = this.particleTexture.getBaseSize();
  45196. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  45197. }
  45198. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  45199. if (this._scene.clipPlane) {
  45200. var clipPlane = this._scene.clipPlane;
  45201. var invView = viewMatrix.clone();
  45202. invView.invert();
  45203. effect.setMatrix("invView", invView);
  45204. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  45205. }
  45206. // VBOs
  45207. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  45208. // Draw order
  45209. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  45210. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  45211. }
  45212. else {
  45213. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  45214. }
  45215. if (this.forceDepthWrite) {
  45216. engine.setDepthWrite(true);
  45217. }
  45218. engine.draw(true, 0, this.particles.length * 6);
  45219. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  45220. return this.particles.length;
  45221. };
  45222. ParticleSystem.prototype.dispose = function () {
  45223. if (this._vertexBuffer) {
  45224. this._vertexBuffer.dispose();
  45225. this._vertexBuffer = null;
  45226. }
  45227. if (this._indexBuffer) {
  45228. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  45229. this._indexBuffer = null;
  45230. }
  45231. if (this.particleTexture) {
  45232. this.particleTexture.dispose();
  45233. this.particleTexture = null;
  45234. }
  45235. // Remove from scene
  45236. var index = this._scene.particleSystems.indexOf(this);
  45237. if (index > -1) {
  45238. this._scene.particleSystems.splice(index, 1);
  45239. }
  45240. // Callback
  45241. this.onDisposeObservable.notifyObservers(this);
  45242. this.onDisposeObservable.clear();
  45243. };
  45244. // Clone
  45245. ParticleSystem.prototype.clone = function (name, newEmitter) {
  45246. var custom = null;
  45247. var program = null;
  45248. if (this.customShader != null) {
  45249. program = this.customShader;
  45250. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  45251. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  45252. }
  45253. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  45254. result.customShader = program;
  45255. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  45256. if (newEmitter === undefined) {
  45257. newEmitter = this.emitter;
  45258. }
  45259. result.emitter = newEmitter;
  45260. if (this.particleTexture) {
  45261. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  45262. }
  45263. if (!this.preventAutoStart) {
  45264. result.start();
  45265. }
  45266. return result;
  45267. };
  45268. ParticleSystem.prototype.serialize = function () {
  45269. var serializationObject = {};
  45270. serializationObject.name = this.name;
  45271. serializationObject.id = this.id;
  45272. // Emitter
  45273. if (this.emitter.position) {
  45274. var emitterMesh = this.emitter;
  45275. serializationObject.emitterId = emitterMesh.id;
  45276. }
  45277. else {
  45278. var emitterPosition = this.emitter;
  45279. serializationObject.emitter = emitterPosition.asArray();
  45280. }
  45281. serializationObject.capacity = this.getCapacity();
  45282. if (this.particleTexture) {
  45283. serializationObject.textureName = this.particleTexture.name;
  45284. }
  45285. // Animations
  45286. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  45287. // Particle system
  45288. serializationObject.minAngularSpeed = this.minAngularSpeed;
  45289. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  45290. serializationObject.minSize = this.minSize;
  45291. serializationObject.maxSize = this.maxSize;
  45292. serializationObject.minEmitPower = this.minEmitPower;
  45293. serializationObject.maxEmitPower = this.maxEmitPower;
  45294. serializationObject.minLifeTime = this.minLifeTime;
  45295. serializationObject.maxLifeTime = this.maxLifeTime;
  45296. serializationObject.emitRate = this.emitRate;
  45297. serializationObject.minEmitBox = this.minEmitBox.asArray();
  45298. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  45299. serializationObject.gravity = this.gravity.asArray();
  45300. serializationObject.direction1 = this.direction1.asArray();
  45301. serializationObject.direction2 = this.direction2.asArray();
  45302. serializationObject.color1 = this.color1.asArray();
  45303. serializationObject.color2 = this.color2.asArray();
  45304. serializationObject.colorDead = this.colorDead.asArray();
  45305. serializationObject.updateSpeed = this.updateSpeed;
  45306. serializationObject.targetStopDuration = this.targetStopDuration;
  45307. serializationObject.textureMask = this.textureMask.asArray();
  45308. serializationObject.blendMode = this.blendMode;
  45309. serializationObject.customShader = this.customShader;
  45310. serializationObject.preventAutoStart = this.preventAutoStart;
  45311. return serializationObject;
  45312. };
  45313. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  45314. var name = parsedParticleSystem.name;
  45315. var custom = null;
  45316. var program = null;
  45317. if (parsedParticleSystem.customShader) {
  45318. program = parsedParticleSystem.customShader;
  45319. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  45320. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  45321. }
  45322. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  45323. particleSystem.customShader = program;
  45324. if (parsedParticleSystem.id) {
  45325. particleSystem.id = parsedParticleSystem.id;
  45326. }
  45327. // Auto start
  45328. if (parsedParticleSystem.preventAutoStart) {
  45329. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  45330. }
  45331. // Texture
  45332. if (parsedParticleSystem.textureName) {
  45333. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  45334. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  45335. }
  45336. // Emitter
  45337. if (parsedParticleSystem.emitterId) {
  45338. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  45339. }
  45340. else {
  45341. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  45342. }
  45343. // Animations
  45344. if (parsedParticleSystem.animations) {
  45345. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  45346. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  45347. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  45348. }
  45349. }
  45350. if (parsedParticleSystem.autoAnimate) {
  45351. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  45352. }
  45353. // Particle system
  45354. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  45355. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  45356. particleSystem.minSize = parsedParticleSystem.minSize;
  45357. particleSystem.maxSize = parsedParticleSystem.maxSize;
  45358. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  45359. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  45360. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  45361. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  45362. particleSystem.emitRate = parsedParticleSystem.emitRate;
  45363. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  45364. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  45365. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  45366. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  45367. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  45368. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  45369. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  45370. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  45371. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  45372. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  45373. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  45374. particleSystem.blendMode = parsedParticleSystem.blendMode;
  45375. if (!particleSystem.preventAutoStart) {
  45376. particleSystem.start();
  45377. }
  45378. return particleSystem;
  45379. };
  45380. // Statics
  45381. ParticleSystem.BLENDMODE_ONEONE = 0;
  45382. ParticleSystem.BLENDMODE_STANDARD = 1;
  45383. return ParticleSystem;
  45384. }());
  45385. BABYLON.ParticleSystem = ParticleSystem;
  45386. })(BABYLON || (BABYLON = {}));
  45387. //# sourceMappingURL=babylon.particleSystem.js.map
  45388. var BABYLON;
  45389. (function (BABYLON) {
  45390. var SolidParticle = /** @class */ (function () {
  45391. /**
  45392. * Creates a Solid Particle object.
  45393. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  45394. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  45395. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  45396. * `indiceIndex` (integer) is the starting index of the particle indices in the SPS "indices" array.
  45397. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  45398. * `shapeId` (integer) is the model shape identifier in the SPS.
  45399. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  45400. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  45401. */
  45402. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  45403. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  45404. this.idx = 0; // particle global index
  45405. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  45406. this.position = BABYLON.Vector3.Zero(); // position
  45407. this.rotation = BABYLON.Vector3.Zero(); // rotation
  45408. this.scaling = BABYLON.Vector3.One(); // scaling
  45409. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  45410. this.velocity = BABYLON.Vector3.Zero(); // velocity
  45411. this.pivot = BABYLON.Vector3.Zero(); // pivot point in the particle local space
  45412. this.alive = true; // alive
  45413. this.isVisible = true; // visibility
  45414. this._pos = 0; // index of this particle in the global "positions" array
  45415. this._ind = 0; // index of this particle in the global "indices" array
  45416. this.shapeId = 0; // model shape id
  45417. this.idxInShape = 0; // index of the particle in its shape id
  45418. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  45419. this.idx = particleIndex;
  45420. this._pos = positionIndex;
  45421. this._ind = indiceIndex;
  45422. this._model = model;
  45423. this.shapeId = shapeId;
  45424. this.idxInShape = idxInShape;
  45425. this._sps = sps;
  45426. if (modelBoundingInfo) {
  45427. this._modelBoundingInfo = modelBoundingInfo;
  45428. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  45429. }
  45430. }
  45431. Object.defineProperty(SolidParticle.prototype, "scale", {
  45432. /**
  45433. * legacy support, changed scale to scaling
  45434. */
  45435. get: function () {
  45436. return this.scaling;
  45437. },
  45438. set: function (scale) {
  45439. this.scaling = scale;
  45440. },
  45441. enumerable: true,
  45442. configurable: true
  45443. });
  45444. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  45445. /**
  45446. * legacy support, changed quaternion to rotationQuaternion
  45447. */
  45448. get: function () {
  45449. return this.rotationQuaternion;
  45450. },
  45451. set: function (q) {
  45452. this.rotationQuaternion = q;
  45453. },
  45454. enumerable: true,
  45455. configurable: true
  45456. });
  45457. /**
  45458. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  45459. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  45460. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  45461. */
  45462. SolidParticle.prototype.intersectsMesh = function (target) {
  45463. if (!this._boundingInfo || !target._boundingInfo) {
  45464. return false;
  45465. }
  45466. if (this._sps._bSphereOnly) {
  45467. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  45468. }
  45469. return this._boundingInfo.intersects(target._boundingInfo, false);
  45470. };
  45471. return SolidParticle;
  45472. }());
  45473. BABYLON.SolidParticle = SolidParticle;
  45474. var ModelShape = /** @class */ (function () {
  45475. /**
  45476. * 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.
  45477. * SPS internal tool, don't use it manually.
  45478. */
  45479. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  45480. this._indicesLength = 0; // length of the shape in the model indices array
  45481. this.shapeID = id;
  45482. this._shape = shape;
  45483. this._indicesLength = indicesLength;
  45484. this._shapeUV = shapeUV;
  45485. this._positionFunction = posFunction;
  45486. this._vertexFunction = vtxFunction;
  45487. }
  45488. return ModelShape;
  45489. }());
  45490. BABYLON.ModelShape = ModelShape;
  45491. var DepthSortedParticle = /** @class */ (function () {
  45492. function DepthSortedParticle() {
  45493. this.ind = 0; // index of the particle in the "indices" array
  45494. this.indicesLength = 0; // length of the particle shape in the "indices" array
  45495. this.sqDistance = 0.0; // squared distance from the particle to the camera
  45496. }
  45497. return DepthSortedParticle;
  45498. }());
  45499. BABYLON.DepthSortedParticle = DepthSortedParticle;
  45500. })(BABYLON || (BABYLON = {}));
  45501. //# sourceMappingURL=babylon.solidParticle.js.map
  45502. var BABYLON;
  45503. (function (BABYLON) {
  45504. /**
  45505. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  45506. */
  45507. var SolidParticleSystem = /** @class */ (function () {
  45508. /**
  45509. * Creates a SPS (Solid Particle System) object.
  45510. * `name` (String) is the SPS name, this will be the underlying mesh name.
  45511. * `scene` (Scene) is the scene in which the SPS is added.
  45512. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  45513. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  45514. * `enableDepthSort` (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  45515. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  45516. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  45517. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  45518. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  45519. */
  45520. function SolidParticleSystem(name, scene, options) {
  45521. // public members
  45522. /**
  45523. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  45524. * Example : var p = SPS.particles[i];
  45525. */
  45526. this.particles = new Array();
  45527. /**
  45528. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  45529. */
  45530. this.nbParticles = 0;
  45531. /**
  45532. * If the particles must ever face the camera (default false). Useful for planar particles.
  45533. */
  45534. this.billboard = false;
  45535. /**
  45536. * Recompute normals when adding a shape
  45537. */
  45538. this.recomputeNormals = true;
  45539. /**
  45540. * This a counter ofr your own usage. It's not set by any SPS functions.
  45541. */
  45542. this.counter = 0;
  45543. /**
  45544. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  45545. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  45546. */
  45547. this.vars = {};
  45548. this._positions = new Array();
  45549. this._indices = new Array();
  45550. this._normals = new Array();
  45551. this._colors = new Array();
  45552. this._uvs = new Array();
  45553. this._index = 0; // indices index
  45554. this._updatable = true;
  45555. this._pickable = false;
  45556. this._isVisibilityBoxLocked = false;
  45557. this._alwaysVisible = false;
  45558. this._depthSort = false;
  45559. this._shapeCounter = 0;
  45560. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  45561. this._color = new BABYLON.Color4(0, 0, 0, 0);
  45562. this._computeParticleColor = true;
  45563. this._computeParticleTexture = true;
  45564. this._computeParticleRotation = true;
  45565. this._computeParticleVertex = false;
  45566. this._computeBoundingBox = false;
  45567. this._depthSortParticles = true;
  45568. this._cam_axisZ = BABYLON.Vector3.Zero();
  45569. this._cam_axisY = BABYLON.Vector3.Zero();
  45570. this._cam_axisX = BABYLON.Vector3.Zero();
  45571. this._axisZ = BABYLON.Axis.Z;
  45572. this._camDir = BABYLON.Vector3.Zero();
  45573. this._camInvertedPosition = BABYLON.Vector3.Zero();
  45574. this._rotMatrix = new BABYLON.Matrix();
  45575. this._invertMatrix = new BABYLON.Matrix();
  45576. this._rotated = BABYLON.Vector3.Zero();
  45577. this._quaternion = new BABYLON.Quaternion();
  45578. this._vertex = BABYLON.Vector3.Zero();
  45579. this._normal = BABYLON.Vector3.Zero();
  45580. this._yaw = 0.0;
  45581. this._pitch = 0.0;
  45582. this._roll = 0.0;
  45583. this._halfroll = 0.0;
  45584. this._halfpitch = 0.0;
  45585. this._halfyaw = 0.0;
  45586. this._sinRoll = 0.0;
  45587. this._cosRoll = 0.0;
  45588. this._sinPitch = 0.0;
  45589. this._cosPitch = 0.0;
  45590. this._sinYaw = 0.0;
  45591. this._cosYaw = 0.0;
  45592. this._mustUnrotateFixedNormals = false;
  45593. this._minimum = BABYLON.Tmp.Vector3[0];
  45594. this._maximum = BABYLON.Tmp.Vector3[1];
  45595. this._minBbox = BABYLON.Tmp.Vector3[4];
  45596. this._maxBbox = BABYLON.Tmp.Vector3[5];
  45597. this._particlesIntersect = false;
  45598. this._depthSortFunction = function (p1, p2) {
  45599. return (p2.sqDistance - p1.sqDistance);
  45600. };
  45601. this._needs32Bits = false;
  45602. this._bSphereOnly = false;
  45603. this._bSphereRadiusFactor = 1.0;
  45604. this.name = name;
  45605. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  45606. this._camera = scene.activeCamera;
  45607. this._pickable = options ? options.isPickable : false;
  45608. this._depthSort = options ? options.enableDepthSort : false;
  45609. this._particlesIntersect = options ? options.particleIntersection : false;
  45610. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  45611. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  45612. if (options && options.updatable) {
  45613. this._updatable = options.updatable;
  45614. }
  45615. else {
  45616. this._updatable = true;
  45617. }
  45618. if (this._pickable) {
  45619. this.pickedParticles = [];
  45620. }
  45621. if (this._depthSort) {
  45622. this.depthSortedParticles = [];
  45623. }
  45624. }
  45625. /**
  45626. * Builds the SPS underlying mesh. Returns a standard Mesh.
  45627. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  45628. */
  45629. SolidParticleSystem.prototype.buildMesh = function () {
  45630. if (this.nbParticles === 0) {
  45631. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  45632. this.addShape(triangle, 1);
  45633. triangle.dispose();
  45634. }
  45635. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  45636. this._positions32 = new Float32Array(this._positions);
  45637. this._uvs32 = new Float32Array(this._uvs);
  45638. this._colors32 = new Float32Array(this._colors);
  45639. if (this.recomputeNormals) {
  45640. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  45641. }
  45642. this._normals32 = new Float32Array(this._normals);
  45643. this._fixedNormal32 = new Float32Array(this._normals);
  45644. if (this._mustUnrotateFixedNormals) {
  45645. this._unrotateFixedNormals();
  45646. }
  45647. var vertexData = new BABYLON.VertexData();
  45648. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  45649. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  45650. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  45651. if (this._uvs32) {
  45652. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  45653. ;
  45654. }
  45655. if (this._colors32) {
  45656. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  45657. }
  45658. var mesh = new BABYLON.Mesh(this.name, this._scene);
  45659. vertexData.applyToMesh(mesh, this._updatable);
  45660. this.mesh = mesh;
  45661. this.mesh.isPickable = this._pickable;
  45662. // free memory
  45663. if (!this._depthSort) {
  45664. this._indices = null;
  45665. }
  45666. this._positions = null;
  45667. this._normals = null;
  45668. this._uvs = null;
  45669. this._colors = null;
  45670. if (!this._updatable) {
  45671. this.particles.length = 0;
  45672. }
  45673. return mesh;
  45674. };
  45675. /**
  45676. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  45677. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  45678. * Thus the particles generated from `digest()` have their property `position` set yet.
  45679. * `mesh` ( Mesh ) is the mesh to be digested
  45680. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  45681. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  45682. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  45683. */
  45684. SolidParticleSystem.prototype.digest = function (mesh, options) {
  45685. var size = (options && options.facetNb) || 1;
  45686. var number = (options && options.number) || 0;
  45687. var delta = (options && options.delta) || 0;
  45688. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45689. var meshInd = mesh.getIndices();
  45690. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  45691. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  45692. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  45693. var f = 0; // facet counter
  45694. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  45695. // compute size from number
  45696. if (number) {
  45697. number = (number > totalFacets) ? totalFacets : number;
  45698. size = Math.round(totalFacets / number);
  45699. delta = 0;
  45700. }
  45701. else {
  45702. size = (size > totalFacets) ? totalFacets : size;
  45703. }
  45704. var facetPos = []; // submesh positions
  45705. var facetInd = []; // submesh indices
  45706. var facetUV = []; // submesh UV
  45707. var facetCol = []; // submesh colors
  45708. var barycenter = BABYLON.Tmp.Vector3[0];
  45709. var sizeO = size;
  45710. while (f < totalFacets) {
  45711. size = sizeO + Math.floor((1 + delta) * Math.random());
  45712. if (f > totalFacets - size) {
  45713. size = totalFacets - f;
  45714. }
  45715. // reset temp arrays
  45716. facetPos.length = 0;
  45717. facetInd.length = 0;
  45718. facetUV.length = 0;
  45719. facetCol.length = 0;
  45720. // iterate over "size" facets
  45721. var fi = 0;
  45722. for (var j = f * 3; j < (f + size) * 3; j++) {
  45723. facetInd.push(fi);
  45724. var i = meshInd[j];
  45725. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  45726. if (meshUV) {
  45727. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  45728. }
  45729. if (meshCol) {
  45730. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  45731. }
  45732. fi++;
  45733. }
  45734. // create a model shape for each single particle
  45735. var idx = this.nbParticles;
  45736. var shape = this._posToShape(facetPos);
  45737. var shapeUV = this._uvsToShapeUV(facetUV);
  45738. // compute the barycenter of the shape
  45739. var v;
  45740. for (v = 0; v < shape.length; v++) {
  45741. barycenter.addInPlace(shape[v]);
  45742. }
  45743. barycenter.scaleInPlace(1 / shape.length);
  45744. // shift the shape from its barycenter to the origin
  45745. for (v = 0; v < shape.length; v++) {
  45746. shape[v].subtractInPlace(barycenter);
  45747. }
  45748. var bInfo;
  45749. if (this._particlesIntersect) {
  45750. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  45751. }
  45752. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  45753. // add the particle in the SPS
  45754. var currentPos = this._positions.length;
  45755. var currentInd = this._indices.length;
  45756. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  45757. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  45758. // initialize the particle position
  45759. this.particles[this.nbParticles].position.addInPlace(barycenter);
  45760. this._index += shape.length;
  45761. idx++;
  45762. this.nbParticles++;
  45763. this._shapeCounter++;
  45764. f += size;
  45765. }
  45766. return this;
  45767. };
  45768. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  45769. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  45770. var index = 0;
  45771. var idx = 0;
  45772. for (var p = 0; p < this.particles.length; p++) {
  45773. this._particle = this.particles[p];
  45774. this._shape = this._particle._model._shape;
  45775. if (this._particle.rotationQuaternion) {
  45776. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  45777. }
  45778. else {
  45779. this._yaw = this._particle.rotation.y;
  45780. this._pitch = this._particle.rotation.x;
  45781. this._roll = this._particle.rotation.z;
  45782. this._quaternionRotationYPR();
  45783. }
  45784. this._quaternionToRotationMatrix();
  45785. this._rotMatrix.invertToRef(this._invertMatrix);
  45786. for (var pt = 0; pt < this._shape.length; pt++) {
  45787. idx = index + pt * 3;
  45788. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  45789. this._fixedNormal32[idx] = this._normal.x;
  45790. this._fixedNormal32[idx + 1] = this._normal.y;
  45791. this._fixedNormal32[idx + 2] = this._normal.z;
  45792. }
  45793. index = idx + 3;
  45794. }
  45795. };
  45796. //reset copy
  45797. SolidParticleSystem.prototype._resetCopy = function () {
  45798. this._copy.position.x = 0;
  45799. this._copy.position.y = 0;
  45800. this._copy.position.z = 0;
  45801. this._copy.rotation.x = 0;
  45802. this._copy.rotation.y = 0;
  45803. this._copy.rotation.z = 0;
  45804. this._copy.rotationQuaternion = null;
  45805. this._copy.scaling.x = 1.0;
  45806. this._copy.scaling.y = 1.0;
  45807. this._copy.scaling.z = 1.0;
  45808. this._copy.uvs.x = 0;
  45809. this._copy.uvs.y = 0;
  45810. this._copy.uvs.z = 1.0;
  45811. this._copy.uvs.w = 1.0;
  45812. this._copy.color = null;
  45813. };
  45814. // _meshBuilder : inserts the shape model in the global SPS mesh
  45815. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  45816. var i;
  45817. var u = 0;
  45818. var c = 0;
  45819. var n = 0;
  45820. this._resetCopy();
  45821. if (options && options.positionFunction) {
  45822. options.positionFunction(this._copy, idx, idxInShape);
  45823. this._mustUnrotateFixedNormals = true;
  45824. }
  45825. if (this._copy.rotationQuaternion) {
  45826. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  45827. }
  45828. else {
  45829. this._yaw = this._copy.rotation.y;
  45830. this._pitch = this._copy.rotation.x;
  45831. this._roll = this._copy.rotation.z;
  45832. this._quaternionRotationYPR();
  45833. }
  45834. this._quaternionToRotationMatrix();
  45835. for (i = 0; i < shape.length; i++) {
  45836. this._vertex.x = shape[i].x;
  45837. this._vertex.y = shape[i].y;
  45838. this._vertex.z = shape[i].z;
  45839. if (options && options.vertexFunction) {
  45840. options.vertexFunction(this._copy, this._vertex, i);
  45841. }
  45842. this._vertex.x *= this._copy.scaling.x;
  45843. this._vertex.y *= this._copy.scaling.y;
  45844. this._vertex.z *= this._copy.scaling.z;
  45845. this._vertex.x += this._copy.pivot.x;
  45846. this._vertex.y += this._copy.pivot.y;
  45847. this._vertex.z += this._copy.pivot.z;
  45848. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  45849. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  45850. if (meshUV) {
  45851. 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);
  45852. u += 2;
  45853. }
  45854. if (this._copy.color) {
  45855. this._color = this._copy.color;
  45856. }
  45857. else if (meshCol && meshCol[c] !== undefined) {
  45858. this._color.r = meshCol[c];
  45859. this._color.g = meshCol[c + 1];
  45860. this._color.b = meshCol[c + 2];
  45861. this._color.a = meshCol[c + 3];
  45862. }
  45863. else {
  45864. this._color.r = 1.0;
  45865. this._color.g = 1.0;
  45866. this._color.b = 1.0;
  45867. this._color.a = 1.0;
  45868. }
  45869. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  45870. c += 4;
  45871. if (!this.recomputeNormals && meshNor) {
  45872. this._normal.x = meshNor[n];
  45873. this._normal.y = meshNor[n + 1];
  45874. this._normal.z = meshNor[n + 2];
  45875. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  45876. normals.push(this._normal.x, this._normal.y, this._normal.z);
  45877. n += 3;
  45878. }
  45879. }
  45880. for (i = 0; i < meshInd.length; i++) {
  45881. var current_ind = p + meshInd[i];
  45882. indices.push(current_ind);
  45883. if (current_ind > 65535) {
  45884. this._needs32Bits = true;
  45885. }
  45886. }
  45887. if (this._pickable) {
  45888. var nbfaces = meshInd.length / 3;
  45889. for (i = 0; i < nbfaces; i++) {
  45890. this.pickedParticles.push({ idx: idx, faceId: i });
  45891. }
  45892. }
  45893. if (this._depthSort) {
  45894. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  45895. }
  45896. return this._copy;
  45897. };
  45898. // returns a shape array from positions array
  45899. SolidParticleSystem.prototype._posToShape = function (positions) {
  45900. var shape = [];
  45901. for (var i = 0; i < positions.length; i += 3) {
  45902. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  45903. }
  45904. return shape;
  45905. };
  45906. // returns a shapeUV array from a Vector4 uvs
  45907. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  45908. var shapeUV = [];
  45909. if (uvs) {
  45910. for (var i = 0; i < uvs.length; i++)
  45911. shapeUV.push(uvs[i]);
  45912. }
  45913. return shapeUV;
  45914. };
  45915. // adds a new particle object in the particles array
  45916. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  45917. if (bInfo === void 0) { bInfo = null; }
  45918. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  45919. this.particles.push(sp);
  45920. return sp;
  45921. };
  45922. /**
  45923. * Adds some particles to the SPS from the model shape. Returns the shape id.
  45924. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  45925. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  45926. * `nb` (positive integer) the number of particles to be created from this model
  45927. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  45928. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  45929. */
  45930. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  45931. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45932. var meshInd = mesh.getIndices();
  45933. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  45934. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  45935. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  45936. var bbInfo;
  45937. if (this._particlesIntersect) {
  45938. bbInfo = mesh.getBoundingInfo();
  45939. }
  45940. var shape = this._posToShape(meshPos);
  45941. var shapeUV = this._uvsToShapeUV(meshUV);
  45942. var posfunc = options ? options.positionFunction : null;
  45943. var vtxfunc = options ? options.vertexFunction : null;
  45944. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  45945. // particles
  45946. var sp;
  45947. var currentCopy;
  45948. var idx = this.nbParticles;
  45949. for (var i = 0; i < nb; i++) {
  45950. var currentPos = this._positions.length;
  45951. var currentInd = this._indices.length;
  45952. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  45953. if (this._updatable) {
  45954. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  45955. sp.position.copyFrom(currentCopy.position);
  45956. sp.rotation.copyFrom(currentCopy.rotation);
  45957. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  45958. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  45959. }
  45960. if (currentCopy.color && sp.color) {
  45961. sp.color.copyFrom(currentCopy.color);
  45962. }
  45963. sp.scaling.copyFrom(currentCopy.scaling);
  45964. sp.uvs.copyFrom(currentCopy.uvs);
  45965. }
  45966. this._index += shape.length;
  45967. idx++;
  45968. }
  45969. this.nbParticles += nb;
  45970. this._shapeCounter++;
  45971. return this._shapeCounter - 1;
  45972. };
  45973. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  45974. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  45975. this._resetCopy();
  45976. if (particle._model._positionFunction) {
  45977. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  45978. }
  45979. if (this._copy.rotationQuaternion) {
  45980. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  45981. }
  45982. else {
  45983. this._yaw = this._copy.rotation.y;
  45984. this._pitch = this._copy.rotation.x;
  45985. this._roll = this._copy.rotation.z;
  45986. this._quaternionRotationYPR();
  45987. }
  45988. this._quaternionToRotationMatrix();
  45989. this._shape = particle._model._shape;
  45990. for (var pt = 0; pt < this._shape.length; pt++) {
  45991. this._vertex.x = this._shape[pt].x;
  45992. this._vertex.y = this._shape[pt].y;
  45993. this._vertex.z = this._shape[pt].z;
  45994. if (particle._model._vertexFunction) {
  45995. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  45996. }
  45997. this._vertex.x *= this._copy.scaling.x;
  45998. this._vertex.y *= this._copy.scaling.y;
  45999. this._vertex.z *= this._copy.scaling.z;
  46000. this._vertex.x += this._copy.pivot.x;
  46001. this._vertex.y += this._copy.pivot.y;
  46002. this._vertex.z += this._copy.pivot.z;
  46003. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  46004. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  46005. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  46006. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  46007. }
  46008. particle.position.x = 0.0;
  46009. particle.position.y = 0.0;
  46010. particle.position.z = 0.0;
  46011. particle.rotation.x = 0.0;
  46012. particle.rotation.y = 0.0;
  46013. particle.rotation.z = 0.0;
  46014. particle.rotationQuaternion = null;
  46015. particle.scaling.x = 1.0;
  46016. particle.scaling.y = 1.0;
  46017. particle.scaling.z = 1.0;
  46018. };
  46019. /**
  46020. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  46021. * Returns the SPS.
  46022. */
  46023. SolidParticleSystem.prototype.rebuildMesh = function () {
  46024. for (var p = 0; p < this.particles.length; p++) {
  46025. this._rebuildParticle(this.particles[p]);
  46026. }
  46027. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  46028. return this;
  46029. };
  46030. /**
  46031. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  46032. * This method calls `updateParticle()` for each particle of the SPS.
  46033. * For an animated SPS, it is usually called within the render loop.
  46034. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  46035. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  46036. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  46037. * Returns the SPS.
  46038. */
  46039. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  46040. if (start === void 0) { start = 0; }
  46041. if (end === void 0) { end = this.nbParticles - 1; }
  46042. if (update === void 0) { update = true; }
  46043. if (!this._updatable) {
  46044. return this;
  46045. }
  46046. // custom beforeUpdate
  46047. this.beforeUpdateParticles(start, end, update);
  46048. this._cam_axisX.x = 1.0;
  46049. this._cam_axisX.y = 0.0;
  46050. this._cam_axisX.z = 0.0;
  46051. this._cam_axisY.x = 0.0;
  46052. this._cam_axisY.y = 1.0;
  46053. this._cam_axisY.z = 0.0;
  46054. this._cam_axisZ.x = 0.0;
  46055. this._cam_axisZ.y = 0.0;
  46056. this._cam_axisZ.z = 1.0;
  46057. // cases when the World Matrix is to be computed first
  46058. if (this.billboard || this._depthSort) {
  46059. this.mesh.computeWorldMatrix(true);
  46060. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  46061. }
  46062. // if the particles will always face the camera
  46063. if (this.billboard) {
  46064. // compute the camera position and un-rotate it by the current mesh rotation
  46065. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  46066. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  46067. this._cam_axisZ.normalize();
  46068. // same for camera up vector extracted from the cam view matrix
  46069. var view = this._camera.getViewMatrix(true);
  46070. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  46071. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  46072. this._cam_axisY.normalize();
  46073. this._cam_axisX.normalize();
  46074. }
  46075. // if depthSort, compute the camera global position in the mesh local system
  46076. if (this._depthSort) {
  46077. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  46078. }
  46079. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  46080. var idx = 0; // current position index in the global array positions32
  46081. var index = 0; // position start index in the global array positions32 of the current particle
  46082. var colidx = 0; // current color index in the global array colors32
  46083. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  46084. var uvidx = 0; // current uv index in the global array uvs32
  46085. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  46086. var pt = 0; // current index in the particle model shape
  46087. if (this.mesh.isFacetDataEnabled) {
  46088. this._computeBoundingBox = true;
  46089. }
  46090. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  46091. if (this._computeBoundingBox) {
  46092. if (start == 0 && end == this.nbParticles - 1) {
  46093. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  46094. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  46095. }
  46096. else {
  46097. if (this.mesh._boundingInfo) {
  46098. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  46099. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  46100. }
  46101. }
  46102. }
  46103. // particle loop
  46104. index = this.particles[start]._pos;
  46105. var vpos = (index / 3) | 0;
  46106. colorIndex = vpos * 4;
  46107. uvIndex = vpos * 2;
  46108. for (var p = start; p <= end; p++) {
  46109. this._particle = this.particles[p];
  46110. this._shape = this._particle._model._shape;
  46111. this._shapeUV = this._particle._model._shapeUV;
  46112. // call to custom user function to update the particle properties
  46113. this.updateParticle(this._particle);
  46114. // camera-particle distance for depth sorting
  46115. if (this._depthSort && this._depthSortParticles) {
  46116. var dsp = this.depthSortedParticles[p];
  46117. dsp.ind = this._particle._ind;
  46118. dsp.indicesLength = this._particle._model._indicesLength;
  46119. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  46120. }
  46121. // skip the computations for inactive or already invisible particles
  46122. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  46123. // increment indexes for the next particle
  46124. pt = this._shape.length;
  46125. index += pt * 3;
  46126. colorIndex += pt * 4;
  46127. uvIndex += pt * 2;
  46128. continue;
  46129. }
  46130. if (this._particle.isVisible) {
  46131. this._particle._stillInvisible = false; // un-mark permanent invisibility
  46132. // particle rotation matrix
  46133. if (this.billboard) {
  46134. this._particle.rotation.x = 0.0;
  46135. this._particle.rotation.y = 0.0;
  46136. }
  46137. if (this._computeParticleRotation || this.billboard) {
  46138. if (this._particle.rotationQuaternion) {
  46139. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  46140. }
  46141. else {
  46142. this._yaw = this._particle.rotation.y;
  46143. this._pitch = this._particle.rotation.x;
  46144. this._roll = this._particle.rotation.z;
  46145. this._quaternionRotationYPR();
  46146. }
  46147. this._quaternionToRotationMatrix();
  46148. }
  46149. // particle vertex loop
  46150. for (pt = 0; pt < this._shape.length; pt++) {
  46151. idx = index + pt * 3;
  46152. colidx = colorIndex + pt * 4;
  46153. uvidx = uvIndex + pt * 2;
  46154. this._vertex.x = this._shape[pt].x;
  46155. this._vertex.y = this._shape[pt].y;
  46156. this._vertex.z = this._shape[pt].z;
  46157. if (this._computeParticleVertex) {
  46158. this.updateParticleVertex(this._particle, this._vertex, pt);
  46159. }
  46160. // positions
  46161. this._vertex.x *= this._particle.scaling.x;
  46162. this._vertex.y *= this._particle.scaling.y;
  46163. this._vertex.z *= this._particle.scaling.z;
  46164. this._vertex.x += this._particle.pivot.x;
  46165. this._vertex.y += this._particle.pivot.y;
  46166. this._vertex.z += this._particle.pivot.z;
  46167. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  46168. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  46169. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  46170. 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;
  46171. 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;
  46172. 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;
  46173. if (this._computeBoundingBox) {
  46174. if (this._positions32[idx] < this._minimum.x) {
  46175. this._minimum.x = this._positions32[idx];
  46176. }
  46177. if (this._positions32[idx] > this._maximum.x) {
  46178. this._maximum.x = this._positions32[idx];
  46179. }
  46180. if (this._positions32[idx + 1] < this._minimum.y) {
  46181. this._minimum.y = this._positions32[idx + 1];
  46182. }
  46183. if (this._positions32[idx + 1] > this._maximum.y) {
  46184. this._maximum.y = this._positions32[idx + 1];
  46185. }
  46186. if (this._positions32[idx + 2] < this._minimum.z) {
  46187. this._minimum.z = this._positions32[idx + 2];
  46188. }
  46189. if (this._positions32[idx + 2] > this._maximum.z) {
  46190. this._maximum.z = this._positions32[idx + 2];
  46191. }
  46192. }
  46193. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  46194. if (!this._computeParticleVertex) {
  46195. this._normal.x = this._fixedNormal32[idx];
  46196. this._normal.y = this._fixedNormal32[idx + 1];
  46197. this._normal.z = this._fixedNormal32[idx + 2];
  46198. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  46199. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  46200. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  46201. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  46202. 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;
  46203. 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;
  46204. }
  46205. if (this._computeParticleColor && this._particle.color) {
  46206. this._colors32[colidx] = this._particle.color.r;
  46207. this._colors32[colidx + 1] = this._particle.color.g;
  46208. this._colors32[colidx + 2] = this._particle.color.b;
  46209. this._colors32[colidx + 3] = this._particle.color.a;
  46210. }
  46211. if (this._computeParticleTexture) {
  46212. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  46213. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  46214. }
  46215. }
  46216. }
  46217. else {
  46218. this._particle._stillInvisible = true; // mark the particle as invisible
  46219. for (pt = 0; pt < this._shape.length; pt++) {
  46220. idx = index + pt * 3;
  46221. colidx = colorIndex + pt * 4;
  46222. uvidx = uvIndex + pt * 2;
  46223. this._positions32[idx] = 0.0;
  46224. this._positions32[idx + 1] = 0.0;
  46225. this._positions32[idx + 2] = 0.0;
  46226. this._normals32[idx] = 0.0;
  46227. this._normals32[idx + 1] = 0.0;
  46228. this._normals32[idx + 2] = 0.0;
  46229. if (this._computeParticleColor && this._particle.color) {
  46230. this._colors32[colidx] = this._particle.color.r;
  46231. this._colors32[colidx + 1] = this._particle.color.g;
  46232. this._colors32[colidx + 2] = this._particle.color.b;
  46233. this._colors32[colidx + 3] = this._particle.color.a;
  46234. }
  46235. if (this._computeParticleTexture) {
  46236. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  46237. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  46238. }
  46239. }
  46240. }
  46241. // if the particle intersections must be computed : update the bbInfo
  46242. if (this._particlesIntersect) {
  46243. var bInfo = this._particle._boundingInfo;
  46244. var bBox = bInfo.boundingBox;
  46245. var bSphere = bInfo.boundingSphere;
  46246. if (!this._bSphereOnly) {
  46247. // place, scale and rotate the particle bbox within the SPS local system, then update it
  46248. for (var b = 0; b < bBox.vectors.length; b++) {
  46249. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  46250. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  46251. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  46252. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  46253. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  46254. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  46255. 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;
  46256. 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;
  46257. 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;
  46258. }
  46259. bBox._update(this.mesh._worldMatrix);
  46260. }
  46261. // place and scale the particle bouding sphere in the SPS local system, then update it
  46262. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  46263. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  46264. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  46265. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  46266. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  46267. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  46268. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  46269. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  46270. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  46271. 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));
  46272. bSphere._update(this.mesh._worldMatrix);
  46273. }
  46274. // increment indexes for the next particle
  46275. index = idx + 3;
  46276. colorIndex = colidx + 4;
  46277. uvIndex = uvidx + 2;
  46278. }
  46279. // if the VBO must be updated
  46280. if (update) {
  46281. if (this._computeParticleColor) {
  46282. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  46283. }
  46284. if (this._computeParticleTexture) {
  46285. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  46286. }
  46287. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  46288. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  46289. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  46290. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  46291. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  46292. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  46293. for (var i = 0; i < this._normals32.length; i++) {
  46294. this._fixedNormal32[i] = this._normals32[i];
  46295. }
  46296. }
  46297. if (!this.mesh.areNormalsFrozen) {
  46298. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  46299. }
  46300. }
  46301. if (this._depthSort && this._depthSortParticles) {
  46302. this.depthSortedParticles.sort(this._depthSortFunction);
  46303. var dspl = this.depthSortedParticles.length;
  46304. var sorted = 0;
  46305. var lind = 0;
  46306. var sind = 0;
  46307. var sid = 0;
  46308. for (sorted = 0; sorted < dspl; sorted++) {
  46309. lind = this.depthSortedParticles[sorted].indicesLength;
  46310. sind = this.depthSortedParticles[sorted].ind;
  46311. for (var i = 0; i < lind; i++) {
  46312. this._indices32[sid] = this._indices[sind + i];
  46313. sid++;
  46314. }
  46315. }
  46316. this.mesh.updateIndices(this._indices32);
  46317. }
  46318. }
  46319. if (this._computeBoundingBox) {
  46320. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  46321. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  46322. }
  46323. this.afterUpdateParticles(start, end, update);
  46324. return this;
  46325. };
  46326. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  46327. this._halfroll = this._roll * 0.5;
  46328. this._halfpitch = this._pitch * 0.5;
  46329. this._halfyaw = this._yaw * 0.5;
  46330. this._sinRoll = Math.sin(this._halfroll);
  46331. this._cosRoll = Math.cos(this._halfroll);
  46332. this._sinPitch = Math.sin(this._halfpitch);
  46333. this._cosPitch = Math.cos(this._halfpitch);
  46334. this._sinYaw = Math.sin(this._halfyaw);
  46335. this._cosYaw = Math.cos(this._halfyaw);
  46336. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  46337. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  46338. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  46339. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  46340. };
  46341. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  46342. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  46343. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  46344. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  46345. this._rotMatrix.m[3] = 0;
  46346. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  46347. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  46348. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  46349. this._rotMatrix.m[7] = 0;
  46350. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  46351. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  46352. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  46353. this._rotMatrix.m[11] = 0;
  46354. this._rotMatrix.m[12] = 0;
  46355. this._rotMatrix.m[13] = 0;
  46356. this._rotMatrix.m[14] = 0;
  46357. this._rotMatrix.m[15] = 1.0;
  46358. };
  46359. /**
  46360. * Disposes the SPS.
  46361. * Returns nothing.
  46362. */
  46363. SolidParticleSystem.prototype.dispose = function () {
  46364. this.mesh.dispose();
  46365. this.vars = null;
  46366. // drop references to internal big arrays for the GC
  46367. this._positions = null;
  46368. this._indices = null;
  46369. this._normals = null;
  46370. this._uvs = null;
  46371. this._colors = null;
  46372. this._indices32 = null;
  46373. this._positions32 = null;
  46374. this._normals32 = null;
  46375. this._fixedNormal32 = null;
  46376. this._uvs32 = null;
  46377. this._colors32 = null;
  46378. this.pickedParticles = null;
  46379. };
  46380. /**
  46381. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  46382. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  46383. * Returns the SPS.
  46384. */
  46385. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  46386. if (!this._isVisibilityBoxLocked) {
  46387. this.mesh.refreshBoundingInfo();
  46388. }
  46389. return this;
  46390. };
  46391. /**
  46392. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  46393. * @param size the size (float) of the visibility box
  46394. * note : this doesn't lock the SPS mesh bounding box.
  46395. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  46396. */
  46397. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  46398. var vis = size / 2;
  46399. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  46400. };
  46401. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  46402. // getter and setter
  46403. get: function () {
  46404. return this._alwaysVisible;
  46405. },
  46406. /**
  46407. * Sets the SPS as always visible or not
  46408. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  46409. */
  46410. set: function (val) {
  46411. this._alwaysVisible = val;
  46412. this.mesh.alwaysSelectAsActiveMesh = val;
  46413. },
  46414. enumerable: true,
  46415. configurable: true
  46416. });
  46417. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  46418. get: function () {
  46419. return this._isVisibilityBoxLocked;
  46420. },
  46421. /**
  46422. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  46423. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  46424. */
  46425. set: function (val) {
  46426. this._isVisibilityBoxLocked = val;
  46427. var boundingInfo = this.mesh.getBoundingInfo();
  46428. boundingInfo.isLocked = val;
  46429. },
  46430. enumerable: true,
  46431. configurable: true
  46432. });
  46433. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  46434. // getters
  46435. get: function () {
  46436. return this._computeParticleRotation;
  46437. },
  46438. // Optimizer setters
  46439. /**
  46440. * Tells to `setParticles()` to compute the particle rotations or not.
  46441. * Default value : true. The SPS is faster when it's set to false.
  46442. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  46443. */
  46444. set: function (val) {
  46445. this._computeParticleRotation = val;
  46446. },
  46447. enumerable: true,
  46448. configurable: true
  46449. });
  46450. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  46451. get: function () {
  46452. return this._computeParticleColor;
  46453. },
  46454. /**
  46455. * Tells to `setParticles()` to compute the particle colors or not.
  46456. * Default value : true. The SPS is faster when it's set to false.
  46457. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  46458. */
  46459. set: function (val) {
  46460. this._computeParticleColor = val;
  46461. },
  46462. enumerable: true,
  46463. configurable: true
  46464. });
  46465. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  46466. get: function () {
  46467. return this._computeParticleTexture;
  46468. },
  46469. /**
  46470. * Tells to `setParticles()` to compute the particle textures or not.
  46471. * Default value : true. The SPS is faster when it's set to false.
  46472. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  46473. */
  46474. set: function (val) {
  46475. this._computeParticleTexture = val;
  46476. },
  46477. enumerable: true,
  46478. configurable: true
  46479. });
  46480. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  46481. get: function () {
  46482. return this._computeParticleVertex;
  46483. },
  46484. /**
  46485. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  46486. * Default value : false. The SPS is faster when it's set to false.
  46487. * Note : the particle custom vertex positions aren't stored values.
  46488. */
  46489. set: function (val) {
  46490. this._computeParticleVertex = val;
  46491. },
  46492. enumerable: true,
  46493. configurable: true
  46494. });
  46495. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  46496. get: function () {
  46497. return this._computeBoundingBox;
  46498. },
  46499. /**
  46500. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  46501. */
  46502. set: function (val) {
  46503. this._computeBoundingBox = val;
  46504. },
  46505. enumerable: true,
  46506. configurable: true
  46507. });
  46508. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  46509. get: function () {
  46510. return this._depthSortParticles;
  46511. },
  46512. /**
  46513. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  46514. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  46515. * Default : `true`
  46516. */
  46517. set: function (val) {
  46518. this._depthSortParticles = val;
  46519. },
  46520. enumerable: true,
  46521. configurable: true
  46522. });
  46523. // =======================================================================
  46524. // Particle behavior logic
  46525. // these following methods may be overwritten by the user to fit his needs
  46526. /**
  46527. * This function does nothing. It may be overwritten to set all the particle first values.
  46528. * The SPS doesn't call this function, you may have to call it by your own.
  46529. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  46530. */
  46531. SolidParticleSystem.prototype.initParticles = function () {
  46532. };
  46533. /**
  46534. * This function does nothing. It may be overwritten to recycle a particle.
  46535. * The SPS doesn't call this function, you may have to call it by your own.
  46536. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  46537. */
  46538. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  46539. return particle;
  46540. };
  46541. /**
  46542. * Updates a particle : this function should be overwritten by the user.
  46543. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  46544. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  46545. * ex : just set a particle position or velocity and recycle conditions
  46546. */
  46547. SolidParticleSystem.prototype.updateParticle = function (particle) {
  46548. return particle;
  46549. };
  46550. /**
  46551. * Updates a vertex of a particle : it can be overwritten by the user.
  46552. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  46553. * @param particle the current particle
  46554. * @param vertex the current index of the current particle
  46555. * @param pt the index of the current vertex in the particle shape
  46556. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  46557. * ex : just set a vertex particle position
  46558. */
  46559. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  46560. return vertex;
  46561. };
  46562. /**
  46563. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  46564. * This does nothing and may be overwritten by the user.
  46565. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  46566. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  46567. * @param update the boolean update value actually passed to setParticles()
  46568. */
  46569. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  46570. };
  46571. /**
  46572. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  46573. * This will be passed three parameters.
  46574. * This does nothing and may be overwritten by the user.
  46575. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  46576. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  46577. * @param update the boolean update value actually passed to setParticles()
  46578. */
  46579. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  46580. };
  46581. return SolidParticleSystem;
  46582. }());
  46583. BABYLON.SolidParticleSystem = SolidParticleSystem;
  46584. })(BABYLON || (BABYLON = {}));
  46585. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  46586. var BABYLON;
  46587. (function (BABYLON) {
  46588. var GroundMesh = /** @class */ (function (_super) {
  46589. __extends(GroundMesh, _super);
  46590. function GroundMesh(name, scene) {
  46591. var _this = _super.call(this, name, scene) || this;
  46592. _this.generateOctree = false;
  46593. return _this;
  46594. }
  46595. GroundMesh.prototype.getClassName = function () {
  46596. return "GroundMesh";
  46597. };
  46598. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  46599. get: function () {
  46600. return Math.min(this._subdivisionsX, this._subdivisionsY);
  46601. },
  46602. enumerable: true,
  46603. configurable: true
  46604. });
  46605. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  46606. get: function () {
  46607. return this._subdivisionsX;
  46608. },
  46609. enumerable: true,
  46610. configurable: true
  46611. });
  46612. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  46613. get: function () {
  46614. return this._subdivisionsY;
  46615. },
  46616. enumerable: true,
  46617. configurable: true
  46618. });
  46619. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  46620. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  46621. this._subdivisionsX = chunksCount;
  46622. this._subdivisionsY = chunksCount;
  46623. this.subdivide(chunksCount);
  46624. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  46625. };
  46626. /**
  46627. * Returns a height (y) value in the Worl system :
  46628. * the ground altitude at the coordinates (x, z) expressed in the World system.
  46629. * Returns the ground y position if (x, z) are outside the ground surface.
  46630. */
  46631. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  46632. var world = this.getWorldMatrix();
  46633. var invMat = BABYLON.Tmp.Matrix[5];
  46634. world.invertToRef(invMat);
  46635. var tmpVect = BABYLON.Tmp.Vector3[8];
  46636. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  46637. x = tmpVect.x;
  46638. z = tmpVect.z;
  46639. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  46640. return this.position.y;
  46641. }
  46642. if (!this._heightQuads || this._heightQuads.length == 0) {
  46643. this._initHeightQuads();
  46644. this._computeHeightQuads();
  46645. }
  46646. var facet = this._getFacetAt(x, z);
  46647. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  46648. // return y in the World system
  46649. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  46650. return tmpVect.y;
  46651. };
  46652. /**
  46653. * Returns a normalized vector (Vector3) orthogonal to the ground
  46654. * at the ground coordinates (x, z) expressed in the World system.
  46655. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  46656. */
  46657. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  46658. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  46659. this.getNormalAtCoordinatesToRef(x, z, normal);
  46660. return normal;
  46661. };
  46662. /**
  46663. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  46664. * at the ground coordinates (x, z) expressed in the World system.
  46665. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  46666. * Returns the GroundMesh.
  46667. */
  46668. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  46669. var world = this.getWorldMatrix();
  46670. var tmpMat = BABYLON.Tmp.Matrix[5];
  46671. world.invertToRef(tmpMat);
  46672. var tmpVect = BABYLON.Tmp.Vector3[8];
  46673. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  46674. x = tmpVect.x;
  46675. z = tmpVect.z;
  46676. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  46677. return this;
  46678. }
  46679. if (!this._heightQuads || this._heightQuads.length == 0) {
  46680. this._initHeightQuads();
  46681. this._computeHeightQuads();
  46682. }
  46683. var facet = this._getFacetAt(x, z);
  46684. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  46685. return this;
  46686. };
  46687. /**
  46688. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  46689. * if the ground has been updated.
  46690. * This can be used in the render loop.
  46691. * Returns the GroundMesh.
  46692. */
  46693. GroundMesh.prototype.updateCoordinateHeights = function () {
  46694. if (!this._heightQuads || this._heightQuads.length == 0) {
  46695. this._initHeightQuads();
  46696. }
  46697. this._computeHeightQuads();
  46698. return this;
  46699. };
  46700. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  46701. GroundMesh.prototype._getFacetAt = function (x, z) {
  46702. // retrieve col and row from x, z coordinates in the ground local system
  46703. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  46704. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  46705. var quad = this._heightQuads[row * this._subdivisionsX + col];
  46706. var facet;
  46707. if (z < quad.slope.x * x + quad.slope.y) {
  46708. facet = quad.facet1;
  46709. }
  46710. else {
  46711. facet = quad.facet2;
  46712. }
  46713. return facet;
  46714. };
  46715. // Creates and populates the heightMap array with "facet" elements :
  46716. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  46717. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  46718. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  46719. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  46720. // Returns the GroundMesh.
  46721. GroundMesh.prototype._initHeightQuads = function () {
  46722. var subdivisionsX = this._subdivisionsX;
  46723. var subdivisionsY = this._subdivisionsY;
  46724. this._heightQuads = new Array();
  46725. for (var row = 0; row < subdivisionsY; row++) {
  46726. for (var col = 0; col < subdivisionsX; col++) {
  46727. 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) };
  46728. this._heightQuads[row * subdivisionsX + col] = quad;
  46729. }
  46730. }
  46731. return this;
  46732. };
  46733. // Compute each quad element values and update the the heightMap array :
  46734. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  46735. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  46736. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  46737. // Returns the GroundMesh.
  46738. GroundMesh.prototype._computeHeightQuads = function () {
  46739. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46740. if (!positions) {
  46741. return this;
  46742. }
  46743. var v1 = BABYLON.Tmp.Vector3[3];
  46744. var v2 = BABYLON.Tmp.Vector3[2];
  46745. var v3 = BABYLON.Tmp.Vector3[1];
  46746. var v4 = BABYLON.Tmp.Vector3[0];
  46747. var v1v2 = BABYLON.Tmp.Vector3[4];
  46748. var v1v3 = BABYLON.Tmp.Vector3[5];
  46749. var v1v4 = BABYLON.Tmp.Vector3[6];
  46750. var norm1 = BABYLON.Tmp.Vector3[7];
  46751. var norm2 = BABYLON.Tmp.Vector3[8];
  46752. var i = 0;
  46753. var j = 0;
  46754. var k = 0;
  46755. var cd = 0; // 2D slope coefficient : z = cd * x + h
  46756. var h = 0;
  46757. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  46758. var d2 = 0;
  46759. var subdivisionsX = this._subdivisionsX;
  46760. var subdivisionsY = this._subdivisionsY;
  46761. for (var row = 0; row < subdivisionsY; row++) {
  46762. for (var col = 0; col < subdivisionsX; col++) {
  46763. i = col * 3;
  46764. j = row * (subdivisionsX + 1) * 3;
  46765. k = (row + 1) * (subdivisionsX + 1) * 3;
  46766. v1.x = positions[j + i];
  46767. v1.y = positions[j + i + 1];
  46768. v1.z = positions[j + i + 2];
  46769. v2.x = positions[j + i + 3];
  46770. v2.y = positions[j + i + 4];
  46771. v2.z = positions[j + i + 5];
  46772. v3.x = positions[k + i];
  46773. v3.y = positions[k + i + 1];
  46774. v3.z = positions[k + i + 2];
  46775. v4.x = positions[k + i + 3];
  46776. v4.y = positions[k + i + 4];
  46777. v4.z = positions[k + i + 5];
  46778. // 2D slope V1V4
  46779. cd = (v4.z - v1.z) / (v4.x - v1.x);
  46780. h = v1.z - cd * v1.x; // v1 belongs to the slope
  46781. // facet equations :
  46782. // we compute each facet normal vector
  46783. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  46784. // we compute the value d by applying the equation to v1 which belongs to the plane
  46785. // then we store the facet equation in a Vector4
  46786. v2.subtractToRef(v1, v1v2);
  46787. v3.subtractToRef(v1, v1v3);
  46788. v4.subtractToRef(v1, v1v4);
  46789. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  46790. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  46791. norm1.normalize();
  46792. norm2.normalize();
  46793. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  46794. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  46795. var quad = this._heightQuads[row * subdivisionsX + col];
  46796. quad.slope.copyFromFloats(cd, h);
  46797. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  46798. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  46799. }
  46800. }
  46801. return this;
  46802. };
  46803. GroundMesh.prototype.serialize = function (serializationObject) {
  46804. _super.prototype.serialize.call(this, serializationObject);
  46805. serializationObject.subdivisionsX = this._subdivisionsX;
  46806. serializationObject.subdivisionsY = this._subdivisionsY;
  46807. serializationObject.minX = this._minX;
  46808. serializationObject.maxX = this._maxX;
  46809. serializationObject.minZ = this._minZ;
  46810. serializationObject.maxZ = this._maxZ;
  46811. serializationObject.width = this._width;
  46812. serializationObject.height = this._height;
  46813. };
  46814. GroundMesh.Parse = function (parsedMesh, scene) {
  46815. var result = new GroundMesh(parsedMesh.name, scene);
  46816. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  46817. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  46818. result._minX = parsedMesh.minX;
  46819. result._maxX = parsedMesh.maxX;
  46820. result._minZ = parsedMesh.minZ;
  46821. result._maxZ = parsedMesh.maxZ;
  46822. result._width = parsedMesh.width;
  46823. result._height = parsedMesh.height;
  46824. return result;
  46825. };
  46826. return GroundMesh;
  46827. }(BABYLON.Mesh));
  46828. BABYLON.GroundMesh = GroundMesh;
  46829. })(BABYLON || (BABYLON = {}));
  46830. //# sourceMappingURL=babylon.groundMesh.js.map
  46831. var BABYLON;
  46832. (function (BABYLON) {
  46833. /**
  46834. * Creates an instance based on a source mesh.
  46835. */
  46836. var InstancedMesh = /** @class */ (function (_super) {
  46837. __extends(InstancedMesh, _super);
  46838. function InstancedMesh(name, source) {
  46839. var _this = _super.call(this, name, source.getScene()) || this;
  46840. source.instances.push(_this);
  46841. _this._sourceMesh = source;
  46842. _this.position.copyFrom(source.position);
  46843. _this.rotation.copyFrom(source.rotation);
  46844. _this.scaling.copyFrom(source.scaling);
  46845. if (source.rotationQuaternion) {
  46846. _this.rotationQuaternion = source.rotationQuaternion.clone();
  46847. }
  46848. _this.infiniteDistance = source.infiniteDistance;
  46849. _this.setPivotMatrix(source.getPivotMatrix());
  46850. _this.refreshBoundingInfo();
  46851. _this._syncSubMeshes();
  46852. return _this;
  46853. }
  46854. /**
  46855. * Returns the string "InstancedMesh".
  46856. */
  46857. InstancedMesh.prototype.getClassName = function () {
  46858. return "InstancedMesh";
  46859. };
  46860. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  46861. // Methods
  46862. get: function () {
  46863. return this._sourceMesh.receiveShadows;
  46864. },
  46865. enumerable: true,
  46866. configurable: true
  46867. });
  46868. Object.defineProperty(InstancedMesh.prototype, "material", {
  46869. get: function () {
  46870. return this._sourceMesh.material;
  46871. },
  46872. enumerable: true,
  46873. configurable: true
  46874. });
  46875. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  46876. get: function () {
  46877. return this._sourceMesh.visibility;
  46878. },
  46879. enumerable: true,
  46880. configurable: true
  46881. });
  46882. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  46883. get: function () {
  46884. return this._sourceMesh.skeleton;
  46885. },
  46886. enumerable: true,
  46887. configurable: true
  46888. });
  46889. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  46890. get: function () {
  46891. return this._sourceMesh.renderingGroupId;
  46892. },
  46893. enumerable: true,
  46894. configurable: true
  46895. });
  46896. /**
  46897. * Returns the total number of vertices (integer).
  46898. */
  46899. InstancedMesh.prototype.getTotalVertices = function () {
  46900. return this._sourceMesh.getTotalVertices();
  46901. };
  46902. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  46903. get: function () {
  46904. return this._sourceMesh;
  46905. },
  46906. enumerable: true,
  46907. configurable: true
  46908. });
  46909. /**
  46910. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  46911. */
  46912. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  46913. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  46914. };
  46915. /**
  46916. * Sets the vertex data of the mesh geometry for the requested `kind`.
  46917. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  46918. * The `data` are either a numeric array either a Float32Array.
  46919. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  46920. * 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).
  46921. * Note that a new underlying VertexBuffer object is created each call.
  46922. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  46923. *
  46924. * Possible `kind` values :
  46925. * - BABYLON.VertexBuffer.PositionKind
  46926. * - BABYLON.VertexBuffer.UVKind
  46927. * - BABYLON.VertexBuffer.UV2Kind
  46928. * - BABYLON.VertexBuffer.UV3Kind
  46929. * - BABYLON.VertexBuffer.UV4Kind
  46930. * - BABYLON.VertexBuffer.UV5Kind
  46931. * - BABYLON.VertexBuffer.UV6Kind
  46932. * - BABYLON.VertexBuffer.ColorKind
  46933. * - BABYLON.VertexBuffer.MatricesIndicesKind
  46934. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  46935. * - BABYLON.VertexBuffer.MatricesWeightsKind
  46936. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  46937. *
  46938. * Returns the Mesh.
  46939. */
  46940. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  46941. if (this.sourceMesh) {
  46942. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  46943. }
  46944. return this.sourceMesh;
  46945. };
  46946. /**
  46947. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  46948. * If the mesh has no geometry, it is simply returned as it is.
  46949. * The `data` are either a numeric array either a Float32Array.
  46950. * No new underlying VertexBuffer object is created.
  46951. * 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.
  46952. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  46953. *
  46954. * Possible `kind` values :
  46955. * - BABYLON.VertexBuffer.PositionKind
  46956. * - BABYLON.VertexBuffer.UVKind
  46957. * - BABYLON.VertexBuffer.UV2Kind
  46958. * - BABYLON.VertexBuffer.UV3Kind
  46959. * - BABYLON.VertexBuffer.UV4Kind
  46960. * - BABYLON.VertexBuffer.UV5Kind
  46961. * - BABYLON.VertexBuffer.UV6Kind
  46962. * - BABYLON.VertexBuffer.ColorKind
  46963. * - BABYLON.VertexBuffer.MatricesIndicesKind
  46964. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  46965. * - BABYLON.VertexBuffer.MatricesWeightsKind
  46966. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  46967. *
  46968. * Returns the Mesh.
  46969. */
  46970. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  46971. if (this.sourceMesh) {
  46972. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  46973. }
  46974. return this.sourceMesh;
  46975. };
  46976. /**
  46977. * Sets the mesh indices.
  46978. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  46979. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  46980. * This method creates a new index buffer each call.
  46981. * Returns the Mesh.
  46982. */
  46983. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  46984. if (totalVertices === void 0) { totalVertices = null; }
  46985. if (this.sourceMesh) {
  46986. this.sourceMesh.setIndices(indices, totalVertices);
  46987. }
  46988. return this.sourceMesh;
  46989. };
  46990. /**
  46991. * Boolean : True if the mesh owns the requested kind of data.
  46992. */
  46993. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  46994. return this._sourceMesh.isVerticesDataPresent(kind);
  46995. };
  46996. /**
  46997. * Returns an array of indices (IndicesArray).
  46998. */
  46999. InstancedMesh.prototype.getIndices = function () {
  47000. return this._sourceMesh.getIndices();
  47001. };
  47002. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  47003. get: function () {
  47004. return this._sourceMesh._positions;
  47005. },
  47006. enumerable: true,
  47007. configurable: true
  47008. });
  47009. /**
  47010. * Sets a new updated BoundingInfo to the mesh.
  47011. * Returns the mesh.
  47012. */
  47013. InstancedMesh.prototype.refreshBoundingInfo = function () {
  47014. var meshBB = this._sourceMesh.getBoundingInfo();
  47015. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  47016. this._updateBoundingInfo();
  47017. return this;
  47018. };
  47019. InstancedMesh.prototype._preActivate = function () {
  47020. if (this._currentLOD) {
  47021. this._currentLOD._preActivate();
  47022. }
  47023. return this;
  47024. };
  47025. InstancedMesh.prototype._activate = function (renderId) {
  47026. if (this._currentLOD) {
  47027. this._currentLOD._registerInstanceForRenderId(this, renderId);
  47028. }
  47029. return this;
  47030. };
  47031. /**
  47032. * Returns the current associated LOD AbstractMesh.
  47033. */
  47034. InstancedMesh.prototype.getLOD = function (camera) {
  47035. if (!camera) {
  47036. return this;
  47037. }
  47038. var boundingInfo = this.getBoundingInfo();
  47039. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  47040. if (this._currentLOD === this.sourceMesh) {
  47041. return this;
  47042. }
  47043. return this._currentLOD;
  47044. };
  47045. InstancedMesh.prototype._syncSubMeshes = function () {
  47046. this.releaseSubMeshes();
  47047. if (this._sourceMesh.subMeshes) {
  47048. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  47049. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  47050. }
  47051. }
  47052. return this;
  47053. };
  47054. InstancedMesh.prototype._generatePointsArray = function () {
  47055. return this._sourceMesh._generatePointsArray();
  47056. };
  47057. /**
  47058. * Creates a new InstancedMesh from the current mesh.
  47059. * - name (string) : the cloned mesh name
  47060. * - newParent (optional Node) : the optional Node to parent the clone to.
  47061. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  47062. *
  47063. * Returns the clone.
  47064. */
  47065. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  47066. var result = this._sourceMesh.createInstance(name);
  47067. // Deep copy
  47068. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  47069. // Bounding info
  47070. this.refreshBoundingInfo();
  47071. // Parent
  47072. if (newParent) {
  47073. result.parent = newParent;
  47074. }
  47075. if (!doNotCloneChildren) {
  47076. // Children
  47077. for (var index = 0; index < this.getScene().meshes.length; index++) {
  47078. var mesh = this.getScene().meshes[index];
  47079. if (mesh.parent === this) {
  47080. mesh.clone(mesh.name, result);
  47081. }
  47082. }
  47083. }
  47084. result.computeWorldMatrix(true);
  47085. return result;
  47086. };
  47087. /**
  47088. * Disposes the InstancedMesh.
  47089. * Returns nothing.
  47090. */
  47091. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  47092. // Remove from mesh
  47093. var index = this._sourceMesh.instances.indexOf(this);
  47094. this._sourceMesh.instances.splice(index, 1);
  47095. _super.prototype.dispose.call(this, doNotRecurse);
  47096. };
  47097. return InstancedMesh;
  47098. }(BABYLON.AbstractMesh));
  47099. BABYLON.InstancedMesh = InstancedMesh;
  47100. })(BABYLON || (BABYLON = {}));
  47101. //# sourceMappingURL=babylon.instancedMesh.js.map
  47102. var BABYLON;
  47103. (function (BABYLON) {
  47104. var LinesMesh = /** @class */ (function (_super) {
  47105. __extends(LinesMesh, _super);
  47106. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  47107. if (scene === void 0) { scene = null; }
  47108. if (parent === void 0) { parent = null; }
  47109. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  47110. _this.useVertexColor = useVertexColor;
  47111. _this.useVertexAlpha = useVertexAlpha;
  47112. _this.color = new BABYLON.Color3(1, 1, 1);
  47113. _this.alpha = 1;
  47114. if (source) {
  47115. _this.color = source.color.clone();
  47116. _this.alpha = source.alpha;
  47117. _this.useVertexColor = source.useVertexColor;
  47118. _this.useVertexAlpha = source.useVertexAlpha;
  47119. }
  47120. _this._intersectionThreshold = 0.1;
  47121. var defines = [];
  47122. var options = {
  47123. attributes: [BABYLON.VertexBuffer.PositionKind],
  47124. uniforms: ["world", "viewProjection"],
  47125. needAlphaBlending: true,
  47126. defines: defines
  47127. };
  47128. if (useVertexAlpha === false) {
  47129. options.needAlphaBlending = false;
  47130. }
  47131. if (!useVertexColor) {
  47132. options.uniforms.push("color");
  47133. }
  47134. else {
  47135. options.defines.push("#define VERTEXCOLOR");
  47136. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  47137. }
  47138. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  47139. return _this;
  47140. }
  47141. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  47142. /**
  47143. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  47144. * This margin is expressed in world space coordinates, so its value may vary.
  47145. * Default value is 0.1
  47146. * @returns the intersection Threshold value.
  47147. */
  47148. get: function () {
  47149. return this._intersectionThreshold;
  47150. },
  47151. /**
  47152. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  47153. * This margin is expressed in world space coordinates, so its value may vary.
  47154. * @param value the new threshold to apply
  47155. */
  47156. set: function (value) {
  47157. if (this._intersectionThreshold === value) {
  47158. return;
  47159. }
  47160. this._intersectionThreshold = value;
  47161. if (this.geometry) {
  47162. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  47163. }
  47164. },
  47165. enumerable: true,
  47166. configurable: true
  47167. });
  47168. /**
  47169. * Returns the string "LineMesh"
  47170. */
  47171. LinesMesh.prototype.getClassName = function () {
  47172. return "LinesMesh";
  47173. };
  47174. Object.defineProperty(LinesMesh.prototype, "material", {
  47175. get: function () {
  47176. return this._colorShader;
  47177. },
  47178. set: function (value) {
  47179. // Do nothing
  47180. },
  47181. enumerable: true,
  47182. configurable: true
  47183. });
  47184. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  47185. get: function () {
  47186. return false;
  47187. },
  47188. enumerable: true,
  47189. configurable: true
  47190. });
  47191. LinesMesh.prototype.createInstance = function (name) {
  47192. throw new Error("LinesMeshes do not support createInstance.");
  47193. };
  47194. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  47195. if (!this._geometry) {
  47196. return this;
  47197. }
  47198. // VBOs
  47199. this._geometry._bind(this._colorShader.getEffect());
  47200. // Color
  47201. if (!this.useVertexColor) {
  47202. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  47203. }
  47204. return this;
  47205. };
  47206. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  47207. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  47208. return this;
  47209. }
  47210. var engine = this.getScene().getEngine();
  47211. // Draw order
  47212. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  47213. return this;
  47214. };
  47215. LinesMesh.prototype.dispose = function (doNotRecurse) {
  47216. this._colorShader.dispose();
  47217. _super.prototype.dispose.call(this, doNotRecurse);
  47218. };
  47219. /**
  47220. * Returns a new LineMesh object cloned from the current one.
  47221. */
  47222. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  47223. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  47224. };
  47225. return LinesMesh;
  47226. }(BABYLON.Mesh));
  47227. BABYLON.LinesMesh = LinesMesh;
  47228. })(BABYLON || (BABYLON = {}));
  47229. //# sourceMappingURL=babylon.linesMesh.js.map
  47230. var BABYLON;
  47231. (function (BABYLON) {
  47232. var ShaderMaterial = /** @class */ (function (_super) {
  47233. __extends(ShaderMaterial, _super);
  47234. function ShaderMaterial(name, scene, shaderPath, options) {
  47235. var _this = _super.call(this, name, scene) || this;
  47236. _this._textures = {};
  47237. _this._textureArrays = {};
  47238. _this._floats = {};
  47239. _this._floatsArrays = {};
  47240. _this._colors3 = {};
  47241. _this._colors3Arrays = {};
  47242. _this._colors4 = {};
  47243. _this._vectors2 = {};
  47244. _this._vectors3 = {};
  47245. _this._vectors4 = {};
  47246. _this._matrices = {};
  47247. _this._matrices3x3 = {};
  47248. _this._matrices2x2 = {};
  47249. _this._vectors2Arrays = {};
  47250. _this._vectors3Arrays = {};
  47251. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  47252. _this._shaderPath = shaderPath;
  47253. options.needAlphaBlending = options.needAlphaBlending || false;
  47254. options.needAlphaTesting = options.needAlphaTesting || false;
  47255. options.attributes = options.attributes || ["position", "normal", "uv"];
  47256. options.uniforms = options.uniforms || ["worldViewProjection"];
  47257. options.uniformBuffers = options.uniformBuffers || [];
  47258. options.samplers = options.samplers || [];
  47259. options.defines = options.defines || [];
  47260. _this._options = options;
  47261. return _this;
  47262. }
  47263. ShaderMaterial.prototype.getClassName = function () {
  47264. return "ShaderMaterial";
  47265. };
  47266. ShaderMaterial.prototype.needAlphaBlending = function () {
  47267. return this._options.needAlphaBlending;
  47268. };
  47269. ShaderMaterial.prototype.needAlphaTesting = function () {
  47270. return this._options.needAlphaTesting;
  47271. };
  47272. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  47273. if (this._options.uniforms.indexOf(uniformName) === -1) {
  47274. this._options.uniforms.push(uniformName);
  47275. }
  47276. };
  47277. ShaderMaterial.prototype.setTexture = function (name, texture) {
  47278. if (this._options.samplers.indexOf(name) === -1) {
  47279. this._options.samplers.push(name);
  47280. }
  47281. this._textures[name] = texture;
  47282. return this;
  47283. };
  47284. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  47285. if (this._options.samplers.indexOf(name) === -1) {
  47286. this._options.samplers.push(name);
  47287. }
  47288. this._checkUniform(name);
  47289. this._textureArrays[name] = textures;
  47290. return this;
  47291. };
  47292. ShaderMaterial.prototype.setFloat = function (name, value) {
  47293. this._checkUniform(name);
  47294. this._floats[name] = value;
  47295. return this;
  47296. };
  47297. ShaderMaterial.prototype.setFloats = function (name, value) {
  47298. this._checkUniform(name);
  47299. this._floatsArrays[name] = value;
  47300. return this;
  47301. };
  47302. ShaderMaterial.prototype.setColor3 = function (name, value) {
  47303. this._checkUniform(name);
  47304. this._colors3[name] = value;
  47305. return this;
  47306. };
  47307. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  47308. this._checkUniform(name);
  47309. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  47310. color.toArray(arr, arr.length);
  47311. return arr;
  47312. }, []);
  47313. return this;
  47314. };
  47315. ShaderMaterial.prototype.setColor4 = function (name, value) {
  47316. this._checkUniform(name);
  47317. this._colors4[name] = value;
  47318. return this;
  47319. };
  47320. ShaderMaterial.prototype.setVector2 = function (name, value) {
  47321. this._checkUniform(name);
  47322. this._vectors2[name] = value;
  47323. return this;
  47324. };
  47325. ShaderMaterial.prototype.setVector3 = function (name, value) {
  47326. this._checkUniform(name);
  47327. this._vectors3[name] = value;
  47328. return this;
  47329. };
  47330. ShaderMaterial.prototype.setVector4 = function (name, value) {
  47331. this._checkUniform(name);
  47332. this._vectors4[name] = value;
  47333. return this;
  47334. };
  47335. ShaderMaterial.prototype.setMatrix = function (name, value) {
  47336. this._checkUniform(name);
  47337. this._matrices[name] = value;
  47338. return this;
  47339. };
  47340. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  47341. this._checkUniform(name);
  47342. this._matrices3x3[name] = value;
  47343. return this;
  47344. };
  47345. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  47346. this._checkUniform(name);
  47347. this._matrices2x2[name] = value;
  47348. return this;
  47349. };
  47350. ShaderMaterial.prototype.setArray2 = function (name, value) {
  47351. this._checkUniform(name);
  47352. this._vectors2Arrays[name] = value;
  47353. return this;
  47354. };
  47355. ShaderMaterial.prototype.setArray3 = function (name, value) {
  47356. this._checkUniform(name);
  47357. this._vectors3Arrays[name] = value;
  47358. return this;
  47359. };
  47360. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  47361. if (!mesh) {
  47362. return true;
  47363. }
  47364. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  47365. return false;
  47366. }
  47367. return false;
  47368. };
  47369. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  47370. var scene = this.getScene();
  47371. var engine = scene.getEngine();
  47372. if (!this.checkReadyOnEveryCall) {
  47373. if (this._renderId === scene.getRenderId()) {
  47374. if (this._checkCache(scene, mesh, useInstances)) {
  47375. return true;
  47376. }
  47377. }
  47378. }
  47379. // Instances
  47380. var defines = [];
  47381. var attribs = [];
  47382. var fallbacks = new BABYLON.EffectFallbacks();
  47383. if (useInstances) {
  47384. defines.push("#define INSTANCES");
  47385. }
  47386. for (var index = 0; index < this._options.defines.length; index++) {
  47387. defines.push(this._options.defines[index]);
  47388. }
  47389. for (var index = 0; index < this._options.attributes.length; index++) {
  47390. attribs.push(this._options.attributes[index]);
  47391. }
  47392. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  47393. attribs.push(BABYLON.VertexBuffer.ColorKind);
  47394. defines.push("#define VERTEXCOLOR");
  47395. }
  47396. // Bones
  47397. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  47398. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47399. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47400. if (mesh.numBoneInfluencers > 4) {
  47401. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  47402. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  47403. }
  47404. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47405. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47406. fallbacks.addCPUSkinningFallback(0, mesh);
  47407. if (this._options.uniforms.indexOf("mBones") === -1) {
  47408. this._options.uniforms.push("mBones");
  47409. }
  47410. }
  47411. else {
  47412. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47413. }
  47414. // Textures
  47415. for (var name in this._textures) {
  47416. if (!this._textures[name].isReady()) {
  47417. return false;
  47418. }
  47419. }
  47420. // Alpha test
  47421. if (engine.getAlphaTesting()) {
  47422. defines.push("#define ALPHATEST");
  47423. }
  47424. var previousEffect = this._effect;
  47425. var join = defines.join("\n");
  47426. this._effect = engine.createEffect(this._shaderPath, {
  47427. attributes: attribs,
  47428. uniformsNames: this._options.uniforms,
  47429. uniformBuffersNames: this._options.uniformBuffers,
  47430. samplers: this._options.samplers,
  47431. defines: join,
  47432. fallbacks: fallbacks,
  47433. onCompiled: this.onCompiled,
  47434. onError: this.onError
  47435. }, engine);
  47436. if (!this._effect.isReady()) {
  47437. return false;
  47438. }
  47439. if (previousEffect !== this._effect) {
  47440. scene.resetCachedMaterial();
  47441. }
  47442. this._renderId = scene.getRenderId();
  47443. return true;
  47444. };
  47445. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  47446. var scene = this.getScene();
  47447. if (!this._effect) {
  47448. return;
  47449. }
  47450. if (this._options.uniforms.indexOf("world") !== -1) {
  47451. this._effect.setMatrix("world", world);
  47452. }
  47453. if (this._options.uniforms.indexOf("worldView") !== -1) {
  47454. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  47455. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  47456. }
  47457. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  47458. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  47459. }
  47460. };
  47461. ShaderMaterial.prototype.bind = function (world, mesh) {
  47462. // Std values
  47463. this.bindOnlyWorldMatrix(world);
  47464. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  47465. if (this._options.uniforms.indexOf("view") !== -1) {
  47466. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  47467. }
  47468. if (this._options.uniforms.indexOf("projection") !== -1) {
  47469. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  47470. }
  47471. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  47472. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  47473. }
  47474. // Bones
  47475. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  47476. var name;
  47477. // Texture
  47478. for (name in this._textures) {
  47479. this._effect.setTexture(name, this._textures[name]);
  47480. }
  47481. // Texture arrays
  47482. for (name in this._textureArrays) {
  47483. this._effect.setTextureArray(name, this._textureArrays[name]);
  47484. }
  47485. // Float
  47486. for (name in this._floats) {
  47487. this._effect.setFloat(name, this._floats[name]);
  47488. }
  47489. // Float s
  47490. for (name in this._floatsArrays) {
  47491. this._effect.setArray(name, this._floatsArrays[name]);
  47492. }
  47493. // Color3
  47494. for (name in this._colors3) {
  47495. this._effect.setColor3(name, this._colors3[name]);
  47496. }
  47497. for (name in this._colors3Arrays) {
  47498. this._effect.setArray3(name, this._colors3Arrays[name]);
  47499. }
  47500. // Color4
  47501. for (name in this._colors4) {
  47502. var color = this._colors4[name];
  47503. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  47504. }
  47505. // Vector2
  47506. for (name in this._vectors2) {
  47507. this._effect.setVector2(name, this._vectors2[name]);
  47508. }
  47509. // Vector3
  47510. for (name in this._vectors3) {
  47511. this._effect.setVector3(name, this._vectors3[name]);
  47512. }
  47513. // Vector4
  47514. for (name in this._vectors4) {
  47515. this._effect.setVector4(name, this._vectors4[name]);
  47516. }
  47517. // Matrix
  47518. for (name in this._matrices) {
  47519. this._effect.setMatrix(name, this._matrices[name]);
  47520. }
  47521. // Matrix 3x3
  47522. for (name in this._matrices3x3) {
  47523. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  47524. }
  47525. // Matrix 2x2
  47526. for (name in this._matrices2x2) {
  47527. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  47528. }
  47529. // Vector2Array
  47530. for (name in this._vectors2Arrays) {
  47531. this._effect.setArray2(name, this._vectors2Arrays[name]);
  47532. }
  47533. // Vector3Array
  47534. for (name in this._vectors3Arrays) {
  47535. this._effect.setArray3(name, this._vectors3Arrays[name]);
  47536. }
  47537. }
  47538. this._afterBind(mesh);
  47539. };
  47540. ShaderMaterial.prototype.getActiveTextures = function () {
  47541. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47542. for (var name in this._textures) {
  47543. activeTextures.push(this._textures[name]);
  47544. }
  47545. for (var name in this._textureArrays) {
  47546. var array = this._textureArrays[name];
  47547. for (var index = 0; index < array.length; index++) {
  47548. activeTextures.push(array[index]);
  47549. }
  47550. }
  47551. return activeTextures;
  47552. };
  47553. ShaderMaterial.prototype.hasTexture = function (texture) {
  47554. if (_super.prototype.hasTexture.call(this, texture)) {
  47555. return true;
  47556. }
  47557. for (var name in this._textures) {
  47558. if (this._textures[name] === texture) {
  47559. return true;
  47560. }
  47561. }
  47562. for (var name in this._textureArrays) {
  47563. var array = this._textureArrays[name];
  47564. for (var index = 0; index < array.length; index++) {
  47565. if (array[index] === texture) {
  47566. return true;
  47567. }
  47568. }
  47569. }
  47570. return false;
  47571. };
  47572. ShaderMaterial.prototype.clone = function (name) {
  47573. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  47574. return newShaderMaterial;
  47575. };
  47576. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  47577. if (forceDisposeTextures) {
  47578. var name;
  47579. for (name in this._textures) {
  47580. this._textures[name].dispose();
  47581. }
  47582. for (name in this._textureArrays) {
  47583. var array = this._textureArrays[name];
  47584. for (var index = 0; index < array.length; index++) {
  47585. array[index].dispose();
  47586. }
  47587. }
  47588. }
  47589. this._textures = {};
  47590. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  47591. };
  47592. ShaderMaterial.prototype.serialize = function () {
  47593. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47594. serializationObject.customType = "BABYLON.ShaderMaterial";
  47595. serializationObject.options = this._options;
  47596. serializationObject.shaderPath = this._shaderPath;
  47597. var name;
  47598. // Texture
  47599. serializationObject.textures = {};
  47600. for (name in this._textures) {
  47601. serializationObject.textures[name] = this._textures[name].serialize();
  47602. }
  47603. // Texture arrays
  47604. serializationObject.textureArrays = {};
  47605. for (name in this._textureArrays) {
  47606. serializationObject.textureArrays[name] = [];
  47607. var array = this._textureArrays[name];
  47608. for (var index = 0; index < array.length; index++) {
  47609. serializationObject.textureArrays[name].push(array[index].serialize());
  47610. }
  47611. }
  47612. // Float
  47613. serializationObject.floats = {};
  47614. for (name in this._floats) {
  47615. serializationObject.floats[name] = this._floats[name];
  47616. }
  47617. // Float s
  47618. serializationObject.FloatArrays = {};
  47619. for (name in this._floatsArrays) {
  47620. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  47621. }
  47622. // Color3
  47623. serializationObject.colors3 = {};
  47624. for (name in this._colors3) {
  47625. serializationObject.colors3[name] = this._colors3[name].asArray();
  47626. }
  47627. // Color3 array
  47628. serializationObject.colors3Arrays = {};
  47629. for (name in this._colors3Arrays) {
  47630. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  47631. }
  47632. // Color4
  47633. serializationObject.colors4 = {};
  47634. for (name in this._colors4) {
  47635. serializationObject.colors4[name] = this._colors4[name].asArray();
  47636. }
  47637. // Vector2
  47638. serializationObject.vectors2 = {};
  47639. for (name in this._vectors2) {
  47640. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  47641. }
  47642. // Vector3
  47643. serializationObject.vectors3 = {};
  47644. for (name in this._vectors3) {
  47645. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  47646. }
  47647. // Vector4
  47648. serializationObject.vectors4 = {};
  47649. for (name in this._vectors4) {
  47650. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  47651. }
  47652. // Matrix
  47653. serializationObject.matrices = {};
  47654. for (name in this._matrices) {
  47655. serializationObject.matrices[name] = this._matrices[name].asArray();
  47656. }
  47657. // Matrix 3x3
  47658. serializationObject.matrices3x3 = {};
  47659. for (name in this._matrices3x3) {
  47660. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  47661. }
  47662. // Matrix 2x2
  47663. serializationObject.matrices2x2 = {};
  47664. for (name in this._matrices2x2) {
  47665. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  47666. }
  47667. // Vector2Array
  47668. serializationObject.vectors2Arrays = {};
  47669. for (name in this._vectors2Arrays) {
  47670. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  47671. }
  47672. // Vector3Array
  47673. serializationObject.vectors3Arrays = {};
  47674. for (name in this._vectors3Arrays) {
  47675. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  47676. }
  47677. return serializationObject;
  47678. };
  47679. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  47680. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  47681. var name;
  47682. // Texture
  47683. for (name in source.textures) {
  47684. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  47685. }
  47686. // Texture arrays
  47687. for (name in source.textureArrays) {
  47688. var array = source.textureArrays[name];
  47689. var textureArray = new Array();
  47690. for (var index = 0; index < array.length; index++) {
  47691. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  47692. }
  47693. material.setTextureArray(name, textureArray);
  47694. }
  47695. // Float
  47696. for (name in source.floats) {
  47697. material.setFloat(name, source.floats[name]);
  47698. }
  47699. // Float s
  47700. for (name in source.floatsArrays) {
  47701. material.setFloats(name, source.floatsArrays[name]);
  47702. }
  47703. // Color3
  47704. for (name in source.colors3) {
  47705. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  47706. }
  47707. // Color3 arrays
  47708. for (name in source.colors3Arrays) {
  47709. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  47710. if (i % 3 === 0) {
  47711. arr.push([num]);
  47712. }
  47713. else {
  47714. arr[arr.length - 1].push(num);
  47715. }
  47716. return arr;
  47717. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  47718. material.setColor3Array(name, colors);
  47719. }
  47720. // Color4
  47721. for (name in source.colors4) {
  47722. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  47723. }
  47724. // Vector2
  47725. for (name in source.vectors2) {
  47726. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  47727. }
  47728. // Vector3
  47729. for (name in source.vectors3) {
  47730. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  47731. }
  47732. // Vector4
  47733. for (name in source.vectors4) {
  47734. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  47735. }
  47736. // Matrix
  47737. for (name in source.matrices) {
  47738. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  47739. }
  47740. // Matrix 3x3
  47741. for (name in source.matrices3x3) {
  47742. material.setMatrix3x3(name, source.matrices3x3[name]);
  47743. }
  47744. // Matrix 2x2
  47745. for (name in source.matrices2x2) {
  47746. material.setMatrix2x2(name, source.matrices2x2[name]);
  47747. }
  47748. // Vector2Array
  47749. for (name in source.vectors2Arrays) {
  47750. material.setArray2(name, source.vectors2Arrays[name]);
  47751. }
  47752. // Vector3Array
  47753. for (name in source.vectors3Arrays) {
  47754. material.setArray3(name, source.vectors3Arrays[name]);
  47755. }
  47756. return material;
  47757. };
  47758. return ShaderMaterial;
  47759. }(BABYLON.Material));
  47760. BABYLON.ShaderMaterial = ShaderMaterial;
  47761. })(BABYLON || (BABYLON = {}));
  47762. //# sourceMappingURL=babylon.shaderMaterial.js.map
  47763. var BABYLON;
  47764. (function (BABYLON) {
  47765. var MeshBuilder = /** @class */ (function () {
  47766. function MeshBuilder() {
  47767. }
  47768. MeshBuilder.updateSideOrientation = function (orientation) {
  47769. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  47770. return BABYLON.Mesh.DOUBLESIDE;
  47771. }
  47772. if (orientation === undefined || orientation === null) {
  47773. return BABYLON.Mesh.FRONTSIDE;
  47774. }
  47775. return orientation;
  47776. };
  47777. /**
  47778. * Creates a box mesh.
  47779. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  47780. * The parameter `size` sets the size (float) of each box side (default 1).
  47781. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  47782. * 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).
  47783. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  47784. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47785. * 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).
  47786. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47787. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47788. */
  47789. MeshBuilder.CreateBox = function (name, options, scene) {
  47790. if (scene === void 0) { scene = null; }
  47791. var box = new BABYLON.Mesh(name, scene);
  47792. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47793. box._originalBuilderSideOrientation = options.sideOrientation;
  47794. var vertexData = BABYLON.VertexData.CreateBox(options);
  47795. vertexData.applyToMesh(box, options.updatable);
  47796. return box;
  47797. };
  47798. /**
  47799. * Creates a sphere mesh.
  47800. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  47801. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  47802. * 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`).
  47803. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  47804. * 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
  47805. * 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).
  47806. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47807. * 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).
  47808. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47809. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47810. */
  47811. MeshBuilder.CreateSphere = function (name, options, scene) {
  47812. var sphere = new BABYLON.Mesh(name, scene);
  47813. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47814. sphere._originalBuilderSideOrientation = options.sideOrientation;
  47815. var vertexData = BABYLON.VertexData.CreateSphere(options);
  47816. vertexData.applyToMesh(sphere, options.updatable);
  47817. return sphere;
  47818. };
  47819. /**
  47820. * Creates a plane polygonal mesh. By default, this is a disc.
  47821. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  47822. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  47823. * 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.
  47824. * 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
  47825. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47826. * 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).
  47827. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47828. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47829. */
  47830. MeshBuilder.CreateDisc = function (name, options, scene) {
  47831. if (scene === void 0) { scene = null; }
  47832. var disc = new BABYLON.Mesh(name, scene);
  47833. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47834. disc._originalBuilderSideOrientation = options.sideOrientation;
  47835. var vertexData = BABYLON.VertexData.CreateDisc(options);
  47836. vertexData.applyToMesh(disc, options.updatable);
  47837. return disc;
  47838. };
  47839. /**
  47840. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  47841. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  47842. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  47843. * 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`).
  47844. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  47845. * 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.
  47846. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47847. * 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).
  47848. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47849. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47850. */
  47851. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  47852. var sphere = new BABYLON.Mesh(name, scene);
  47853. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47854. sphere._originalBuilderSideOrientation = options.sideOrientation;
  47855. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  47856. vertexData.applyToMesh(sphere, options.updatable);
  47857. return sphere;
  47858. };
  47859. ;
  47860. /**
  47861. * Creates a ribbon mesh.
  47862. * 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.
  47863. *
  47864. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  47865. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  47866. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  47867. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  47868. * 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.
  47869. * 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.
  47870. * 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
  47871. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47872. * 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).
  47873. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47874. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47875. * 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.
  47876. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  47877. * 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
  47878. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  47879. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  47880. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47881. */
  47882. MeshBuilder.CreateRibbon = function (name, options, scene) {
  47883. if (scene === void 0) { scene = null; }
  47884. var pathArray = options.pathArray;
  47885. var closeArray = options.closeArray;
  47886. var closePath = options.closePath;
  47887. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47888. var instance = options.instance;
  47889. var updatable = options.updatable;
  47890. if (instance) {
  47891. // positionFunction : ribbon case
  47892. // only pathArray and sideOrientation parameters are taken into account for positions update
  47893. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  47894. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  47895. var positionFunction = function (positions) {
  47896. var minlg = pathArray[0].length;
  47897. var i = 0;
  47898. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  47899. for (var si = 1; si <= ns; si++) {
  47900. for (var p = 0; p < pathArray.length; p++) {
  47901. var path = pathArray[p];
  47902. var l = path.length;
  47903. minlg = (minlg < l) ? minlg : l;
  47904. var j = 0;
  47905. while (j < minlg) {
  47906. positions[i] = path[j].x;
  47907. positions[i + 1] = path[j].y;
  47908. positions[i + 2] = path[j].z;
  47909. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  47910. BABYLON.Tmp.Vector3[0].x = path[j].x;
  47911. }
  47912. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  47913. BABYLON.Tmp.Vector3[1].x = path[j].x;
  47914. }
  47915. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  47916. BABYLON.Tmp.Vector3[0].y = path[j].y;
  47917. }
  47918. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  47919. BABYLON.Tmp.Vector3[1].y = path[j].y;
  47920. }
  47921. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  47922. BABYLON.Tmp.Vector3[0].z = path[j].z;
  47923. }
  47924. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  47925. BABYLON.Tmp.Vector3[1].z = path[j].z;
  47926. }
  47927. j++;
  47928. i += 3;
  47929. }
  47930. if (instance._closePath) {
  47931. positions[i] = path[0].x;
  47932. positions[i + 1] = path[0].y;
  47933. positions[i + 2] = path[0].z;
  47934. i += 3;
  47935. }
  47936. }
  47937. }
  47938. };
  47939. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47940. positionFunction(positions);
  47941. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  47942. instance._boundingInfo.update(instance._worldMatrix);
  47943. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  47944. if (options.colors) {
  47945. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47946. for (var c = 0; c < options.colors.length; c++) {
  47947. colors[c * 4] = options.colors[c].r;
  47948. colors[c * 4 + 1] = options.colors[c].g;
  47949. colors[c * 4 + 2] = options.colors[c].b;
  47950. colors[c * 4 + 3] = options.colors[c].a;
  47951. }
  47952. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  47953. }
  47954. if (options.uvs) {
  47955. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47956. for (var i = 0; i < options.uvs.length; i++) {
  47957. uvs[i * 2] = options.uvs[i].x;
  47958. uvs[i * 2 + 1] = options.uvs[i].y;
  47959. }
  47960. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  47961. }
  47962. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  47963. var indices = instance.getIndices();
  47964. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47965. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  47966. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  47967. if (instance._closePath) {
  47968. var indexFirst = 0;
  47969. var indexLast = 0;
  47970. for (var p = 0; p < pathArray.length; p++) {
  47971. indexFirst = instance._idx[p] * 3;
  47972. if (p + 1 < pathArray.length) {
  47973. indexLast = (instance._idx[p + 1] - 1) * 3;
  47974. }
  47975. else {
  47976. indexLast = normals.length - 3;
  47977. }
  47978. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  47979. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  47980. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  47981. normals[indexLast] = normals[indexFirst];
  47982. normals[indexLast + 1] = normals[indexFirst + 1];
  47983. normals[indexLast + 2] = normals[indexFirst + 2];
  47984. }
  47985. }
  47986. if (!(instance.areNormalsFrozen)) {
  47987. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  47988. }
  47989. }
  47990. return instance;
  47991. }
  47992. else {
  47993. var ribbon = new BABYLON.Mesh(name, scene);
  47994. ribbon._originalBuilderSideOrientation = sideOrientation;
  47995. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  47996. if (closePath) {
  47997. ribbon._idx = vertexData._idx;
  47998. }
  47999. ribbon._closePath = closePath;
  48000. ribbon._closeArray = closeArray;
  48001. vertexData.applyToMesh(ribbon, updatable);
  48002. return ribbon;
  48003. }
  48004. };
  48005. /**
  48006. * Creates a cylinder or a cone mesh.
  48007. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  48008. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  48009. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  48010. * 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.
  48011. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  48012. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  48013. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  48014. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  48015. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  48016. * 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).
  48017. * 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
  48018. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  48019. * 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
  48020. * 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.
  48021. * If `enclose` is false, a ring surface is one element.
  48022. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  48023. * 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
  48024. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48025. * 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).
  48026. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48027. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48028. */
  48029. MeshBuilder.CreateCylinder = function (name, options, scene) {
  48030. var cylinder = new BABYLON.Mesh(name, scene);
  48031. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48032. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  48033. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  48034. vertexData.applyToMesh(cylinder, options.updatable);
  48035. return cylinder;
  48036. };
  48037. /**
  48038. * Creates a torus mesh.
  48039. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  48040. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  48041. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  48042. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  48043. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48044. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  48045. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48046. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48047. */
  48048. MeshBuilder.CreateTorus = function (name, options, scene) {
  48049. var torus = new BABYLON.Mesh(name, scene);
  48050. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48051. torus._originalBuilderSideOrientation = options.sideOrientation;
  48052. var vertexData = BABYLON.VertexData.CreateTorus(options);
  48053. vertexData.applyToMesh(torus, options.updatable);
  48054. return torus;
  48055. };
  48056. /**
  48057. * Creates a torus knot mesh.
  48058. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  48059. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  48060. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  48061. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  48062. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  48063. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48064. * 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).
  48065. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48066. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48067. */
  48068. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  48069. var torusKnot = new BABYLON.Mesh(name, scene);
  48070. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48071. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  48072. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  48073. vertexData.applyToMesh(torusKnot, options.updatable);
  48074. return torusKnot;
  48075. };
  48076. /**
  48077. * Creates a line system mesh.
  48078. * A line system is a pool of many lines gathered in a single mesh.
  48079. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  48080. * 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.
  48081. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  48082. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  48083. * 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
  48084. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  48085. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  48086. * 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
  48087. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  48088. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48089. */
  48090. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  48091. var instance = options.instance;
  48092. var lines = options.lines;
  48093. var colors = options.colors;
  48094. if (instance) {
  48095. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48096. var vertexColor;
  48097. var lineColors;
  48098. if (colors) {
  48099. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  48100. }
  48101. var i = 0;
  48102. var c = 0;
  48103. for (var l = 0; l < lines.length; l++) {
  48104. var points = lines[l];
  48105. for (var p = 0; p < points.length; p++) {
  48106. positions[i] = points[p].x;
  48107. positions[i + 1] = points[p].y;
  48108. positions[i + 2] = points[p].z;
  48109. if (colors && vertexColor) {
  48110. lineColors = colors[l];
  48111. vertexColor[c] = lineColors[p].r;
  48112. vertexColor[c + 1] = lineColors[p].g;
  48113. vertexColor[c + 2] = lineColors[p].b;
  48114. vertexColor[c + 3] = lineColors[p].a;
  48115. c += 4;
  48116. }
  48117. i += 3;
  48118. }
  48119. }
  48120. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  48121. if (colors && vertexColor) {
  48122. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  48123. }
  48124. return instance;
  48125. }
  48126. // line system creation
  48127. var useVertexColor = (colors) ? true : false;
  48128. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  48129. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  48130. vertexData.applyToMesh(lineSystem, options.updatable);
  48131. return lineSystem;
  48132. };
  48133. /**
  48134. * Creates a line mesh.
  48135. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  48136. * 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.
  48137. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  48138. * The parameter `points` is an array successive Vector3.
  48139. * 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
  48140. * The optional parameter `colors` is an array of successive Color4, one per line point.
  48141. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  48142. * When updating an instance, remember that only point positions can change, not the number of points.
  48143. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48144. */
  48145. MeshBuilder.CreateLines = function (name, options, scene) {
  48146. if (scene === void 0) { scene = null; }
  48147. var colors = (options.colors) ? [options.colors] : null;
  48148. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  48149. return lines;
  48150. };
  48151. /**
  48152. * Creates a dashed line mesh.
  48153. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  48154. * 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.
  48155. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  48156. * The parameter `points` is an array successive Vector3.
  48157. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  48158. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  48159. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  48160. * 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
  48161. * When updating an instance, remember that only point positions can change, not the number of points.
  48162. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48163. */
  48164. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  48165. if (scene === void 0) { scene = null; }
  48166. var points = options.points;
  48167. var instance = options.instance;
  48168. var gapSize = options.gapSize || 1;
  48169. var dashSize = options.dashSize || 3;
  48170. if (instance) {
  48171. var positionFunction = function (positions) {
  48172. var curvect = BABYLON.Vector3.Zero();
  48173. var nbSeg = positions.length / 6;
  48174. var lg = 0;
  48175. var nb = 0;
  48176. var shft = 0;
  48177. var dashshft = 0;
  48178. var curshft = 0;
  48179. var p = 0;
  48180. var i = 0;
  48181. var j = 0;
  48182. for (i = 0; i < points.length - 1; i++) {
  48183. points[i + 1].subtractToRef(points[i], curvect);
  48184. lg += curvect.length();
  48185. }
  48186. shft = lg / nbSeg;
  48187. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  48188. for (i = 0; i < points.length - 1; i++) {
  48189. points[i + 1].subtractToRef(points[i], curvect);
  48190. nb = Math.floor(curvect.length() / shft);
  48191. curvect.normalize();
  48192. j = 0;
  48193. while (j < nb && p < positions.length) {
  48194. curshft = shft * j;
  48195. positions[p] = points[i].x + curshft * curvect.x;
  48196. positions[p + 1] = points[i].y + curshft * curvect.y;
  48197. positions[p + 2] = points[i].z + curshft * curvect.z;
  48198. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  48199. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  48200. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  48201. p += 6;
  48202. j++;
  48203. }
  48204. }
  48205. while (p < positions.length) {
  48206. positions[p] = points[i].x;
  48207. positions[p + 1] = points[i].y;
  48208. positions[p + 2] = points[i].z;
  48209. p += 3;
  48210. }
  48211. };
  48212. instance.updateMeshPositions(positionFunction, false);
  48213. return instance;
  48214. }
  48215. // dashed lines creation
  48216. var dashedLines = new BABYLON.LinesMesh(name, scene);
  48217. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  48218. vertexData.applyToMesh(dashedLines, options.updatable);
  48219. dashedLines.dashSize = dashSize;
  48220. dashedLines.gapSize = gapSize;
  48221. return dashedLines;
  48222. };
  48223. /**
  48224. * Creates an extruded shape mesh.
  48225. * 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.
  48226. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  48227. *
  48228. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  48229. * 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
  48230. * extruded along the Z axis.
  48231. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  48232. * 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.
  48233. * The parameter `scale` (float, default 1) is the value to scale the shape.
  48234. * 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
  48235. * 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
  48236. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  48237. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48238. * 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).
  48239. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48240. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  48241. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48242. */
  48243. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  48244. if (scene === void 0) { scene = null; }
  48245. var path = options.path;
  48246. var shape = options.shape;
  48247. var scale = options.scale || 1;
  48248. var rotation = options.rotation || 0;
  48249. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  48250. var updatable = options.updatable;
  48251. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48252. var instance = options.instance || null;
  48253. var invertUV = options.invertUV || false;
  48254. 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);
  48255. };
  48256. /**
  48257. * Creates an custom extruded shape mesh.
  48258. * 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.
  48259. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  48260. *
  48261. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  48262. * 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
  48263. * extruded along the Z axis.
  48264. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  48265. * 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
  48266. * and the distance of this point from the begining of the path :
  48267. * ```javascript
  48268. * var rotationFunction = function(i, distance) {
  48269. * // do things
  48270. * return rotationValue; }
  48271. * ```
  48272. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  48273. * 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
  48274. * and the distance of this point from the begining of the path :
  48275. * ```javascript
  48276. * var scaleFunction = function(i, distance) {
  48277. * // do things
  48278. * return scaleValue;}
  48279. * ```
  48280. * It must returns a float value that will be the scale value applied to the shape on each path point.
  48281. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  48282. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  48283. * 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
  48284. * 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
  48285. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  48286. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48287. * 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).
  48288. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48289. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  48290. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48291. */
  48292. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  48293. var path = options.path;
  48294. var shape = options.shape;
  48295. var scaleFunction = options.scaleFunction || (function () { return 1; });
  48296. var rotationFunction = options.rotationFunction || (function () { return 0; });
  48297. var ribbonCloseArray = options.ribbonCloseArray || false;
  48298. var ribbonClosePath = options.ribbonClosePath || false;
  48299. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  48300. var updatable = options.updatable;
  48301. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48302. var instance = options.instance;
  48303. var invertUV = options.invertUV || false;
  48304. 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);
  48305. };
  48306. /**
  48307. * Creates lathe mesh.
  48308. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  48309. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  48310. *
  48311. * 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
  48312. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  48313. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  48314. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  48315. * 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.
  48316. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  48317. * 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
  48318. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48319. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  48320. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48321. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  48322. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48323. */
  48324. MeshBuilder.CreateLathe = function (name, options, scene) {
  48325. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  48326. var closed = (options.closed === undefined) ? true : options.closed;
  48327. var shape = options.shape;
  48328. var radius = options.radius || 1;
  48329. var tessellation = options.tessellation || 64;
  48330. var updatable = options.updatable;
  48331. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48332. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  48333. var pi2 = Math.PI * 2;
  48334. var paths = new Array();
  48335. var invertUV = options.invertUV || false;
  48336. var i = 0;
  48337. var p = 0;
  48338. var step = pi2 / tessellation * arc;
  48339. var rotated;
  48340. var path = new Array();
  48341. ;
  48342. for (i = 0; i <= tessellation; i++) {
  48343. var path = [];
  48344. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  48345. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  48346. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  48347. }
  48348. for (p = 0; p < shape.length; p++) {
  48349. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  48350. path.push(rotated);
  48351. }
  48352. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  48353. 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));
  48354. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  48355. }
  48356. paths.push(path);
  48357. }
  48358. // lathe ribbon
  48359. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  48360. return lathe;
  48361. };
  48362. /**
  48363. * Creates a plane mesh.
  48364. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  48365. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  48366. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  48367. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  48368. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48369. * 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).
  48370. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48371. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48372. */
  48373. MeshBuilder.CreatePlane = function (name, options, scene) {
  48374. var plane = new BABYLON.Mesh(name, scene);
  48375. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48376. plane._originalBuilderSideOrientation = options.sideOrientation;
  48377. var vertexData = BABYLON.VertexData.CreatePlane(options);
  48378. vertexData.applyToMesh(plane, options.updatable);
  48379. if (options.sourcePlane) {
  48380. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  48381. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  48382. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  48383. plane.rotate(vectorProduct, product);
  48384. }
  48385. return plane;
  48386. };
  48387. /**
  48388. * Creates a ground mesh.
  48389. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  48390. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  48391. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  48392. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48393. */
  48394. MeshBuilder.CreateGround = function (name, options, scene) {
  48395. var ground = new BABYLON.GroundMesh(name, scene);
  48396. ground._setReady(false);
  48397. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  48398. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  48399. ground._width = options.width || 1;
  48400. ground._height = options.height || 1;
  48401. ground._maxX = ground._width / 2;
  48402. ground._maxZ = ground._height / 2;
  48403. ground._minX = -ground._maxX;
  48404. ground._minZ = -ground._maxZ;
  48405. var vertexData = BABYLON.VertexData.CreateGround(options);
  48406. vertexData.applyToMesh(ground, options.updatable);
  48407. ground._setReady(true);
  48408. return ground;
  48409. };
  48410. /**
  48411. * Creates a tiled ground mesh.
  48412. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  48413. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  48414. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  48415. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  48416. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  48417. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  48418. * numbers of subdivisions on the ground width and height of each tile.
  48419. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48420. */
  48421. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  48422. var tiledGround = new BABYLON.Mesh(name, scene);
  48423. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  48424. vertexData.applyToMesh(tiledGround, options.updatable);
  48425. return tiledGround;
  48426. };
  48427. /**
  48428. * Creates a ground mesh from a height map.
  48429. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  48430. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  48431. * The parameter `url` sets the URL of the height map image resource.
  48432. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  48433. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  48434. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  48435. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  48436. * 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.
  48437. * 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).
  48438. * This function is passed the newly built mesh :
  48439. * ```javascript
  48440. * function(mesh) { // do things
  48441. * return; }
  48442. * ```
  48443. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48444. */
  48445. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  48446. var width = options.width || 10.0;
  48447. var height = options.height || 10.0;
  48448. var subdivisions = options.subdivisions || 1 | 0;
  48449. var minHeight = options.minHeight || 0.0;
  48450. var maxHeight = options.maxHeight || 1.0;
  48451. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  48452. var updatable = options.updatable;
  48453. var onReady = options.onReady;
  48454. var ground = new BABYLON.GroundMesh(name, scene);
  48455. ground._subdivisionsX = subdivisions;
  48456. ground._subdivisionsY = subdivisions;
  48457. ground._width = width;
  48458. ground._height = height;
  48459. ground._maxX = ground._width / 2.0;
  48460. ground._maxZ = ground._height / 2.0;
  48461. ground._minX = -ground._maxX;
  48462. ground._minZ = -ground._maxZ;
  48463. ground._setReady(false);
  48464. var onload = function (img) {
  48465. // Getting height map data
  48466. var canvas = document.createElement("canvas");
  48467. var context = canvas.getContext("2d");
  48468. if (!context) {
  48469. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  48470. }
  48471. var bufferWidth = img.width;
  48472. var bufferHeight = img.height;
  48473. canvas.width = bufferWidth;
  48474. canvas.height = bufferHeight;
  48475. context.drawImage(img, 0, 0);
  48476. // Create VertexData from map data
  48477. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  48478. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  48479. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  48480. width: width, height: height,
  48481. subdivisions: subdivisions,
  48482. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  48483. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  48484. });
  48485. vertexData.applyToMesh(ground, updatable);
  48486. ground._setReady(true);
  48487. //execute ready callback, if set
  48488. if (onReady) {
  48489. onReady(ground);
  48490. }
  48491. };
  48492. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  48493. return ground;
  48494. };
  48495. /**
  48496. * Creates a polygon mesh.
  48497. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  48498. * 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.
  48499. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48500. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48501. * 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).
  48502. * Remember you can only change the shape positions, not their number when updating a polygon.
  48503. */
  48504. MeshBuilder.CreatePolygon = function (name, options, scene) {
  48505. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48506. var shape = options.shape;
  48507. var holes = options.holes || [];
  48508. var depth = options.depth || 0;
  48509. var contours = [];
  48510. var hole = [];
  48511. for (var i = 0; i < shape.length; i++) {
  48512. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  48513. }
  48514. var epsilon = 0.00000001;
  48515. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  48516. contours.pop();
  48517. }
  48518. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  48519. for (var hNb = 0; hNb < holes.length; hNb++) {
  48520. hole = [];
  48521. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  48522. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  48523. }
  48524. polygonTriangulation.addHole(hole);
  48525. }
  48526. var polygon = polygonTriangulation.build(options.updatable, depth);
  48527. polygon._originalBuilderSideOrientation = options.sideOrientation;
  48528. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  48529. vertexData.applyToMesh(polygon, options.updatable);
  48530. return polygon;
  48531. };
  48532. ;
  48533. /**
  48534. * Creates an extruded polygon mesh, with depth in the Y direction.
  48535. * 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).
  48536. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  48537. */
  48538. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  48539. return MeshBuilder.CreatePolygon(name, options, scene);
  48540. };
  48541. ;
  48542. /**
  48543. * Creates a tube mesh.
  48544. * 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.
  48545. *
  48546. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  48547. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  48548. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  48549. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  48550. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  48551. * 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.
  48552. * It must return a radius value (positive float) :
  48553. * ```javascript
  48554. * var radiusFunction = function(i, distance) {
  48555. * // do things
  48556. * return radius; }
  48557. * ```
  48558. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  48559. * 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
  48560. * 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
  48561. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48562. * 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).
  48563. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48564. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  48565. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48566. */
  48567. MeshBuilder.CreateTube = function (name, options, scene) {
  48568. var path = options.path;
  48569. var instance = options.instance;
  48570. var radius = 1.0;
  48571. if (instance) {
  48572. radius = instance.radius;
  48573. }
  48574. if (options.radius !== undefined) {
  48575. radius = options.radius;
  48576. }
  48577. ;
  48578. var tessellation = options.tessellation || 64 | 0;
  48579. var radiusFunction = options.radiusFunction || null;
  48580. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  48581. var invertUV = options.invertUV || false;
  48582. var updatable = options.updatable;
  48583. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48584. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  48585. // tube geometry
  48586. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  48587. var tangents = path3D.getTangents();
  48588. var normals = path3D.getNormals();
  48589. var distances = path3D.getDistances();
  48590. var pi2 = Math.PI * 2;
  48591. var step = pi2 / tessellation * arc;
  48592. var returnRadius = function () { return radius; };
  48593. var radiusFunctionFinal = radiusFunction || returnRadius;
  48594. var circlePath;
  48595. var rad;
  48596. var normal;
  48597. var rotated;
  48598. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  48599. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  48600. for (var i = 0; i < path.length; i++) {
  48601. rad = radiusFunctionFinal(i, distances[i]); // current radius
  48602. circlePath = Array(); // current circle array
  48603. normal = normals[i]; // current normal
  48604. for (var t = 0; t < tessellation; t++) {
  48605. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  48606. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  48607. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  48608. rotated.scaleInPlace(rad).addInPlace(path[i]);
  48609. circlePath[t] = rotated;
  48610. }
  48611. circlePaths[index] = circlePath;
  48612. index++;
  48613. }
  48614. // cap
  48615. var capPath = function (nbPoints, pathIndex) {
  48616. var pointCap = Array();
  48617. for (var i = 0; i < nbPoints; i++) {
  48618. pointCap.push(path[pathIndex]);
  48619. }
  48620. return pointCap;
  48621. };
  48622. switch (cap) {
  48623. case BABYLON.Mesh.NO_CAP:
  48624. break;
  48625. case BABYLON.Mesh.CAP_START:
  48626. circlePaths[0] = capPath(tessellation, 0);
  48627. circlePaths[1] = circlePaths[2].slice(0);
  48628. break;
  48629. case BABYLON.Mesh.CAP_END:
  48630. circlePaths[index] = circlePaths[index - 1].slice(0);
  48631. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  48632. break;
  48633. case BABYLON.Mesh.CAP_ALL:
  48634. circlePaths[0] = capPath(tessellation, 0);
  48635. circlePaths[1] = circlePaths[2].slice(0);
  48636. circlePaths[index] = circlePaths[index - 1].slice(0);
  48637. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  48638. break;
  48639. default:
  48640. break;
  48641. }
  48642. return circlePaths;
  48643. };
  48644. var path3D;
  48645. var pathArray;
  48646. if (instance) {
  48647. var arc = options.arc || instance.arc;
  48648. path3D = (instance.path3D).update(path);
  48649. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  48650. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  48651. instance.path3D = path3D;
  48652. instance.pathArray = pathArray;
  48653. instance.arc = arc;
  48654. instance.radius = radius;
  48655. return instance;
  48656. }
  48657. // tube creation
  48658. path3D = new BABYLON.Path3D(path);
  48659. var newPathArray = new Array();
  48660. cap = (cap < 0 || cap > 3) ? 0 : cap;
  48661. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  48662. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  48663. tube.pathArray = pathArray;
  48664. tube.path3D = path3D;
  48665. tube.tessellation = tessellation;
  48666. tube.cap = cap;
  48667. tube.arc = options.arc;
  48668. tube.radius = radius;
  48669. return tube;
  48670. };
  48671. /**
  48672. * Creates a polyhedron mesh.
  48673. *
  48674. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  48675. * 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
  48676. * to choose the wanted type.
  48677. * The parameter `size` (positive float, default 1) sets the polygon size.
  48678. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  48679. * 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`.
  48680. * 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
  48681. * 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)`).
  48682. * 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
  48683. * 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.
  48684. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48685. * 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).
  48686. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48687. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48688. */
  48689. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  48690. var polyhedron = new BABYLON.Mesh(name, scene);
  48691. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48692. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  48693. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  48694. vertexData.applyToMesh(polyhedron, options.updatable);
  48695. return polyhedron;
  48696. };
  48697. /**
  48698. * Creates a decal mesh.
  48699. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  48700. * 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.
  48701. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  48702. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  48703. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  48704. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  48705. */
  48706. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  48707. var indices = sourceMesh.getIndices();
  48708. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48709. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  48710. var position = options.position || BABYLON.Vector3.Zero();
  48711. var normal = options.normal || BABYLON.Vector3.Up();
  48712. var size = options.size || BABYLON.Vector3.One();
  48713. var angle = options.angle || 0;
  48714. // Getting correct rotation
  48715. if (!normal) {
  48716. var target = new BABYLON.Vector3(0, 0, 1);
  48717. var camera = sourceMesh.getScene().activeCamera;
  48718. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  48719. normal = camera.globalPosition.subtract(cameraWorldTarget);
  48720. }
  48721. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  48722. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  48723. var pitch = Math.atan2(normal.y, len);
  48724. // Matrix
  48725. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  48726. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  48727. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  48728. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  48729. var vertexData = new BABYLON.VertexData();
  48730. vertexData.indices = [];
  48731. vertexData.positions = [];
  48732. vertexData.normals = [];
  48733. vertexData.uvs = [];
  48734. var currentVertexDataIndex = 0;
  48735. var extractDecalVector3 = function (indexId) {
  48736. var result = new BABYLON.PositionNormalVertex();
  48737. if (!indices || !positions || !normals) {
  48738. return result;
  48739. }
  48740. var vertexId = indices[indexId];
  48741. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  48742. // Send vector to decal local world
  48743. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  48744. // Get normal
  48745. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  48746. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  48747. return result;
  48748. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  48749. var clip = function (vertices, axis) {
  48750. if (vertices.length === 0) {
  48751. return vertices;
  48752. }
  48753. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  48754. var clipVertices = function (v0, v1) {
  48755. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  48756. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  48757. };
  48758. var result = new Array();
  48759. for (var index = 0; index < vertices.length; index += 3) {
  48760. var v1Out;
  48761. var v2Out;
  48762. var v3Out;
  48763. var total = 0;
  48764. var nV1 = null;
  48765. var nV2 = null;
  48766. var nV3 = null;
  48767. var nV4 = null;
  48768. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  48769. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  48770. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  48771. v1Out = d1 > 0;
  48772. v2Out = d2 > 0;
  48773. v3Out = d3 > 0;
  48774. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  48775. switch (total) {
  48776. case 0:
  48777. result.push(vertices[index]);
  48778. result.push(vertices[index + 1]);
  48779. result.push(vertices[index + 2]);
  48780. break;
  48781. case 1:
  48782. if (v1Out) {
  48783. nV1 = vertices[index + 1];
  48784. nV2 = vertices[index + 2];
  48785. nV3 = clipVertices(vertices[index], nV1);
  48786. nV4 = clipVertices(vertices[index], nV2);
  48787. }
  48788. if (v2Out) {
  48789. nV1 = vertices[index];
  48790. nV2 = vertices[index + 2];
  48791. nV3 = clipVertices(vertices[index + 1], nV1);
  48792. nV4 = clipVertices(vertices[index + 1], nV2);
  48793. result.push(nV3);
  48794. result.push(nV2.clone());
  48795. result.push(nV1.clone());
  48796. result.push(nV2.clone());
  48797. result.push(nV3.clone());
  48798. result.push(nV4);
  48799. break;
  48800. }
  48801. if (v3Out) {
  48802. nV1 = vertices[index];
  48803. nV2 = vertices[index + 1];
  48804. nV3 = clipVertices(vertices[index + 2], nV1);
  48805. nV4 = clipVertices(vertices[index + 2], nV2);
  48806. }
  48807. if (nV1 && nV2 && nV3 && nV4) {
  48808. result.push(nV1.clone());
  48809. result.push(nV2.clone());
  48810. result.push(nV3);
  48811. result.push(nV4);
  48812. result.push(nV3.clone());
  48813. result.push(nV2.clone());
  48814. }
  48815. break;
  48816. case 2:
  48817. if (!v1Out) {
  48818. nV1 = vertices[index].clone();
  48819. nV2 = clipVertices(nV1, vertices[index + 1]);
  48820. nV3 = clipVertices(nV1, vertices[index + 2]);
  48821. result.push(nV1);
  48822. result.push(nV2);
  48823. result.push(nV3);
  48824. }
  48825. if (!v2Out) {
  48826. nV1 = vertices[index + 1].clone();
  48827. nV2 = clipVertices(nV1, vertices[index + 2]);
  48828. nV3 = clipVertices(nV1, vertices[index]);
  48829. result.push(nV1);
  48830. result.push(nV2);
  48831. result.push(nV3);
  48832. }
  48833. if (!v3Out) {
  48834. nV1 = vertices[index + 2].clone();
  48835. nV2 = clipVertices(nV1, vertices[index]);
  48836. nV3 = clipVertices(nV1, vertices[index + 1]);
  48837. result.push(nV1);
  48838. result.push(nV2);
  48839. result.push(nV3);
  48840. }
  48841. break;
  48842. case 3:
  48843. break;
  48844. }
  48845. }
  48846. return result;
  48847. };
  48848. for (var index = 0; index < indices.length; index += 3) {
  48849. var faceVertices = new Array();
  48850. faceVertices.push(extractDecalVector3(index));
  48851. faceVertices.push(extractDecalVector3(index + 1));
  48852. faceVertices.push(extractDecalVector3(index + 2));
  48853. // Clip
  48854. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  48855. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  48856. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  48857. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  48858. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  48859. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  48860. if (faceVertices.length === 0) {
  48861. continue;
  48862. }
  48863. // Add UVs and get back to world
  48864. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  48865. var vertex = faceVertices[vIndex];
  48866. //TODO check for Int32Array | Uint32Array | Uint16Array
  48867. vertexData.indices.push(currentVertexDataIndex);
  48868. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  48869. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  48870. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  48871. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  48872. currentVertexDataIndex++;
  48873. }
  48874. }
  48875. // Return mesh
  48876. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  48877. vertexData.applyToMesh(decal);
  48878. decal.position = position.clone();
  48879. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  48880. return decal;
  48881. };
  48882. // Privates
  48883. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  48884. // extrusion geometry
  48885. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  48886. var tangents = path3D.getTangents();
  48887. var normals = path3D.getNormals();
  48888. var binormals = path3D.getBinormals();
  48889. var distances = path3D.getDistances();
  48890. var angle = 0;
  48891. var returnScale = function () { return scale !== null ? scale : 1; };
  48892. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  48893. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  48894. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  48895. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  48896. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  48897. for (var i = 0; i < curve.length; i++) {
  48898. var shapePath = new Array();
  48899. var angleStep = rotate(i, distances[i]);
  48900. var scaleRatio = scl(i, distances[i]);
  48901. for (var p = 0; p < shape.length; p++) {
  48902. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  48903. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  48904. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  48905. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  48906. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  48907. shapePath[p] = rotated;
  48908. }
  48909. shapePaths[index] = shapePath;
  48910. angle += angleStep;
  48911. index++;
  48912. }
  48913. // cap
  48914. var capPath = function (shapePath) {
  48915. var pointCap = Array();
  48916. var barycenter = BABYLON.Vector3.Zero();
  48917. var i;
  48918. for (i = 0; i < shapePath.length; i++) {
  48919. barycenter.addInPlace(shapePath[i]);
  48920. }
  48921. barycenter.scaleInPlace(1.0 / shapePath.length);
  48922. for (i = 0; i < shapePath.length; i++) {
  48923. pointCap.push(barycenter);
  48924. }
  48925. return pointCap;
  48926. };
  48927. switch (cap) {
  48928. case BABYLON.Mesh.NO_CAP:
  48929. break;
  48930. case BABYLON.Mesh.CAP_START:
  48931. shapePaths[0] = capPath(shapePaths[2]);
  48932. shapePaths[1] = shapePaths[2];
  48933. break;
  48934. case BABYLON.Mesh.CAP_END:
  48935. shapePaths[index] = shapePaths[index - 1];
  48936. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  48937. break;
  48938. case BABYLON.Mesh.CAP_ALL:
  48939. shapePaths[0] = capPath(shapePaths[2]);
  48940. shapePaths[1] = shapePaths[2];
  48941. shapePaths[index] = shapePaths[index - 1];
  48942. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  48943. break;
  48944. default:
  48945. break;
  48946. }
  48947. return shapePaths;
  48948. };
  48949. var path3D;
  48950. var pathArray;
  48951. if (instance) {
  48952. path3D = (instance.path3D).update(curve);
  48953. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  48954. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  48955. return instance;
  48956. }
  48957. // extruded shape creation
  48958. path3D = new BABYLON.Path3D(curve);
  48959. var newShapePaths = new Array();
  48960. cap = (cap < 0 || cap > 3) ? 0 : cap;
  48961. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  48962. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  48963. extrudedGeneric.pathArray = pathArray;
  48964. extrudedGeneric.path3D = path3D;
  48965. extrudedGeneric.cap = cap;
  48966. return extrudedGeneric;
  48967. };
  48968. return MeshBuilder;
  48969. }());
  48970. BABYLON.MeshBuilder = MeshBuilder;
  48971. })(BABYLON || (BABYLON = {}));
  48972. //# sourceMappingURL=babylon.meshBuilder.js.map
  48973. var BABYLON;
  48974. (function (BABYLON) {
  48975. var AudioEngine = /** @class */ (function () {
  48976. function AudioEngine() {
  48977. this._audioContext = null;
  48978. this._audioContextInitialized = false;
  48979. this.canUseWebAudio = false;
  48980. this.WarnedWebAudioUnsupported = false;
  48981. this.unlocked = false;
  48982. this.isMP3supported = false;
  48983. this.isOGGsupported = false;
  48984. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  48985. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  48986. this.canUseWebAudio = true;
  48987. }
  48988. var audioElem = document.createElement('audio');
  48989. try {
  48990. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  48991. this.isMP3supported = true;
  48992. }
  48993. }
  48994. catch (e) {
  48995. // protect error during capability check.
  48996. }
  48997. try {
  48998. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  48999. this.isOGGsupported = true;
  49000. }
  49001. }
  49002. catch (e) {
  49003. // protect error during capability check.
  49004. }
  49005. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  49006. this._unlockiOSaudio();
  49007. }
  49008. else {
  49009. this.unlocked = true;
  49010. }
  49011. }
  49012. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  49013. get: function () {
  49014. if (!this._audioContextInitialized) {
  49015. this._initializeAudioContext();
  49016. }
  49017. return this._audioContext;
  49018. },
  49019. enumerable: true,
  49020. configurable: true
  49021. });
  49022. AudioEngine.prototype._unlockiOSaudio = function () {
  49023. var _this = this;
  49024. var unlockaudio = function () {
  49025. if (!_this.audioContext) {
  49026. return;
  49027. }
  49028. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  49029. var source = _this.audioContext.createBufferSource();
  49030. source.buffer = buffer;
  49031. source.connect(_this.audioContext.destination);
  49032. source.start(0);
  49033. setTimeout(function () {
  49034. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  49035. _this.unlocked = true;
  49036. window.removeEventListener('touchend', unlockaudio, false);
  49037. if (_this.onAudioUnlocked) {
  49038. _this.onAudioUnlocked();
  49039. }
  49040. }
  49041. }, 0);
  49042. };
  49043. window.addEventListener('touchend', unlockaudio, false);
  49044. };
  49045. AudioEngine.prototype._initializeAudioContext = function () {
  49046. try {
  49047. if (this.canUseWebAudio) {
  49048. this._audioContext = new AudioContext();
  49049. // create a global volume gain node
  49050. this.masterGain = this._audioContext.createGain();
  49051. this.masterGain.gain.value = 1;
  49052. this.masterGain.connect(this._audioContext.destination);
  49053. this._audioContextInitialized = true;
  49054. }
  49055. }
  49056. catch (e) {
  49057. this.canUseWebAudio = false;
  49058. BABYLON.Tools.Error("Web Audio: " + e.message);
  49059. }
  49060. };
  49061. AudioEngine.prototype.dispose = function () {
  49062. if (this.canUseWebAudio && this._audioContextInitialized) {
  49063. if (this._connectedAnalyser && this._audioContext) {
  49064. this._connectedAnalyser.stopDebugCanvas();
  49065. this._connectedAnalyser.dispose();
  49066. this.masterGain.disconnect();
  49067. this.masterGain.connect(this._audioContext.destination);
  49068. this._connectedAnalyser = null;
  49069. }
  49070. this.masterGain.gain.value = 1;
  49071. }
  49072. this.WarnedWebAudioUnsupported = false;
  49073. };
  49074. AudioEngine.prototype.getGlobalVolume = function () {
  49075. if (this.canUseWebAudio && this._audioContextInitialized) {
  49076. return this.masterGain.gain.value;
  49077. }
  49078. else {
  49079. return -1;
  49080. }
  49081. };
  49082. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  49083. if (this.canUseWebAudio && this._audioContextInitialized) {
  49084. this.masterGain.gain.value = newVolume;
  49085. }
  49086. };
  49087. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  49088. if (this._connectedAnalyser) {
  49089. this._connectedAnalyser.stopDebugCanvas();
  49090. }
  49091. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  49092. this._connectedAnalyser = analyser;
  49093. this.masterGain.disconnect();
  49094. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  49095. }
  49096. };
  49097. return AudioEngine;
  49098. }());
  49099. BABYLON.AudioEngine = AudioEngine;
  49100. })(BABYLON || (BABYLON = {}));
  49101. //# sourceMappingURL=babylon.audioEngine.js.map
  49102. var BABYLON;
  49103. (function (BABYLON) {
  49104. var Sound = /** @class */ (function () {
  49105. /**
  49106. * Create a sound and attach it to a scene
  49107. * @param name Name of your sound
  49108. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  49109. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  49110. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  49111. */
  49112. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  49113. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  49114. var _this = this;
  49115. this.autoplay = false;
  49116. this.loop = false;
  49117. this.useCustomAttenuation = false;
  49118. this.spatialSound = false;
  49119. this.refDistance = 1;
  49120. this.rolloffFactor = 1;
  49121. this.maxDistance = 100;
  49122. this.distanceModel = "linear";
  49123. this._panningModel = "equalpower";
  49124. this._playbackRate = 1;
  49125. this._streaming = false;
  49126. this._startTime = 0;
  49127. this._startOffset = 0;
  49128. this._position = BABYLON.Vector3.Zero();
  49129. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  49130. this._volume = 1;
  49131. this._isReadyToPlay = false;
  49132. this.isPlaying = false;
  49133. this.isPaused = false;
  49134. this._isDirectional = false;
  49135. // Used if you'd like to create a directional sound.
  49136. // If not set, the sound will be omnidirectional
  49137. this._coneInnerAngle = 360;
  49138. this._coneOuterAngle = 360;
  49139. this._coneOuterGain = 0;
  49140. this._isOutputConnected = false;
  49141. this._urlType = "Unknown";
  49142. this.name = name;
  49143. this._scene = scene;
  49144. this._readyToPlayCallback = readyToPlayCallback;
  49145. // Default custom attenuation function is a linear attenuation
  49146. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  49147. if (currentDistance < maxDistance) {
  49148. return currentVolume * (1 - currentDistance / maxDistance);
  49149. }
  49150. else {
  49151. return 0;
  49152. }
  49153. };
  49154. if (options) {
  49155. this.autoplay = options.autoplay || false;
  49156. this.loop = options.loop || false;
  49157. // if volume === 0, we need another way to check this option
  49158. if (options.volume !== undefined) {
  49159. this._volume = options.volume;
  49160. }
  49161. this.spatialSound = options.spatialSound || false;
  49162. this.maxDistance = options.maxDistance || 100;
  49163. this.useCustomAttenuation = options.useCustomAttenuation || false;
  49164. this.rolloffFactor = options.rolloffFactor || 1;
  49165. this.refDistance = options.refDistance || 1;
  49166. this.distanceModel = options.distanceModel || "linear";
  49167. this._playbackRate = options.playbackRate || 1;
  49168. this._streaming = options.streaming || false;
  49169. }
  49170. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  49171. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  49172. this._soundGain.gain.value = this._volume;
  49173. this._inputAudioNode = this._soundGain;
  49174. this._ouputAudioNode = this._soundGain;
  49175. if (this.spatialSound) {
  49176. this._createSpatialParameters();
  49177. }
  49178. this._scene.mainSoundTrack.AddSound(this);
  49179. var validParameter = true;
  49180. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  49181. if (urlOrArrayBuffer) {
  49182. if (typeof (urlOrArrayBuffer) === "string")
  49183. this._urlType = "String";
  49184. if (Array.isArray(urlOrArrayBuffer))
  49185. this._urlType = "Array";
  49186. if (urlOrArrayBuffer instanceof ArrayBuffer)
  49187. this._urlType = "ArrayBuffer";
  49188. var urls = [];
  49189. var codecSupportedFound = false;
  49190. switch (this._urlType) {
  49191. case "ArrayBuffer":
  49192. if (urlOrArrayBuffer.byteLength > 0) {
  49193. codecSupportedFound = true;
  49194. this._soundLoaded(urlOrArrayBuffer);
  49195. }
  49196. break;
  49197. case "String":
  49198. urls.push(urlOrArrayBuffer);
  49199. case "Array":
  49200. if (urls.length === 0)
  49201. urls = urlOrArrayBuffer;
  49202. // If we found a supported format, we load it immediately and stop the loop
  49203. for (var i = 0; i < urls.length; i++) {
  49204. var url = urls[i];
  49205. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  49206. codecSupportedFound = true;
  49207. }
  49208. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  49209. codecSupportedFound = true;
  49210. }
  49211. if (url.indexOf(".wav", url.length - 4) !== -1) {
  49212. codecSupportedFound = true;
  49213. }
  49214. if (url.indexOf("blob:") !== -1) {
  49215. codecSupportedFound = true;
  49216. }
  49217. if (codecSupportedFound) {
  49218. // Loading sound using XHR2
  49219. if (!this._streaming) {
  49220. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, undefined, this._scene.database, true);
  49221. }
  49222. else {
  49223. this._htmlAudioElement = new Audio(url);
  49224. this._htmlAudioElement.controls = false;
  49225. this._htmlAudioElement.loop = this.loop;
  49226. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  49227. this._htmlAudioElement.preload = "auto";
  49228. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  49229. _this._isReadyToPlay = true;
  49230. if (_this.autoplay) {
  49231. _this.play();
  49232. }
  49233. if (_this._readyToPlayCallback) {
  49234. _this._readyToPlayCallback();
  49235. }
  49236. });
  49237. document.body.appendChild(this._htmlAudioElement);
  49238. }
  49239. break;
  49240. }
  49241. }
  49242. break;
  49243. default:
  49244. validParameter = false;
  49245. break;
  49246. }
  49247. if (!validParameter) {
  49248. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  49249. }
  49250. else {
  49251. if (!codecSupportedFound) {
  49252. this._isReadyToPlay = true;
  49253. // Simulating a ready to play event to avoid breaking code path
  49254. if (this._readyToPlayCallback) {
  49255. window.setTimeout(function () {
  49256. if (_this._readyToPlayCallback) {
  49257. _this._readyToPlayCallback();
  49258. }
  49259. }, 1000);
  49260. }
  49261. }
  49262. }
  49263. }
  49264. }
  49265. else {
  49266. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  49267. this._scene.mainSoundTrack.AddSound(this);
  49268. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  49269. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  49270. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  49271. }
  49272. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  49273. if (this._readyToPlayCallback) {
  49274. window.setTimeout(function () {
  49275. if (_this._readyToPlayCallback) {
  49276. _this._readyToPlayCallback();
  49277. }
  49278. }, 1000);
  49279. }
  49280. }
  49281. }
  49282. Sound.prototype.dispose = function () {
  49283. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  49284. if (this.isPlaying) {
  49285. this.stop();
  49286. }
  49287. this._isReadyToPlay = false;
  49288. if (this.soundTrackId === -1) {
  49289. this._scene.mainSoundTrack.RemoveSound(this);
  49290. }
  49291. else {
  49292. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  49293. }
  49294. if (this._soundGain) {
  49295. this._soundGain.disconnect();
  49296. this._soundGain = null;
  49297. }
  49298. if (this._soundPanner) {
  49299. this._soundPanner.disconnect();
  49300. this._soundPanner = null;
  49301. }
  49302. if (this._soundSource) {
  49303. this._soundSource.disconnect();
  49304. this._soundSource = null;
  49305. }
  49306. this._audioBuffer = null;
  49307. if (this._htmlAudioElement) {
  49308. this._htmlAudioElement.pause();
  49309. this._htmlAudioElement.src = "";
  49310. document.body.removeChild(this._htmlAudioElement);
  49311. }
  49312. if (this._connectedMesh && this._registerFunc) {
  49313. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  49314. this._connectedMesh = null;
  49315. }
  49316. }
  49317. };
  49318. Sound.prototype.isReady = function () {
  49319. return this._isReadyToPlay;
  49320. };
  49321. Sound.prototype._soundLoaded = function (audioData) {
  49322. var _this = this;
  49323. if (!BABYLON.Engine.audioEngine.audioContext) {
  49324. return;
  49325. }
  49326. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  49327. _this._audioBuffer = buffer;
  49328. _this._isReadyToPlay = true;
  49329. if (_this.autoplay) {
  49330. _this.play();
  49331. }
  49332. if (_this._readyToPlayCallback) {
  49333. _this._readyToPlayCallback();
  49334. }
  49335. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  49336. };
  49337. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  49338. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49339. this._audioBuffer = audioBuffer;
  49340. this._isReadyToPlay = true;
  49341. }
  49342. };
  49343. Sound.prototype.updateOptions = function (options) {
  49344. if (options) {
  49345. this.loop = options.loop || this.loop;
  49346. this.maxDistance = options.maxDistance || this.maxDistance;
  49347. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  49348. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  49349. this.refDistance = options.refDistance || this.refDistance;
  49350. this.distanceModel = options.distanceModel || this.distanceModel;
  49351. this._playbackRate = options.playbackRate || this._playbackRate;
  49352. this._updateSpatialParameters();
  49353. if (this.isPlaying) {
  49354. if (this._streaming) {
  49355. this._htmlAudioElement.playbackRate = this._playbackRate;
  49356. }
  49357. else {
  49358. if (this._soundSource) {
  49359. this._soundSource.playbackRate.value = this._playbackRate;
  49360. }
  49361. }
  49362. }
  49363. }
  49364. };
  49365. Sound.prototype._createSpatialParameters = function () {
  49366. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  49367. if (this._scene.headphone) {
  49368. this._panningModel = "HRTF";
  49369. }
  49370. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  49371. this._updateSpatialParameters();
  49372. this._soundPanner.connect(this._ouputAudioNode);
  49373. this._inputAudioNode = this._soundPanner;
  49374. }
  49375. };
  49376. Sound.prototype._updateSpatialParameters = function () {
  49377. if (this.spatialSound && this._soundPanner) {
  49378. if (this.useCustomAttenuation) {
  49379. // Tricks to disable in a way embedded Web Audio attenuation
  49380. this._soundPanner.distanceModel = "linear";
  49381. this._soundPanner.maxDistance = Number.MAX_VALUE;
  49382. this._soundPanner.refDistance = 1;
  49383. this._soundPanner.rolloffFactor = 1;
  49384. this._soundPanner.panningModel = this._panningModel;
  49385. }
  49386. else {
  49387. this._soundPanner.distanceModel = this.distanceModel;
  49388. this._soundPanner.maxDistance = this.maxDistance;
  49389. this._soundPanner.refDistance = this.refDistance;
  49390. this._soundPanner.rolloffFactor = this.rolloffFactor;
  49391. this._soundPanner.panningModel = this._panningModel;
  49392. }
  49393. }
  49394. };
  49395. Sound.prototype.switchPanningModelToHRTF = function () {
  49396. this._panningModel = "HRTF";
  49397. this._switchPanningModel();
  49398. };
  49399. Sound.prototype.switchPanningModelToEqualPower = function () {
  49400. this._panningModel = "equalpower";
  49401. this._switchPanningModel();
  49402. };
  49403. Sound.prototype._switchPanningModel = function () {
  49404. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  49405. this._soundPanner.panningModel = this._panningModel;
  49406. }
  49407. };
  49408. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  49409. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49410. if (this._isOutputConnected) {
  49411. this._ouputAudioNode.disconnect();
  49412. }
  49413. this._ouputAudioNode.connect(soundTrackAudioNode);
  49414. this._isOutputConnected = true;
  49415. }
  49416. };
  49417. /**
  49418. * Transform this sound into a directional source
  49419. * @param coneInnerAngle Size of the inner cone in degree
  49420. * @param coneOuterAngle Size of the outer cone in degree
  49421. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  49422. */
  49423. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  49424. if (coneOuterAngle < coneInnerAngle) {
  49425. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  49426. return;
  49427. }
  49428. this._coneInnerAngle = coneInnerAngle;
  49429. this._coneOuterAngle = coneOuterAngle;
  49430. this._coneOuterGain = coneOuterGain;
  49431. this._isDirectional = true;
  49432. if (this.isPlaying && this.loop) {
  49433. this.stop();
  49434. this.play();
  49435. }
  49436. };
  49437. Sound.prototype.setPosition = function (newPosition) {
  49438. this._position = newPosition;
  49439. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  49440. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  49441. }
  49442. };
  49443. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  49444. this._localDirection = newLocalDirection;
  49445. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  49446. this._updateDirection();
  49447. }
  49448. };
  49449. Sound.prototype._updateDirection = function () {
  49450. if (!this._connectedMesh || !this._soundPanner) {
  49451. return;
  49452. }
  49453. var mat = this._connectedMesh.getWorldMatrix();
  49454. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  49455. direction.normalize();
  49456. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  49457. };
  49458. Sound.prototype.updateDistanceFromListener = function () {
  49459. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  49460. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  49461. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  49462. }
  49463. };
  49464. Sound.prototype.setAttenuationFunction = function (callback) {
  49465. this._customAttenuationFunction = callback;
  49466. };
  49467. /**
  49468. * Play the sound
  49469. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  49470. * @param offset (optional) Start the sound setting it at a specific time
  49471. */
  49472. Sound.prototype.play = function (time, offset) {
  49473. var _this = this;
  49474. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  49475. try {
  49476. if (this._startOffset < 0) {
  49477. time = -this._startOffset;
  49478. this._startOffset = 0;
  49479. }
  49480. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  49481. if (!this._soundSource || !this._streamingSource) {
  49482. if (this.spatialSound && this._soundPanner) {
  49483. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  49484. if (this._isDirectional) {
  49485. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  49486. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  49487. this._soundPanner.coneOuterGain = this._coneOuterGain;
  49488. if (this._connectedMesh) {
  49489. this._updateDirection();
  49490. }
  49491. else {
  49492. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  49493. }
  49494. }
  49495. }
  49496. }
  49497. if (this._streaming) {
  49498. if (!this._streamingSource) {
  49499. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  49500. this._htmlAudioElement.onended = function () { _this._onended(); };
  49501. this._htmlAudioElement.playbackRate = this._playbackRate;
  49502. }
  49503. this._streamingSource.disconnect();
  49504. this._streamingSource.connect(this._inputAudioNode);
  49505. this._htmlAudioElement.play();
  49506. }
  49507. else {
  49508. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  49509. this._soundSource.buffer = this._audioBuffer;
  49510. this._soundSource.connect(this._inputAudioNode);
  49511. this._soundSource.loop = this.loop;
  49512. this._soundSource.playbackRate.value = this._playbackRate;
  49513. this._soundSource.onended = function () { _this._onended(); };
  49514. if (this._soundSource.buffer) {
  49515. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  49516. }
  49517. }
  49518. this._startTime = startTime;
  49519. this.isPlaying = true;
  49520. this.isPaused = false;
  49521. }
  49522. catch (ex) {
  49523. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  49524. }
  49525. }
  49526. };
  49527. Sound.prototype._onended = function () {
  49528. this.isPlaying = false;
  49529. if (this.onended) {
  49530. this.onended();
  49531. }
  49532. };
  49533. /**
  49534. * Stop the sound
  49535. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  49536. */
  49537. Sound.prototype.stop = function (time) {
  49538. if (this.isPlaying) {
  49539. if (this._streaming) {
  49540. this._htmlAudioElement.pause();
  49541. // Test needed for Firefox or it will generate an Invalid State Error
  49542. if (this._htmlAudioElement.currentTime > 0) {
  49543. this._htmlAudioElement.currentTime = 0;
  49544. }
  49545. }
  49546. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  49547. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  49548. this._soundSource.stop(stopTime);
  49549. this._soundSource.onended = function () { };
  49550. if (!this.isPaused) {
  49551. this._startOffset = 0;
  49552. }
  49553. }
  49554. this.isPlaying = false;
  49555. }
  49556. };
  49557. Sound.prototype.pause = function () {
  49558. if (this.isPlaying) {
  49559. this.isPaused = true;
  49560. if (this._streaming) {
  49561. this._htmlAudioElement.pause();
  49562. }
  49563. else if (BABYLON.Engine.audioEngine.audioContext) {
  49564. this.stop(0);
  49565. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  49566. }
  49567. }
  49568. };
  49569. Sound.prototype.setVolume = function (newVolume, time) {
  49570. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  49571. if (time && BABYLON.Engine.audioEngine.audioContext) {
  49572. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  49573. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  49574. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  49575. }
  49576. else {
  49577. this._soundGain.gain.value = newVolume;
  49578. }
  49579. }
  49580. this._volume = newVolume;
  49581. };
  49582. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  49583. this._playbackRate = newPlaybackRate;
  49584. if (this.isPlaying) {
  49585. if (this._streaming) {
  49586. this._htmlAudioElement.playbackRate = this._playbackRate;
  49587. }
  49588. else if (this._soundSource) {
  49589. this._soundSource.playbackRate.value = this._playbackRate;
  49590. }
  49591. }
  49592. };
  49593. Sound.prototype.getVolume = function () {
  49594. return this._volume;
  49595. };
  49596. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  49597. var _this = this;
  49598. if (this._connectedMesh && this._registerFunc) {
  49599. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  49600. this._registerFunc = null;
  49601. }
  49602. this._connectedMesh = meshToConnectTo;
  49603. if (!this.spatialSound) {
  49604. this.spatialSound = true;
  49605. this._createSpatialParameters();
  49606. if (this.isPlaying && this.loop) {
  49607. this.stop();
  49608. this.play();
  49609. }
  49610. }
  49611. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  49612. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  49613. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  49614. };
  49615. Sound.prototype.detachFromMesh = function () {
  49616. if (this._connectedMesh && this._registerFunc) {
  49617. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  49618. this._registerFunc = null;
  49619. this._connectedMesh = null;
  49620. }
  49621. };
  49622. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  49623. if (!node.getBoundingInfo) {
  49624. return;
  49625. }
  49626. var mesh = node;
  49627. var boundingInfo = mesh.getBoundingInfo();
  49628. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  49629. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  49630. this._updateDirection();
  49631. }
  49632. };
  49633. Sound.prototype.clone = function () {
  49634. var _this = this;
  49635. if (!this._streaming) {
  49636. var setBufferAndRun = function () {
  49637. if (_this._isReadyToPlay) {
  49638. clonedSound._audioBuffer = _this.getAudioBuffer();
  49639. clonedSound._isReadyToPlay = true;
  49640. if (clonedSound.autoplay) {
  49641. clonedSound.play();
  49642. }
  49643. }
  49644. else {
  49645. window.setTimeout(setBufferAndRun, 300);
  49646. }
  49647. };
  49648. var currentOptions = {
  49649. autoplay: this.autoplay, loop: this.loop,
  49650. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  49651. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  49652. refDistance: this.refDistance, distanceModel: this.distanceModel
  49653. };
  49654. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  49655. if (this.useCustomAttenuation) {
  49656. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  49657. }
  49658. clonedSound.setPosition(this._position);
  49659. clonedSound.setPlaybackRate(this._playbackRate);
  49660. setBufferAndRun();
  49661. return clonedSound;
  49662. }
  49663. else {
  49664. return null;
  49665. }
  49666. };
  49667. Sound.prototype.getAudioBuffer = function () {
  49668. return this._audioBuffer;
  49669. };
  49670. Sound.prototype.serialize = function () {
  49671. var serializationObject = {
  49672. name: this.name,
  49673. url: this.name,
  49674. autoplay: this.autoplay,
  49675. loop: this.loop,
  49676. volume: this._volume,
  49677. spatialSound: this.spatialSound,
  49678. maxDistance: this.maxDistance,
  49679. rolloffFactor: this.rolloffFactor,
  49680. refDistance: this.refDistance,
  49681. distanceModel: this.distanceModel,
  49682. playbackRate: this._playbackRate,
  49683. panningModel: this._panningModel,
  49684. soundTrackId: this.soundTrackId
  49685. };
  49686. if (this.spatialSound) {
  49687. if (this._connectedMesh)
  49688. serializationObject.connectedMeshId = this._connectedMesh.id;
  49689. serializationObject.position = this._position.asArray();
  49690. serializationObject.refDistance = this.refDistance;
  49691. serializationObject.distanceModel = this.distanceModel;
  49692. serializationObject.isDirectional = this._isDirectional;
  49693. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  49694. serializationObject.coneInnerAngle = this._coneInnerAngle;
  49695. serializationObject.coneOuterAngle = this._coneOuterAngle;
  49696. serializationObject.coneOuterGain = this._coneOuterGain;
  49697. }
  49698. return serializationObject;
  49699. };
  49700. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  49701. var soundName = parsedSound.name;
  49702. var soundUrl;
  49703. if (parsedSound.url) {
  49704. soundUrl = rootUrl + parsedSound.url;
  49705. }
  49706. else {
  49707. soundUrl = rootUrl + soundName;
  49708. }
  49709. var options = {
  49710. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  49711. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  49712. rolloffFactor: parsedSound.rolloffFactor,
  49713. refDistance: parsedSound.refDistance,
  49714. distanceModel: parsedSound.distanceModel,
  49715. playbackRate: parsedSound.playbackRate
  49716. };
  49717. var newSound;
  49718. if (!sourceSound) {
  49719. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  49720. scene._addPendingData(newSound);
  49721. }
  49722. else {
  49723. var setBufferAndRun = function () {
  49724. if (sourceSound._isReadyToPlay) {
  49725. newSound._audioBuffer = sourceSound.getAudioBuffer();
  49726. newSound._isReadyToPlay = true;
  49727. if (newSound.autoplay) {
  49728. newSound.play();
  49729. }
  49730. }
  49731. else {
  49732. window.setTimeout(setBufferAndRun, 300);
  49733. }
  49734. };
  49735. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  49736. setBufferAndRun();
  49737. }
  49738. if (parsedSound.position) {
  49739. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  49740. newSound.setPosition(soundPosition);
  49741. }
  49742. if (parsedSound.isDirectional) {
  49743. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  49744. if (parsedSound.localDirectionToMesh) {
  49745. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  49746. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  49747. }
  49748. }
  49749. if (parsedSound.connectedMeshId) {
  49750. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  49751. if (connectedMesh) {
  49752. newSound.attachToMesh(connectedMesh);
  49753. }
  49754. }
  49755. return newSound;
  49756. };
  49757. return Sound;
  49758. }());
  49759. BABYLON.Sound = Sound;
  49760. })(BABYLON || (BABYLON = {}));
  49761. //# sourceMappingURL=babylon.sound.js.map
  49762. var BABYLON;
  49763. (function (BABYLON) {
  49764. var SoundTrack = /** @class */ (function () {
  49765. function SoundTrack(scene, options) {
  49766. this.id = -1;
  49767. this._isMainTrack = false;
  49768. this._isInitialized = false;
  49769. this._scene = scene;
  49770. this.soundCollection = new Array();
  49771. this._options = options;
  49772. if (!this._isMainTrack) {
  49773. this._scene.soundTracks.push(this);
  49774. this.id = this._scene.soundTracks.length - 1;
  49775. }
  49776. }
  49777. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  49778. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  49779. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  49780. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  49781. if (this._options) {
  49782. if (this._options.volume) {
  49783. this._outputAudioNode.gain.value = this._options.volume;
  49784. }
  49785. if (this._options.mainTrack) {
  49786. this._isMainTrack = this._options.mainTrack;
  49787. }
  49788. }
  49789. this._isInitialized = true;
  49790. }
  49791. };
  49792. SoundTrack.prototype.dispose = function () {
  49793. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49794. if (this._connectedAnalyser) {
  49795. this._connectedAnalyser.stopDebugCanvas();
  49796. }
  49797. while (this.soundCollection.length) {
  49798. this.soundCollection[0].dispose();
  49799. }
  49800. if (this._outputAudioNode) {
  49801. this._outputAudioNode.disconnect();
  49802. }
  49803. this._outputAudioNode = null;
  49804. }
  49805. };
  49806. SoundTrack.prototype.AddSound = function (sound) {
  49807. if (!this._isInitialized) {
  49808. this._initializeSoundTrackAudioGraph();
  49809. }
  49810. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  49811. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  49812. }
  49813. if (sound.soundTrackId) {
  49814. if (sound.soundTrackId === -1) {
  49815. this._scene.mainSoundTrack.RemoveSound(sound);
  49816. }
  49817. else {
  49818. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  49819. }
  49820. }
  49821. this.soundCollection.push(sound);
  49822. sound.soundTrackId = this.id;
  49823. };
  49824. SoundTrack.prototype.RemoveSound = function (sound) {
  49825. var index = this.soundCollection.indexOf(sound);
  49826. if (index !== -1) {
  49827. this.soundCollection.splice(index, 1);
  49828. }
  49829. };
  49830. SoundTrack.prototype.setVolume = function (newVolume) {
  49831. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  49832. this._outputAudioNode.gain.value = newVolume;
  49833. }
  49834. };
  49835. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  49836. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49837. for (var i = 0; i < this.soundCollection.length; i++) {
  49838. this.soundCollection[i].switchPanningModelToHRTF();
  49839. }
  49840. }
  49841. };
  49842. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  49843. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49844. for (var i = 0; i < this.soundCollection.length; i++) {
  49845. this.soundCollection[i].switchPanningModelToEqualPower();
  49846. }
  49847. }
  49848. };
  49849. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  49850. if (this._connectedAnalyser) {
  49851. this._connectedAnalyser.stopDebugCanvas();
  49852. }
  49853. this._connectedAnalyser = analyser;
  49854. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  49855. this._outputAudioNode.disconnect();
  49856. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  49857. }
  49858. };
  49859. return SoundTrack;
  49860. }());
  49861. BABYLON.SoundTrack = SoundTrack;
  49862. })(BABYLON || (BABYLON = {}));
  49863. //# sourceMappingURL=babylon.soundtrack.js.map
  49864. var BABYLON;
  49865. (function (BABYLON) {
  49866. var Analyser = /** @class */ (function () {
  49867. function Analyser(scene) {
  49868. this.SMOOTHING = 0.75;
  49869. this.FFT_SIZE = 512;
  49870. this.BARGRAPHAMPLITUDE = 256;
  49871. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  49872. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  49873. this._scene = scene;
  49874. this._audioEngine = BABYLON.Engine.audioEngine;
  49875. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  49876. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  49877. this._webAudioAnalyser.minDecibels = -140;
  49878. this._webAudioAnalyser.maxDecibels = 0;
  49879. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  49880. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  49881. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  49882. }
  49883. }
  49884. Analyser.prototype.getFrequencyBinCount = function () {
  49885. if (this._audioEngine.canUseWebAudio) {
  49886. return this._webAudioAnalyser.frequencyBinCount;
  49887. }
  49888. else {
  49889. return 0;
  49890. }
  49891. };
  49892. Analyser.prototype.getByteFrequencyData = function () {
  49893. if (this._audioEngine.canUseWebAudio) {
  49894. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  49895. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  49896. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  49897. }
  49898. return this._byteFreqs;
  49899. };
  49900. Analyser.prototype.getByteTimeDomainData = function () {
  49901. if (this._audioEngine.canUseWebAudio) {
  49902. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  49903. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  49904. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  49905. }
  49906. return this._byteTime;
  49907. };
  49908. Analyser.prototype.getFloatFrequencyData = function () {
  49909. if (this._audioEngine.canUseWebAudio) {
  49910. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  49911. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  49912. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  49913. }
  49914. return this._floatFreqs;
  49915. };
  49916. Analyser.prototype.drawDebugCanvas = function () {
  49917. var _this = this;
  49918. if (this._audioEngine.canUseWebAudio) {
  49919. if (!this._debugCanvas) {
  49920. this._debugCanvas = document.createElement("canvas");
  49921. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  49922. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  49923. this._debugCanvas.style.position = "absolute";
  49924. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  49925. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  49926. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  49927. document.body.appendChild(this._debugCanvas);
  49928. this._registerFunc = function () {
  49929. _this.drawDebugCanvas();
  49930. };
  49931. this._scene.registerBeforeRender(this._registerFunc);
  49932. }
  49933. if (this._registerFunc && this._debugCanvasContext) {
  49934. var workingArray = this.getByteFrequencyData();
  49935. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  49936. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  49937. // Draw the frequency domain chart.
  49938. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  49939. var value = workingArray[i];
  49940. var percent = value / this.BARGRAPHAMPLITUDE;
  49941. var height = this.DEBUGCANVASSIZE.height * percent;
  49942. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  49943. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  49944. var hue = i / this.getFrequencyBinCount() * 360;
  49945. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  49946. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  49947. }
  49948. }
  49949. }
  49950. };
  49951. Analyser.prototype.stopDebugCanvas = function () {
  49952. if (this._debugCanvas) {
  49953. if (this._registerFunc) {
  49954. this._scene.unregisterBeforeRender(this._registerFunc);
  49955. this._registerFunc = null;
  49956. }
  49957. document.body.removeChild(this._debugCanvas);
  49958. this._debugCanvas = null;
  49959. this._debugCanvasContext = null;
  49960. }
  49961. };
  49962. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  49963. if (this._audioEngine.canUseWebAudio) {
  49964. inputAudioNode.connect(this._webAudioAnalyser);
  49965. this._webAudioAnalyser.connect(outputAudioNode);
  49966. }
  49967. };
  49968. Analyser.prototype.dispose = function () {
  49969. if (this._audioEngine.canUseWebAudio) {
  49970. this._webAudioAnalyser.disconnect();
  49971. }
  49972. };
  49973. return Analyser;
  49974. }());
  49975. BABYLON.Analyser = Analyser;
  49976. })(BABYLON || (BABYLON = {}));
  49977. //# sourceMappingURL=babylon.analyser.js.map
  49978. var BABYLON;
  49979. (function (BABYLON) {
  49980. var CubeTexture = /** @class */ (function (_super) {
  49981. __extends(CubeTexture, _super);
  49982. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  49983. if (extensions === void 0) { extensions = null; }
  49984. if (noMipmap === void 0) { noMipmap = false; }
  49985. if (files === void 0) { files = null; }
  49986. if (onLoad === void 0) { onLoad = null; }
  49987. if (onError === void 0) { onError = null; }
  49988. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  49989. if (prefiltered === void 0) { prefiltered = false; }
  49990. if (forcedExtension === void 0) { forcedExtension = null; }
  49991. var _this = _super.call(this, scene) || this;
  49992. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  49993. _this.name = rootUrl;
  49994. _this.url = rootUrl;
  49995. _this._noMipmap = noMipmap;
  49996. _this.hasAlpha = false;
  49997. _this._format = format;
  49998. _this._prefiltered = prefiltered;
  49999. _this.isCube = true;
  50000. _this._textureMatrix = BABYLON.Matrix.Identity();
  50001. if (prefiltered) {
  50002. _this.gammaSpace = false;
  50003. }
  50004. if (!rootUrl && !files) {
  50005. return _this;
  50006. }
  50007. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  50008. var lastDot = rootUrl.lastIndexOf(".");
  50009. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  50010. var isDDS = (extension === ".dds");
  50011. if (!files) {
  50012. if (!isDDS && !extensions) {
  50013. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  50014. }
  50015. files = [];
  50016. if (extensions) {
  50017. for (var index = 0; index < extensions.length; index++) {
  50018. files.push(rootUrl + extensions[index]);
  50019. }
  50020. }
  50021. }
  50022. if (!_this._texture) {
  50023. if (!scene.useDelayedTextureLoading) {
  50024. if (prefiltered) {
  50025. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  50026. }
  50027. else {
  50028. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  50029. }
  50030. }
  50031. else {
  50032. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  50033. }
  50034. }
  50035. else if (onLoad) {
  50036. if (_this._texture.isReady) {
  50037. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  50038. }
  50039. else {
  50040. _this._texture.onLoadedObservable.add(onLoad);
  50041. }
  50042. }
  50043. return _this;
  50044. }
  50045. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  50046. return new CubeTexture("", scene, null, noMipmap, files);
  50047. };
  50048. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  50049. if (forcedExtension === void 0) { forcedExtension = null; }
  50050. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  50051. };
  50052. // Methods
  50053. CubeTexture.prototype.delayLoad = function () {
  50054. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  50055. return;
  50056. }
  50057. var scene = this.getScene();
  50058. if (!scene) {
  50059. return;
  50060. }
  50061. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  50062. this._texture = this._getFromCache(this.url, this._noMipmap);
  50063. if (!this._texture) {
  50064. if (this._prefiltered) {
  50065. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  50066. }
  50067. else {
  50068. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  50069. }
  50070. }
  50071. };
  50072. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  50073. return this._textureMatrix;
  50074. };
  50075. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  50076. this._textureMatrix = value;
  50077. };
  50078. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  50079. var texture = BABYLON.SerializationHelper.Parse(function () {
  50080. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  50081. }, parsedTexture, scene);
  50082. // Animations
  50083. if (parsedTexture.animations) {
  50084. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  50085. var parsedAnimation = parsedTexture.animations[animationIndex];
  50086. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  50087. }
  50088. }
  50089. return texture;
  50090. };
  50091. CubeTexture.prototype.clone = function () {
  50092. var _this = this;
  50093. return BABYLON.SerializationHelper.Clone(function () {
  50094. var scene = _this.getScene();
  50095. if (!scene) {
  50096. return _this;
  50097. }
  50098. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  50099. }, this);
  50100. };
  50101. return CubeTexture;
  50102. }(BABYLON.BaseTexture));
  50103. BABYLON.CubeTexture = CubeTexture;
  50104. })(BABYLON || (BABYLON = {}));
  50105. //# sourceMappingURL=babylon.cubeTexture.js.map
  50106. var BABYLON;
  50107. (function (BABYLON) {
  50108. var RenderTargetTexture = /** @class */ (function (_super) {
  50109. __extends(RenderTargetTexture, _super);
  50110. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  50111. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  50112. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50113. if (isCube === void 0) { isCube = false; }
  50114. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50115. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  50116. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  50117. if (isMulti === void 0) { isMulti = false; }
  50118. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  50119. _this.isCube = isCube;
  50120. /**
  50121. * Use this list to define the list of mesh you want to render.
  50122. */
  50123. _this.renderList = new Array();
  50124. _this.renderParticles = true;
  50125. _this.renderSprites = false;
  50126. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  50127. _this.ignoreCameraViewport = false;
  50128. // Events
  50129. /**
  50130. * An event triggered when the texture is unbind.
  50131. * @type {BABYLON.Observable}
  50132. */
  50133. _this.onBeforeBindObservable = new BABYLON.Observable();
  50134. /**
  50135. * An event triggered when the texture is unbind.
  50136. * @type {BABYLON.Observable}
  50137. */
  50138. _this.onAfterUnbindObservable = new BABYLON.Observable();
  50139. /**
  50140. * An event triggered before rendering the texture
  50141. * @type {BABYLON.Observable}
  50142. */
  50143. _this.onBeforeRenderObservable = new BABYLON.Observable();
  50144. /**
  50145. * An event triggered after rendering the texture
  50146. * @type {BABYLON.Observable}
  50147. */
  50148. _this.onAfterRenderObservable = new BABYLON.Observable();
  50149. /**
  50150. * An event triggered after the texture clear
  50151. * @type {BABYLON.Observable}
  50152. */
  50153. _this.onClearObservable = new BABYLON.Observable();
  50154. _this._currentRefreshId = -1;
  50155. _this._refreshRate = 1;
  50156. _this._samples = 1;
  50157. scene = _this.getScene();
  50158. if (!scene) {
  50159. return _this;
  50160. }
  50161. _this._engine = scene.getEngine();
  50162. _this.name = name;
  50163. _this.isRenderTarget = true;
  50164. _this._initialSizeParameter = size;
  50165. _this._processSizeParameter(size);
  50166. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  50167. });
  50168. _this._generateMipMaps = generateMipMaps ? true : false;
  50169. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  50170. // Rendering groups
  50171. _this._renderingManager = new BABYLON.RenderingManager(scene);
  50172. if (isMulti) {
  50173. return _this;
  50174. }
  50175. _this._renderTargetOptions = {
  50176. generateMipMaps: generateMipMaps,
  50177. type: type,
  50178. samplingMode: samplingMode,
  50179. generateDepthBuffer: generateDepthBuffer,
  50180. generateStencilBuffer: generateStencilBuffer
  50181. };
  50182. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  50183. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50184. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50185. }
  50186. if (isCube) {
  50187. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  50188. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  50189. _this._textureMatrix = BABYLON.Matrix.Identity();
  50190. }
  50191. else {
  50192. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  50193. }
  50194. return _this;
  50195. }
  50196. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  50197. get: function () {
  50198. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  50199. },
  50200. enumerable: true,
  50201. configurable: true
  50202. });
  50203. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  50204. get: function () {
  50205. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  50206. },
  50207. enumerable: true,
  50208. configurable: true
  50209. });
  50210. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  50211. get: function () {
  50212. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  50213. },
  50214. enumerable: true,
  50215. configurable: true
  50216. });
  50217. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  50218. set: function (callback) {
  50219. if (this._onAfterUnbindObserver) {
  50220. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  50221. }
  50222. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  50223. },
  50224. enumerable: true,
  50225. configurable: true
  50226. });
  50227. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  50228. set: function (callback) {
  50229. if (this._onBeforeRenderObserver) {
  50230. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  50231. }
  50232. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  50233. },
  50234. enumerable: true,
  50235. configurable: true
  50236. });
  50237. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  50238. set: function (callback) {
  50239. if (this._onAfterRenderObserver) {
  50240. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  50241. }
  50242. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  50243. },
  50244. enumerable: true,
  50245. configurable: true
  50246. });
  50247. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  50248. set: function (callback) {
  50249. if (this._onClearObserver) {
  50250. this.onClearObservable.remove(this._onClearObserver);
  50251. }
  50252. this._onClearObserver = this.onClearObservable.add(callback);
  50253. },
  50254. enumerable: true,
  50255. configurable: true
  50256. });
  50257. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  50258. get: function () {
  50259. return this._renderTargetOptions;
  50260. },
  50261. enumerable: true,
  50262. configurable: true
  50263. });
  50264. RenderTargetTexture.prototype._onRatioRescale = function () {
  50265. if (this._sizeRatio) {
  50266. this.resize(this._initialSizeParameter);
  50267. }
  50268. };
  50269. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  50270. if (size.ratio) {
  50271. this._sizeRatio = size.ratio;
  50272. this._size = {
  50273. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  50274. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  50275. };
  50276. }
  50277. else {
  50278. this._size = size;
  50279. }
  50280. };
  50281. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  50282. get: function () {
  50283. return this._samples;
  50284. },
  50285. set: function (value) {
  50286. if (this._samples === value) {
  50287. return;
  50288. }
  50289. var scene = this.getScene();
  50290. if (!scene) {
  50291. return;
  50292. }
  50293. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  50294. },
  50295. enumerable: true,
  50296. configurable: true
  50297. });
  50298. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  50299. this._currentRefreshId = -1;
  50300. };
  50301. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  50302. get: function () {
  50303. return this._refreshRate;
  50304. },
  50305. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  50306. set: function (value) {
  50307. this._refreshRate = value;
  50308. this.resetRefreshCounter();
  50309. },
  50310. enumerable: true,
  50311. configurable: true
  50312. });
  50313. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  50314. if (!this._postProcessManager) {
  50315. var scene = this.getScene();
  50316. if (!scene) {
  50317. return;
  50318. }
  50319. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  50320. this._postProcesses = new Array();
  50321. }
  50322. this._postProcesses.push(postProcess);
  50323. this._postProcesses[0].autoClear = false;
  50324. };
  50325. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  50326. if (!this._postProcesses) {
  50327. return;
  50328. }
  50329. if (dispose) {
  50330. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  50331. var postProcess = _a[_i];
  50332. postProcess.dispose();
  50333. }
  50334. }
  50335. this._postProcesses = [];
  50336. };
  50337. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  50338. if (!this._postProcesses) {
  50339. return;
  50340. }
  50341. var index = this._postProcesses.indexOf(postProcess);
  50342. if (index === -1) {
  50343. return;
  50344. }
  50345. this._postProcesses.splice(index, 1);
  50346. if (this._postProcesses.length > 0) {
  50347. this._postProcesses[0].autoClear = false;
  50348. }
  50349. };
  50350. RenderTargetTexture.prototype._shouldRender = function () {
  50351. if (this._currentRefreshId === -1) {
  50352. this._currentRefreshId = 1;
  50353. return true;
  50354. }
  50355. if (this.refreshRate === this._currentRefreshId) {
  50356. this._currentRefreshId = 1;
  50357. return true;
  50358. }
  50359. this._currentRefreshId++;
  50360. return false;
  50361. };
  50362. RenderTargetTexture.prototype.getRenderSize = function () {
  50363. if (this._size.width) {
  50364. return this._size.width;
  50365. }
  50366. return this._size;
  50367. };
  50368. RenderTargetTexture.prototype.getRenderWidth = function () {
  50369. if (this._size.width) {
  50370. return this._size.width;
  50371. }
  50372. return this._size;
  50373. };
  50374. RenderTargetTexture.prototype.getRenderHeight = function () {
  50375. if (this._size.width) {
  50376. return this._size.height;
  50377. }
  50378. return this._size;
  50379. };
  50380. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  50381. get: function () {
  50382. return true;
  50383. },
  50384. enumerable: true,
  50385. configurable: true
  50386. });
  50387. RenderTargetTexture.prototype.scale = function (ratio) {
  50388. var newSize = this.getRenderSize() * ratio;
  50389. this.resize(newSize);
  50390. };
  50391. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  50392. if (this.isCube) {
  50393. return this._textureMatrix;
  50394. }
  50395. return _super.prototype.getReflectionTextureMatrix.call(this);
  50396. };
  50397. RenderTargetTexture.prototype.resize = function (size) {
  50398. this.releaseInternalTexture();
  50399. var scene = this.getScene();
  50400. if (!scene) {
  50401. return;
  50402. }
  50403. this._processSizeParameter(size);
  50404. if (this.isCube) {
  50405. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  50406. }
  50407. else {
  50408. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  50409. }
  50410. };
  50411. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  50412. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  50413. if (dumpForDebug === void 0) { dumpForDebug = false; }
  50414. var scene = this.getScene();
  50415. if (!scene) {
  50416. return;
  50417. }
  50418. var engine = scene.getEngine();
  50419. if (this.useCameraPostProcesses !== undefined) {
  50420. useCameraPostProcess = this.useCameraPostProcesses;
  50421. }
  50422. if (this._waitingRenderList) {
  50423. this.renderList = [];
  50424. for (var index = 0; index < this._waitingRenderList.length; index++) {
  50425. var id = this._waitingRenderList[index];
  50426. var mesh_1 = scene.getMeshByID(id);
  50427. if (mesh_1) {
  50428. this.renderList.push(mesh_1);
  50429. }
  50430. }
  50431. delete this._waitingRenderList;
  50432. }
  50433. // Is predicate defined?
  50434. if (this.renderListPredicate) {
  50435. if (this.renderList) {
  50436. this.renderList.splice(0); // Clear previous renderList
  50437. }
  50438. else {
  50439. this.renderList = [];
  50440. }
  50441. var scene = this.getScene();
  50442. if (!scene) {
  50443. return;
  50444. }
  50445. var sceneMeshes = scene.meshes;
  50446. for (var index = 0; index < sceneMeshes.length; index++) {
  50447. var mesh = sceneMeshes[index];
  50448. if (this.renderListPredicate(mesh)) {
  50449. this.renderList.push(mesh);
  50450. }
  50451. }
  50452. }
  50453. this.onBeforeBindObservable.notifyObservers(this);
  50454. // Set custom projection.
  50455. // Needs to be before binding to prevent changing the aspect ratio.
  50456. var camera;
  50457. if (this.activeCamera) {
  50458. camera = this.activeCamera;
  50459. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  50460. if (this.activeCamera !== scene.activeCamera) {
  50461. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  50462. }
  50463. }
  50464. else {
  50465. camera = scene.activeCamera;
  50466. if (camera) {
  50467. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  50468. }
  50469. }
  50470. // Prepare renderingManager
  50471. this._renderingManager.reset();
  50472. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  50473. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  50474. var sceneRenderId = scene.getRenderId();
  50475. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  50476. var mesh = currentRenderList[meshIndex];
  50477. if (mesh) {
  50478. if (!mesh.isReady()) {
  50479. // Reset _currentRefreshId
  50480. this.resetRefreshCounter();
  50481. continue;
  50482. }
  50483. mesh._preActivateForIntermediateRendering(sceneRenderId);
  50484. var isMasked = void 0;
  50485. if (!this.renderList && camera) {
  50486. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  50487. }
  50488. else {
  50489. isMasked = false;
  50490. }
  50491. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  50492. mesh._activate(sceneRenderId);
  50493. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  50494. var subMesh = mesh.subMeshes[subIndex];
  50495. scene._activeIndices.addCount(subMesh.indexCount, false);
  50496. this._renderingManager.dispatch(subMesh);
  50497. }
  50498. }
  50499. }
  50500. }
  50501. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  50502. var particleSystem = scene.particleSystems[particleIndex];
  50503. var emitter = particleSystem.emitter;
  50504. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  50505. continue;
  50506. }
  50507. if (currentRenderList.indexOf(emitter) >= 0) {
  50508. this._renderingManager.dispatchParticles(particleSystem);
  50509. }
  50510. }
  50511. if (this.isCube) {
  50512. for (var face = 0; face < 6; face++) {
  50513. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  50514. scene.incrementRenderId();
  50515. scene.resetCachedMaterial();
  50516. }
  50517. }
  50518. else {
  50519. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  50520. }
  50521. this.onAfterUnbindObservable.notifyObservers(this);
  50522. if (scene.activeCamera) {
  50523. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  50524. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  50525. }
  50526. engine.setViewport(scene.activeCamera.viewport);
  50527. }
  50528. scene.resetCachedMaterial();
  50529. };
  50530. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  50531. var minimum = 128;
  50532. var x = renderDimension * scale;
  50533. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  50534. // Ensure we don't exceed the render dimension (while staying POT)
  50535. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  50536. };
  50537. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  50538. var _this = this;
  50539. var scene = this.getScene();
  50540. if (!scene) {
  50541. return;
  50542. }
  50543. var engine = scene.getEngine();
  50544. if (!this._texture) {
  50545. return;
  50546. }
  50547. // Bind
  50548. if (this._postProcessManager) {
  50549. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  50550. }
  50551. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  50552. if (this._texture) {
  50553. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  50554. }
  50555. }
  50556. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  50557. // Clear
  50558. if (this.onClearObservable.hasObservers()) {
  50559. this.onClearObservable.notifyObservers(engine);
  50560. }
  50561. else {
  50562. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  50563. }
  50564. if (!this._doNotChangeAspectRatio) {
  50565. scene.updateTransformMatrix(true);
  50566. }
  50567. // Render
  50568. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  50569. if (this._postProcessManager) {
  50570. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  50571. }
  50572. else if (useCameraPostProcess) {
  50573. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  50574. }
  50575. if (!this._doNotChangeAspectRatio) {
  50576. scene.updateTransformMatrix(true);
  50577. }
  50578. // Dump ?
  50579. if (dumpForDebug) {
  50580. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  50581. }
  50582. // Unbind
  50583. if (!this.isCube || faceIndex === 5) {
  50584. if (this.isCube) {
  50585. if (faceIndex === 5) {
  50586. engine.generateMipMapsForCubemap(this._texture);
  50587. }
  50588. }
  50589. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  50590. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  50591. });
  50592. }
  50593. else {
  50594. this.onAfterRenderObservable.notifyObservers(faceIndex);
  50595. }
  50596. };
  50597. /**
  50598. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  50599. * This allowed control for front to back rendering or reversly depending of the special needs.
  50600. *
  50601. * @param renderingGroupId The rendering group id corresponding to its index
  50602. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  50603. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  50604. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  50605. */
  50606. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  50607. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  50608. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  50609. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  50610. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  50611. };
  50612. /**
  50613. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  50614. *
  50615. * @param renderingGroupId The rendering group id corresponding to its index
  50616. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  50617. */
  50618. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  50619. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  50620. };
  50621. RenderTargetTexture.prototype.clone = function () {
  50622. var textureSize = this.getSize();
  50623. 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);
  50624. // Base texture
  50625. newTexture.hasAlpha = this.hasAlpha;
  50626. newTexture.level = this.level;
  50627. // RenderTarget Texture
  50628. newTexture.coordinatesMode = this.coordinatesMode;
  50629. if (this.renderList) {
  50630. newTexture.renderList = this.renderList.slice(0);
  50631. }
  50632. return newTexture;
  50633. };
  50634. RenderTargetTexture.prototype.serialize = function () {
  50635. if (!this.name) {
  50636. return null;
  50637. }
  50638. var serializationObject = _super.prototype.serialize.call(this);
  50639. serializationObject.renderTargetSize = this.getRenderSize();
  50640. serializationObject.renderList = [];
  50641. if (this.renderList) {
  50642. for (var index = 0; index < this.renderList.length; index++) {
  50643. serializationObject.renderList.push(this.renderList[index].id);
  50644. }
  50645. }
  50646. return serializationObject;
  50647. };
  50648. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  50649. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  50650. var objBuffer = this.getInternalTexture();
  50651. var scene = this.getScene();
  50652. if (objBuffer && scene) {
  50653. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  50654. }
  50655. };
  50656. RenderTargetTexture.prototype.dispose = function () {
  50657. if (this._postProcessManager) {
  50658. this._postProcessManager.dispose();
  50659. this._postProcessManager = null;
  50660. }
  50661. this.clearPostProcesses(true);
  50662. if (this._resizeObserver) {
  50663. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  50664. this._resizeObserver = null;
  50665. }
  50666. this.renderList = null;
  50667. // Remove from custom render targets
  50668. var scene = this.getScene();
  50669. if (!scene) {
  50670. return;
  50671. }
  50672. var index = scene.customRenderTargets.indexOf(this);
  50673. if (index >= 0) {
  50674. scene.customRenderTargets.splice(index, 1);
  50675. }
  50676. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  50677. var camera = _a[_i];
  50678. index = camera.customRenderTargets.indexOf(this);
  50679. if (index >= 0) {
  50680. camera.customRenderTargets.splice(index, 1);
  50681. }
  50682. }
  50683. _super.prototype.dispose.call(this);
  50684. };
  50685. RenderTargetTexture.prototype._rebuild = function () {
  50686. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  50687. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  50688. }
  50689. if (this._postProcessManager) {
  50690. this._postProcessManager._rebuild();
  50691. }
  50692. };
  50693. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  50694. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  50695. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  50696. return RenderTargetTexture;
  50697. }(BABYLON.Texture));
  50698. BABYLON.RenderTargetTexture = RenderTargetTexture;
  50699. })(BABYLON || (BABYLON = {}));
  50700. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  50701. var BABYLON;
  50702. (function (BABYLON) {
  50703. ;
  50704. var MultiRenderTarget = /** @class */ (function (_super) {
  50705. __extends(MultiRenderTarget, _super);
  50706. function MultiRenderTarget(name, size, count, scene, options) {
  50707. var _this = this;
  50708. options = options || {};
  50709. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  50710. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  50711. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  50712. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  50713. _this._engine = scene.getEngine();
  50714. if (!_this.isSupported) {
  50715. _this.dispose();
  50716. return;
  50717. }
  50718. var types = [];
  50719. var samplingModes = [];
  50720. for (var i = 0; i < count; i++) {
  50721. if (options.types && options.types[i]) {
  50722. types.push(options.types[i]);
  50723. }
  50724. else {
  50725. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  50726. }
  50727. if (options.samplingModes && options.samplingModes[i]) {
  50728. samplingModes.push(options.samplingModes[i]);
  50729. }
  50730. else {
  50731. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  50732. }
  50733. }
  50734. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  50735. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  50736. _this._size = size;
  50737. _this._multiRenderTargetOptions = {
  50738. samplingModes: samplingModes,
  50739. generateMipMaps: generateMipMaps,
  50740. generateDepthBuffer: generateDepthBuffer,
  50741. generateStencilBuffer: generateStencilBuffer,
  50742. generateDepthTexture: generateDepthTexture,
  50743. types: types,
  50744. textureCount: count
  50745. };
  50746. _this._createInternalTextures();
  50747. _this._createTextures();
  50748. return _this;
  50749. }
  50750. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  50751. get: function () {
  50752. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  50753. },
  50754. enumerable: true,
  50755. configurable: true
  50756. });
  50757. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  50758. get: function () {
  50759. return this._textures;
  50760. },
  50761. enumerable: true,
  50762. configurable: true
  50763. });
  50764. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  50765. get: function () {
  50766. return this._textures[this._textures.length - 1];
  50767. },
  50768. enumerable: true,
  50769. configurable: true
  50770. });
  50771. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  50772. set: function (wrap) {
  50773. if (this._textures) {
  50774. for (var i = 0; i < this._textures.length; i++) {
  50775. this._textures[i].wrapU = wrap;
  50776. }
  50777. }
  50778. },
  50779. enumerable: true,
  50780. configurable: true
  50781. });
  50782. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  50783. set: function (wrap) {
  50784. if (this._textures) {
  50785. for (var i = 0; i < this._textures.length; i++) {
  50786. this._textures[i].wrapV = wrap;
  50787. }
  50788. }
  50789. },
  50790. enumerable: true,
  50791. configurable: true
  50792. });
  50793. MultiRenderTarget.prototype._rebuild = function () {
  50794. this.releaseInternalTextures();
  50795. this._createInternalTextures();
  50796. for (var i = 0; i < this._internalTextures.length; i++) {
  50797. var texture = this._textures[i];
  50798. texture._texture = this._internalTextures[i];
  50799. }
  50800. // Keeps references to frame buffer and stencil/depth buffer
  50801. this._texture = this._internalTextures[0];
  50802. };
  50803. MultiRenderTarget.prototype._createInternalTextures = function () {
  50804. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  50805. };
  50806. MultiRenderTarget.prototype._createTextures = function () {
  50807. this._textures = [];
  50808. for (var i = 0; i < this._internalTextures.length; i++) {
  50809. var texture = new BABYLON.Texture(null, this.getScene());
  50810. texture._texture = this._internalTextures[i];
  50811. this._textures.push(texture);
  50812. }
  50813. // Keeps references to frame buffer and stencil/depth buffer
  50814. this._texture = this._internalTextures[0];
  50815. };
  50816. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  50817. get: function () {
  50818. return this._samples;
  50819. },
  50820. set: function (value) {
  50821. if (this._samples === value) {
  50822. return;
  50823. }
  50824. for (var i = 0; i < this._internalTextures.length; i++) {
  50825. this._samples = this._engine.updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  50826. }
  50827. },
  50828. enumerable: true,
  50829. configurable: true
  50830. });
  50831. MultiRenderTarget.prototype.resize = function (size) {
  50832. this.releaseInternalTextures();
  50833. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  50834. this._createInternalTextures();
  50835. };
  50836. MultiRenderTarget.prototype.dispose = function () {
  50837. this.releaseInternalTextures();
  50838. _super.prototype.dispose.call(this);
  50839. };
  50840. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  50841. if (!this._internalTextures) {
  50842. return;
  50843. }
  50844. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  50845. if (this._internalTextures[i] !== undefined) {
  50846. this._internalTextures[i].dispose();
  50847. this._internalTextures.splice(i, 1);
  50848. }
  50849. }
  50850. };
  50851. return MultiRenderTarget;
  50852. }(BABYLON.RenderTargetTexture));
  50853. BABYLON.MultiRenderTarget = MultiRenderTarget;
  50854. })(BABYLON || (BABYLON = {}));
  50855. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  50856. var BABYLON;
  50857. (function (BABYLON) {
  50858. var MirrorTexture = /** @class */ (function (_super) {
  50859. __extends(MirrorTexture, _super);
  50860. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  50861. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50862. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  50863. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  50864. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  50865. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  50866. _this._transformMatrix = BABYLON.Matrix.Zero();
  50867. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  50868. _this._adaptiveBlurKernel = 0;
  50869. _this._blurKernelX = 0;
  50870. _this._blurKernelY = 0;
  50871. _this._blurRatio = 1.0;
  50872. _this.ignoreCameraViewport = true;
  50873. _this.onBeforeRenderObservable.add(function () {
  50874. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  50875. _this._savedViewMatrix = scene.getViewMatrix();
  50876. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  50877. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  50878. scene.clipPlane = _this.mirrorPlane;
  50879. scene.getEngine().cullBackFaces = false;
  50880. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  50881. });
  50882. _this.onAfterRenderObservable.add(function () {
  50883. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  50884. scene.getEngine().cullBackFaces = true;
  50885. scene._mirroredCameraPosition = null;
  50886. delete scene.clipPlane;
  50887. });
  50888. return _this;
  50889. }
  50890. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  50891. get: function () {
  50892. return this._blurRatio;
  50893. },
  50894. set: function (value) {
  50895. if (this._blurRatio === value) {
  50896. return;
  50897. }
  50898. this._blurRatio = value;
  50899. this._preparePostProcesses();
  50900. },
  50901. enumerable: true,
  50902. configurable: true
  50903. });
  50904. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  50905. set: function (value) {
  50906. this._adaptiveBlurKernel = value;
  50907. this._autoComputeBlurKernel();
  50908. },
  50909. enumerable: true,
  50910. configurable: true
  50911. });
  50912. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  50913. set: function (value) {
  50914. this.blurKernelX = value;
  50915. this.blurKernelY = value;
  50916. },
  50917. enumerable: true,
  50918. configurable: true
  50919. });
  50920. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  50921. get: function () {
  50922. return this._blurKernelX;
  50923. },
  50924. set: function (value) {
  50925. if (this._blurKernelX === value) {
  50926. return;
  50927. }
  50928. this._blurKernelX = value;
  50929. this._preparePostProcesses();
  50930. },
  50931. enumerable: true,
  50932. configurable: true
  50933. });
  50934. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  50935. get: function () {
  50936. return this._blurKernelY;
  50937. },
  50938. set: function (value) {
  50939. if (this._blurKernelY === value) {
  50940. return;
  50941. }
  50942. this._blurKernelY = value;
  50943. this._preparePostProcesses();
  50944. },
  50945. enumerable: true,
  50946. configurable: true
  50947. });
  50948. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  50949. var engine = this.getScene().getEngine();
  50950. var dw = this.getRenderWidth() / engine.getRenderWidth();
  50951. var dh = this.getRenderHeight() / engine.getRenderHeight();
  50952. this.blurKernelX = this._adaptiveBlurKernel * dw;
  50953. this.blurKernelY = this._adaptiveBlurKernel * dh;
  50954. };
  50955. MirrorTexture.prototype._onRatioRescale = function () {
  50956. if (this._sizeRatio) {
  50957. this.resize(this._initialSizeParameter);
  50958. if (!this._adaptiveBlurKernel) {
  50959. this._preparePostProcesses();
  50960. }
  50961. }
  50962. if (this._adaptiveBlurKernel) {
  50963. this._autoComputeBlurKernel();
  50964. }
  50965. };
  50966. MirrorTexture.prototype._preparePostProcesses = function () {
  50967. this.clearPostProcesses(true);
  50968. if (this._blurKernelX && this._blurKernelY) {
  50969. var engine = this.getScene().getEngine();
  50970. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  50971. 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);
  50972. this._blurX.autoClear = false;
  50973. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  50974. this._blurX.outputTexture = this._texture;
  50975. }
  50976. else {
  50977. this._blurX.alwaysForcePOT = true;
  50978. }
  50979. 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);
  50980. this._blurY.autoClear = false;
  50981. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  50982. this.addPostProcess(this._blurX);
  50983. this.addPostProcess(this._blurY);
  50984. }
  50985. else {
  50986. if (this._blurY) {
  50987. this.removePostProcess(this._blurY);
  50988. this._blurY.dispose();
  50989. this._blurY = null;
  50990. }
  50991. if (this._blurX) {
  50992. this.removePostProcess(this._blurX);
  50993. this._blurX.dispose();
  50994. this._blurX = null;
  50995. }
  50996. }
  50997. };
  50998. MirrorTexture.prototype.clone = function () {
  50999. var scene = this.getScene();
  51000. if (!scene) {
  51001. return this;
  51002. }
  51003. var textureSize = this.getSize();
  51004. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  51005. // Base texture
  51006. newTexture.hasAlpha = this.hasAlpha;
  51007. newTexture.level = this.level;
  51008. // Mirror Texture
  51009. newTexture.mirrorPlane = this.mirrorPlane.clone();
  51010. if (this.renderList) {
  51011. newTexture.renderList = this.renderList.slice(0);
  51012. }
  51013. return newTexture;
  51014. };
  51015. MirrorTexture.prototype.serialize = function () {
  51016. if (!this.name) {
  51017. return null;
  51018. }
  51019. var serializationObject = _super.prototype.serialize.call(this);
  51020. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  51021. return serializationObject;
  51022. };
  51023. return MirrorTexture;
  51024. }(BABYLON.RenderTargetTexture));
  51025. BABYLON.MirrorTexture = MirrorTexture;
  51026. })(BABYLON || (BABYLON = {}));
  51027. //# sourceMappingURL=babylon.mirrorTexture.js.map
  51028. var BABYLON;
  51029. (function (BABYLON) {
  51030. /**
  51031. * Creates a refraction texture used by refraction channel of the standard material.
  51032. * @param name the texture name
  51033. * @param size size of the underlying texture
  51034. * @param scene root scene
  51035. */
  51036. var RefractionTexture = /** @class */ (function (_super) {
  51037. __extends(RefractionTexture, _super);
  51038. function RefractionTexture(name, size, scene, generateMipMaps) {
  51039. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  51040. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  51041. _this.depth = 2.0;
  51042. _this.onBeforeRenderObservable.add(function () {
  51043. scene.clipPlane = _this.refractionPlane;
  51044. });
  51045. _this.onAfterRenderObservable.add(function () {
  51046. delete scene.clipPlane;
  51047. });
  51048. return _this;
  51049. }
  51050. RefractionTexture.prototype.clone = function () {
  51051. var scene = this.getScene();
  51052. if (!scene) {
  51053. return this;
  51054. }
  51055. var textureSize = this.getSize();
  51056. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  51057. // Base texture
  51058. newTexture.hasAlpha = this.hasAlpha;
  51059. newTexture.level = this.level;
  51060. // Refraction Texture
  51061. newTexture.refractionPlane = this.refractionPlane.clone();
  51062. if (this.renderList) {
  51063. newTexture.renderList = this.renderList.slice(0);
  51064. }
  51065. newTexture.depth = this.depth;
  51066. return newTexture;
  51067. };
  51068. RefractionTexture.prototype.serialize = function () {
  51069. if (!this.name) {
  51070. return null;
  51071. }
  51072. var serializationObject = _super.prototype.serialize.call(this);
  51073. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  51074. serializationObject.depth = this.depth;
  51075. return serializationObject;
  51076. };
  51077. return RefractionTexture;
  51078. }(BABYLON.RenderTargetTexture));
  51079. BABYLON.RefractionTexture = RefractionTexture;
  51080. })(BABYLON || (BABYLON = {}));
  51081. //# sourceMappingURL=babylon.refractionTexture.js.map
  51082. var BABYLON;
  51083. (function (BABYLON) {
  51084. var DynamicTexture = /** @class */ (function (_super) {
  51085. __extends(DynamicTexture, _super);
  51086. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  51087. if (scene === void 0) { scene = null; }
  51088. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51089. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  51090. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  51091. _this.name = name;
  51092. _this._engine = _this.getScene().getEngine();
  51093. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51094. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51095. _this._generateMipMaps = generateMipMaps;
  51096. if (options.getContext) {
  51097. _this._canvas = options;
  51098. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  51099. }
  51100. else {
  51101. _this._canvas = document.createElement("canvas");
  51102. if (options.width) {
  51103. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  51104. }
  51105. else {
  51106. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  51107. }
  51108. }
  51109. var textureSize = _this.getSize();
  51110. _this._canvas.width = textureSize.width;
  51111. _this._canvas.height = textureSize.height;
  51112. _this._context = _this._canvas.getContext("2d");
  51113. return _this;
  51114. }
  51115. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  51116. get: function () {
  51117. return true;
  51118. },
  51119. enumerable: true,
  51120. configurable: true
  51121. });
  51122. DynamicTexture.prototype._recreate = function (textureSize) {
  51123. this._canvas.width = textureSize.width;
  51124. this._canvas.height = textureSize.height;
  51125. this.releaseInternalTexture();
  51126. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  51127. };
  51128. DynamicTexture.prototype.scale = function (ratio) {
  51129. var textureSize = this.getSize();
  51130. textureSize.width *= ratio;
  51131. textureSize.height *= ratio;
  51132. this._recreate(textureSize);
  51133. };
  51134. DynamicTexture.prototype.scaleTo = function (width, height) {
  51135. var textureSize = this.getSize();
  51136. textureSize.width = width;
  51137. textureSize.height = height;
  51138. this._recreate(textureSize);
  51139. };
  51140. DynamicTexture.prototype.getContext = function () {
  51141. return this._context;
  51142. };
  51143. DynamicTexture.prototype.clear = function () {
  51144. var size = this.getSize();
  51145. this._context.fillRect(0, 0, size.width, size.height);
  51146. };
  51147. DynamicTexture.prototype.update = function (invertY) {
  51148. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  51149. };
  51150. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  51151. if (update === void 0) { update = true; }
  51152. var size = this.getSize();
  51153. if (clearColor) {
  51154. this._context.fillStyle = clearColor;
  51155. this._context.fillRect(0, 0, size.width, size.height);
  51156. }
  51157. this._context.font = font;
  51158. if (x === null || x === undefined) {
  51159. var textSize = this._context.measureText(text);
  51160. x = (size.width - textSize.width) / 2;
  51161. }
  51162. if (y === null || y === undefined) {
  51163. var fontSize = parseInt((font.replace(/\D/g, '')));
  51164. ;
  51165. y = (size.height / 2) + (fontSize / 3.65);
  51166. }
  51167. this._context.fillStyle = color;
  51168. this._context.fillText(text, x, y);
  51169. if (update) {
  51170. this.update(invertY);
  51171. }
  51172. };
  51173. DynamicTexture.prototype.clone = function () {
  51174. var scene = this.getScene();
  51175. if (!scene) {
  51176. return this;
  51177. }
  51178. var textureSize = this.getSize();
  51179. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  51180. // Base texture
  51181. newTexture.hasAlpha = this.hasAlpha;
  51182. newTexture.level = this.level;
  51183. // Dynamic Texture
  51184. newTexture.wrapU = this.wrapU;
  51185. newTexture.wrapV = this.wrapV;
  51186. return newTexture;
  51187. };
  51188. DynamicTexture.prototype._rebuild = function () {
  51189. this.update();
  51190. };
  51191. return DynamicTexture;
  51192. }(BABYLON.Texture));
  51193. BABYLON.DynamicTexture = DynamicTexture;
  51194. })(BABYLON || (BABYLON = {}));
  51195. //# sourceMappingURL=babylon.dynamicTexture.js.map
  51196. var BABYLON;
  51197. (function (BABYLON) {
  51198. var VideoTexture = /** @class */ (function (_super) {
  51199. __extends(VideoTexture, _super);
  51200. /**
  51201. * Creates a video texture.
  51202. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  51203. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  51204. * @param {BABYLON.Scene} scene is obviously the current scene.
  51205. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  51206. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  51207. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  51208. */
  51209. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  51210. if (generateMipMaps === void 0) { generateMipMaps = false; }
  51211. if (invertY === void 0) { invertY = false; }
  51212. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51213. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  51214. _this._autoLaunch = true;
  51215. var urls = null;
  51216. _this.name = name;
  51217. if (urlsOrVideo instanceof HTMLVideoElement) {
  51218. _this.video = urlsOrVideo;
  51219. }
  51220. else {
  51221. urls = urlsOrVideo;
  51222. _this.video = document.createElement("video");
  51223. _this.video.autoplay = false;
  51224. _this.video.loop = true;
  51225. BABYLON.Tools.SetCorsBehavior(urls, _this.video);
  51226. }
  51227. _this._engine = _this.getScene().getEngine();
  51228. _this._generateMipMaps = generateMipMaps;
  51229. _this._samplingMode = samplingMode;
  51230. if (!_this._engine.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  51231. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  51232. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  51233. }
  51234. else {
  51235. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51236. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51237. _this._generateMipMaps = false;
  51238. }
  51239. if (urls) {
  51240. _this.video.addEventListener("canplay", function () {
  51241. _this._createTexture();
  51242. });
  51243. urls.forEach(function (url) {
  51244. var source = document.createElement("source");
  51245. source.src = url;
  51246. _this.video.appendChild(source);
  51247. });
  51248. }
  51249. else {
  51250. _this._createTexture();
  51251. }
  51252. _this._lastUpdate = BABYLON.Tools.Now;
  51253. return _this;
  51254. }
  51255. VideoTexture.prototype.__setTextureReady = function () {
  51256. if (this._texture) {
  51257. this._texture.isReady = true;
  51258. }
  51259. };
  51260. VideoTexture.prototype._createTexture = function () {
  51261. this._texture = this._engine.createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  51262. if (this._autoLaunch) {
  51263. this._autoLaunch = false;
  51264. this.video.play();
  51265. }
  51266. this._setTextureReady = this.__setTextureReady.bind(this);
  51267. this.video.addEventListener("playing", this._setTextureReady);
  51268. };
  51269. VideoTexture.prototype._rebuild = function () {
  51270. this.update();
  51271. };
  51272. VideoTexture.prototype.update = function () {
  51273. var now = BABYLON.Tools.Now;
  51274. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  51275. return false;
  51276. }
  51277. this._lastUpdate = now;
  51278. this._engine.updateVideoTexture(this._texture, this.video, this._invertY);
  51279. return true;
  51280. };
  51281. VideoTexture.prototype.dispose = function () {
  51282. _super.prototype.dispose.call(this);
  51283. this.video.removeEventListener("playing", this._setTextureReady);
  51284. };
  51285. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  51286. var video = document.createElement("video");
  51287. var constraintsDeviceId;
  51288. if (constraints && constraints.deviceId) {
  51289. constraintsDeviceId = {
  51290. exact: constraints.deviceId
  51291. };
  51292. }
  51293. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  51294. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  51295. if (navigator.getUserMedia) {
  51296. navigator.getUserMedia({
  51297. video: {
  51298. deviceId: constraintsDeviceId,
  51299. width: {
  51300. min: (constraints && constraints.minWidth) || 256,
  51301. max: (constraints && constraints.maxWidth) || 640
  51302. },
  51303. height: {
  51304. min: (constraints && constraints.minHeight) || 256,
  51305. max: (constraints && constraints.maxHeight) || 480
  51306. }
  51307. }
  51308. }, function (stream) {
  51309. if (video.mozSrcObject !== undefined) {
  51310. video.mozSrcObject = stream;
  51311. }
  51312. else {
  51313. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  51314. }
  51315. video.play();
  51316. if (onReady) {
  51317. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  51318. }
  51319. }, function (e) {
  51320. BABYLON.Tools.Error(e.name);
  51321. });
  51322. }
  51323. };
  51324. return VideoTexture;
  51325. }(BABYLON.Texture));
  51326. BABYLON.VideoTexture = VideoTexture;
  51327. })(BABYLON || (BABYLON = {}));
  51328. //# sourceMappingURL=babylon.videoTexture.js.map
  51329. var BABYLON;
  51330. (function (BABYLON) {
  51331. var RawTexture = /** @class */ (function (_super) {
  51332. __extends(RawTexture, _super);
  51333. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  51334. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51335. if (invertY === void 0) { invertY = false; }
  51336. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51337. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51338. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  51339. _this.format = format;
  51340. _this._engine = scene.getEngine();
  51341. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  51342. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51343. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51344. return _this;
  51345. }
  51346. RawTexture.prototype.update = function (data) {
  51347. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  51348. };
  51349. // Statics
  51350. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51351. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51352. if (invertY === void 0) { invertY = false; }
  51353. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51354. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  51355. };
  51356. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51357. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51358. if (invertY === void 0) { invertY = false; }
  51359. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51360. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  51361. };
  51362. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51363. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51364. if (invertY === void 0) { invertY = false; }
  51365. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51366. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  51367. };
  51368. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  51369. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51370. if (invertY === void 0) { invertY = false; }
  51371. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51372. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51373. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  51374. };
  51375. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  51376. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51377. if (invertY === void 0) { invertY = false; }
  51378. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51379. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51380. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  51381. };
  51382. return RawTexture;
  51383. }(BABYLON.Texture));
  51384. BABYLON.RawTexture = RawTexture;
  51385. })(BABYLON || (BABYLON = {}));
  51386. //# sourceMappingURL=babylon.rawTexture.js.map
  51387. var BABYLON;
  51388. (function (BABYLON) {
  51389. var PostProcess = /** @class */ (function () {
  51390. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  51391. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  51392. if (defines === void 0) { defines = null; }
  51393. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51394. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  51395. if (blockCompilation === void 0) { blockCompilation = false; }
  51396. this.name = name;
  51397. this.width = -1;
  51398. this.height = -1;
  51399. this.autoClear = true;
  51400. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  51401. this.animations = new Array();
  51402. /*
  51403. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  51404. Can only be used on a single postprocess or on the last one of a chain.
  51405. */
  51406. this.enablePixelPerfectMode = false;
  51407. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  51408. this.alwaysForcePOT = false;
  51409. this.samples = 1;
  51410. this.adaptScaleToCurrentViewport = false;
  51411. this._reusable = false;
  51412. this._textures = new BABYLON.SmartArray(2);
  51413. this._currentRenderTextureInd = 0;
  51414. this._scaleRatio = new BABYLON.Vector2(1, 1);
  51415. this._texelSize = BABYLON.Vector2.Zero();
  51416. // Events
  51417. /**
  51418. * An event triggered when the postprocess is activated.
  51419. * @type {BABYLON.Observable}
  51420. */
  51421. this.onActivateObservable = new BABYLON.Observable();
  51422. /**
  51423. * An event triggered when the postprocess changes its size.
  51424. * @type {BABYLON.Observable}
  51425. */
  51426. this.onSizeChangedObservable = new BABYLON.Observable();
  51427. /**
  51428. * An event triggered when the postprocess applies its effect.
  51429. * @type {BABYLON.Observable}
  51430. */
  51431. this.onApplyObservable = new BABYLON.Observable();
  51432. /**
  51433. * An event triggered before rendering the postprocess
  51434. * @type {BABYLON.Observable}
  51435. */
  51436. this.onBeforeRenderObservable = new BABYLON.Observable();
  51437. /**
  51438. * An event triggered after rendering the postprocess
  51439. * @type {BABYLON.Observable}
  51440. */
  51441. this.onAfterRenderObservable = new BABYLON.Observable();
  51442. if (camera != null) {
  51443. this._camera = camera;
  51444. this._scene = camera.getScene();
  51445. camera.attachPostProcess(this);
  51446. this._engine = this._scene.getEngine();
  51447. this._scene.postProcesses.push(this);
  51448. }
  51449. else if (engine) {
  51450. this._engine = engine;
  51451. this._engine.postProcesses.push(this);
  51452. }
  51453. this._options = options;
  51454. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  51455. this._reusable = reusable || false;
  51456. this._textureType = textureType;
  51457. this._samplers = samplers || [];
  51458. this._samplers.push("textureSampler");
  51459. this._fragmentUrl = fragmentUrl;
  51460. this._vertexUrl = vertexUrl;
  51461. this._parameters = parameters || [];
  51462. this._parameters.push("scale");
  51463. this._indexParameters = indexParameters;
  51464. if (!blockCompilation) {
  51465. this.updateEffect(defines);
  51466. }
  51467. }
  51468. Object.defineProperty(PostProcess.prototype, "onActivate", {
  51469. set: function (callback) {
  51470. if (this._onActivateObserver) {
  51471. this.onActivateObservable.remove(this._onActivateObserver);
  51472. }
  51473. if (callback) {
  51474. this._onActivateObserver = this.onActivateObservable.add(callback);
  51475. }
  51476. },
  51477. enumerable: true,
  51478. configurable: true
  51479. });
  51480. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  51481. set: function (callback) {
  51482. if (this._onSizeChangedObserver) {
  51483. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  51484. }
  51485. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  51486. },
  51487. enumerable: true,
  51488. configurable: true
  51489. });
  51490. Object.defineProperty(PostProcess.prototype, "onApply", {
  51491. set: function (callback) {
  51492. if (this._onApplyObserver) {
  51493. this.onApplyObservable.remove(this._onApplyObserver);
  51494. }
  51495. this._onApplyObserver = this.onApplyObservable.add(callback);
  51496. },
  51497. enumerable: true,
  51498. configurable: true
  51499. });
  51500. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  51501. set: function (callback) {
  51502. if (this._onBeforeRenderObserver) {
  51503. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  51504. }
  51505. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  51506. },
  51507. enumerable: true,
  51508. configurable: true
  51509. });
  51510. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  51511. set: function (callback) {
  51512. if (this._onAfterRenderObserver) {
  51513. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  51514. }
  51515. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  51516. },
  51517. enumerable: true,
  51518. configurable: true
  51519. });
  51520. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  51521. get: function () {
  51522. return this._textures.data[this._currentRenderTextureInd];
  51523. },
  51524. set: function (value) {
  51525. this._forcedOutputTexture = value;
  51526. },
  51527. enumerable: true,
  51528. configurable: true
  51529. });
  51530. PostProcess.prototype.getCamera = function () {
  51531. return this._camera;
  51532. };
  51533. Object.defineProperty(PostProcess.prototype, "texelSize", {
  51534. get: function () {
  51535. if (this._shareOutputWithPostProcess) {
  51536. return this._shareOutputWithPostProcess.texelSize;
  51537. }
  51538. if (this._forcedOutputTexture) {
  51539. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  51540. }
  51541. return this._texelSize;
  51542. },
  51543. enumerable: true,
  51544. configurable: true
  51545. });
  51546. PostProcess.prototype.getEngine = function () {
  51547. return this._engine;
  51548. };
  51549. PostProcess.prototype.getEffect = function () {
  51550. return this._effect;
  51551. };
  51552. PostProcess.prototype.shareOutputWith = function (postProcess) {
  51553. this._disposeTextures();
  51554. this._shareOutputWithPostProcess = postProcess;
  51555. return this;
  51556. };
  51557. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  51558. if (defines === void 0) { defines = null; }
  51559. if (uniforms === void 0) { uniforms = null; }
  51560. if (samplers === void 0) { samplers = null; }
  51561. 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);
  51562. };
  51563. PostProcess.prototype.isReusable = function () {
  51564. return this._reusable;
  51565. };
  51566. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  51567. PostProcess.prototype.markTextureDirty = function () {
  51568. this.width = -1;
  51569. };
  51570. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  51571. var _this = this;
  51572. if (sourceTexture === void 0) { sourceTexture = null; }
  51573. camera = camera || this._camera;
  51574. var scene = camera.getScene();
  51575. var engine = scene.getEngine();
  51576. var maxSize = engine.getCaps().maxTextureSize;
  51577. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  51578. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  51579. var desiredWidth = (this._options.width || requiredWidth);
  51580. var desiredHeight = this._options.height || requiredHeight;
  51581. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  51582. if (this.adaptScaleToCurrentViewport) {
  51583. var currentViewport = engine.currentViewport;
  51584. if (currentViewport) {
  51585. desiredWidth *= currentViewport.width;
  51586. desiredHeight *= currentViewport.height;
  51587. }
  51588. }
  51589. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  51590. if (!this._options.width) {
  51591. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  51592. }
  51593. if (!this._options.height) {
  51594. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  51595. }
  51596. }
  51597. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  51598. if (this._textures.length > 0) {
  51599. for (var i = 0; i < this._textures.length; i++) {
  51600. this._engine._releaseTexture(this._textures.data[i]);
  51601. }
  51602. this._textures.reset();
  51603. }
  51604. this.width = desiredWidth;
  51605. this.height = desiredHeight;
  51606. var textureSize = { width: this.width, height: this.height };
  51607. var textureOptions = {
  51608. generateMipMaps: false,
  51609. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  51610. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  51611. samplingMode: this.renderTargetSamplingMode,
  51612. type: this._textureType
  51613. };
  51614. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  51615. if (this._reusable) {
  51616. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  51617. }
  51618. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  51619. this.onSizeChangedObservable.notifyObservers(this);
  51620. }
  51621. this._textures.forEach(function (texture) {
  51622. if (texture.samples !== _this.samples) {
  51623. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  51624. }
  51625. });
  51626. }
  51627. var target;
  51628. if (this._shareOutputWithPostProcess) {
  51629. target = this._shareOutputWithPostProcess.outputTexture;
  51630. }
  51631. else if (this._forcedOutputTexture) {
  51632. target = this._forcedOutputTexture;
  51633. this.width = this._forcedOutputTexture.width;
  51634. this.height = this._forcedOutputTexture.height;
  51635. }
  51636. else {
  51637. target = this.outputTexture;
  51638. }
  51639. if (this.enablePixelPerfectMode) {
  51640. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  51641. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  51642. }
  51643. else {
  51644. this._scaleRatio.copyFromFloats(1, 1);
  51645. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  51646. }
  51647. this.onActivateObservable.notifyObservers(camera);
  51648. // Clear
  51649. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  51650. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  51651. }
  51652. if (this._reusable) {
  51653. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  51654. }
  51655. };
  51656. Object.defineProperty(PostProcess.prototype, "isSupported", {
  51657. get: function () {
  51658. return this._effect.isSupported;
  51659. },
  51660. enumerable: true,
  51661. configurable: true
  51662. });
  51663. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  51664. get: function () {
  51665. if (this._shareOutputWithPostProcess) {
  51666. return this._shareOutputWithPostProcess.aspectRatio;
  51667. }
  51668. if (this._forcedOutputTexture) {
  51669. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  51670. }
  51671. return this.width / this.height;
  51672. },
  51673. enumerable: true,
  51674. configurable: true
  51675. });
  51676. PostProcess.prototype.apply = function () {
  51677. // Check
  51678. if (!this._effect || !this._effect.isReady())
  51679. return null;
  51680. // States
  51681. this._engine.enableEffect(this._effect);
  51682. this._engine.setState(false);
  51683. this._engine.setDepthBuffer(false);
  51684. this._engine.setDepthWrite(false);
  51685. // Alpha
  51686. this._engine.setAlphaMode(this.alphaMode);
  51687. if (this.alphaConstants) {
  51688. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  51689. }
  51690. // Texture
  51691. var source;
  51692. if (this._shareOutputWithPostProcess) {
  51693. source = this._shareOutputWithPostProcess.outputTexture;
  51694. }
  51695. else if (this._forcedOutputTexture) {
  51696. source = this._forcedOutputTexture;
  51697. }
  51698. else {
  51699. source = this.outputTexture;
  51700. }
  51701. this._effect._bindTexture("textureSampler", source);
  51702. // Parameters
  51703. this._effect.setVector2("scale", this._scaleRatio);
  51704. this.onApplyObservable.notifyObservers(this._effect);
  51705. return this._effect;
  51706. };
  51707. PostProcess.prototype._disposeTextures = function () {
  51708. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  51709. return;
  51710. }
  51711. if (this._textures.length > 0) {
  51712. for (var i = 0; i < this._textures.length; i++) {
  51713. this._engine._releaseTexture(this._textures.data[i]);
  51714. }
  51715. }
  51716. this._textures.dispose();
  51717. };
  51718. PostProcess.prototype.dispose = function (camera) {
  51719. camera = camera || this._camera;
  51720. this._disposeTextures();
  51721. if (this._scene) {
  51722. var index_1 = this._scene.postProcesses.indexOf(this);
  51723. if (index_1 !== -1) {
  51724. this._scene.postProcesses.splice(index_1, 1);
  51725. }
  51726. }
  51727. else {
  51728. var index_2 = this._engine.postProcesses.indexOf(this);
  51729. if (index_2 !== -1) {
  51730. this._engine.postProcesses.splice(index_2, 1);
  51731. }
  51732. }
  51733. if (!camera) {
  51734. return;
  51735. }
  51736. camera.detachPostProcess(this);
  51737. var index = camera._postProcesses.indexOf(this);
  51738. if (index === 0 && camera._postProcesses.length > 0) {
  51739. this._camera._postProcesses[0].markTextureDirty();
  51740. }
  51741. this.onActivateObservable.clear();
  51742. this.onAfterRenderObservable.clear();
  51743. this.onApplyObservable.clear();
  51744. this.onBeforeRenderObservable.clear();
  51745. this.onSizeChangedObservable.clear();
  51746. };
  51747. return PostProcess;
  51748. }());
  51749. BABYLON.PostProcess = PostProcess;
  51750. })(BABYLON || (BABYLON = {}));
  51751. //# sourceMappingURL=babylon.postProcess.js.map
  51752. var BABYLON;
  51753. (function (BABYLON) {
  51754. var PassPostProcess = /** @class */ (function (_super) {
  51755. __extends(PassPostProcess, _super);
  51756. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  51757. if (camera === void 0) { camera = null; }
  51758. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51759. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  51760. }
  51761. return PassPostProcess;
  51762. }(BABYLON.PostProcess));
  51763. BABYLON.PassPostProcess = PassPostProcess;
  51764. })(BABYLON || (BABYLON = {}));
  51765. //# sourceMappingURL=babylon.passPostProcess.js.map
  51766. var __assign = (this && this.__assign) || Object.assign || function(t) {
  51767. for (var s, i = 1, n = arguments.length; i < n; i++) {
  51768. s = arguments[i];
  51769. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  51770. t[p] = s[p];
  51771. }
  51772. return t;
  51773. };
  51774. var BABYLON;
  51775. (function (BABYLON) {
  51776. var ShadowGenerator = /** @class */ (function () {
  51777. /**
  51778. * Creates a ShadowGenerator object.
  51779. * A ShadowGenerator is the required tool to use the shadows.
  51780. * Each light casting shadows needs to use its own ShadowGenerator.
  51781. * Required parameters :
  51782. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  51783. * - `light`: the light object generating the shadows.
  51784. * - `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.
  51785. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  51786. */
  51787. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  51788. // Members
  51789. this._bias = 0.00005;
  51790. this._blurBoxOffset = 1;
  51791. this._blurScale = 2;
  51792. this._blurKernel = 1;
  51793. this._useKernelBlur = false;
  51794. this._filter = ShadowGenerator.FILTER_NONE;
  51795. this._darkness = 0;
  51796. this._transparencyShadow = false;
  51797. /**
  51798. * Controls the extent to which the shadows fade out at the edge of the frustum
  51799. * Used only by directionals and spots
  51800. */
  51801. this.frustumEdgeFalloff = 0;
  51802. this.forceBackFacesOnly = false;
  51803. this._lightDirection = BABYLON.Vector3.Zero();
  51804. this._viewMatrix = BABYLON.Matrix.Zero();
  51805. this._projectionMatrix = BABYLON.Matrix.Zero();
  51806. this._transformMatrix = BABYLON.Matrix.Zero();
  51807. this._currentFaceIndex = 0;
  51808. this._currentFaceIndexCache = 0;
  51809. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  51810. this._mapSize = mapSize;
  51811. this._light = light;
  51812. this._scene = light.getScene();
  51813. light._shadowGenerator = this;
  51814. // Texture type fallback from float to int if not supported.
  51815. var caps = this._scene.getEngine().getCaps();
  51816. if (!useFullFloatFirst) {
  51817. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  51818. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  51819. }
  51820. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  51821. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  51822. }
  51823. else {
  51824. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  51825. }
  51826. }
  51827. else {
  51828. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  51829. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  51830. }
  51831. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  51832. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  51833. }
  51834. else {
  51835. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  51836. }
  51837. }
  51838. this._initializeGenerator();
  51839. }
  51840. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  51841. // Static
  51842. get: function () {
  51843. return ShadowGenerator._FILTER_NONE;
  51844. },
  51845. enumerable: true,
  51846. configurable: true
  51847. });
  51848. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  51849. get: function () {
  51850. return ShadowGenerator._FILTER_POISSONSAMPLING;
  51851. },
  51852. enumerable: true,
  51853. configurable: true
  51854. });
  51855. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  51856. get: function () {
  51857. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  51858. },
  51859. enumerable: true,
  51860. configurable: true
  51861. });
  51862. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  51863. get: function () {
  51864. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  51865. },
  51866. enumerable: true,
  51867. configurable: true
  51868. });
  51869. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  51870. get: function () {
  51871. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  51872. },
  51873. enumerable: true,
  51874. configurable: true
  51875. });
  51876. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  51877. get: function () {
  51878. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  51879. },
  51880. enumerable: true,
  51881. configurable: true
  51882. });
  51883. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  51884. get: function () {
  51885. return this._bias;
  51886. },
  51887. set: function (bias) {
  51888. this._bias = bias;
  51889. },
  51890. enumerable: true,
  51891. configurable: true
  51892. });
  51893. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  51894. get: function () {
  51895. return this._blurBoxOffset;
  51896. },
  51897. set: function (value) {
  51898. if (this._blurBoxOffset === value) {
  51899. return;
  51900. }
  51901. this._blurBoxOffset = value;
  51902. this._disposeBlurPostProcesses();
  51903. },
  51904. enumerable: true,
  51905. configurable: true
  51906. });
  51907. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  51908. get: function () {
  51909. return this._blurScale;
  51910. },
  51911. set: function (value) {
  51912. if (this._blurScale === value) {
  51913. return;
  51914. }
  51915. this._blurScale = value;
  51916. this._disposeBlurPostProcesses();
  51917. },
  51918. enumerable: true,
  51919. configurable: true
  51920. });
  51921. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  51922. get: function () {
  51923. return this._blurKernel;
  51924. },
  51925. set: function (value) {
  51926. if (this._blurKernel === value) {
  51927. return;
  51928. }
  51929. this._blurKernel = value;
  51930. this._disposeBlurPostProcesses();
  51931. },
  51932. enumerable: true,
  51933. configurable: true
  51934. });
  51935. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  51936. get: function () {
  51937. return this._useKernelBlur;
  51938. },
  51939. set: function (value) {
  51940. if (this._useKernelBlur === value) {
  51941. return;
  51942. }
  51943. this._useKernelBlur = value;
  51944. this._disposeBlurPostProcesses();
  51945. },
  51946. enumerable: true,
  51947. configurable: true
  51948. });
  51949. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  51950. get: function () {
  51951. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  51952. },
  51953. set: function (value) {
  51954. this._depthScale = value;
  51955. },
  51956. enumerable: true,
  51957. configurable: true
  51958. });
  51959. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  51960. get: function () {
  51961. return this._filter;
  51962. },
  51963. set: function (value) {
  51964. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  51965. if (this._light.needCube()) {
  51966. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  51967. this.useExponentialShadowMap = true;
  51968. return;
  51969. }
  51970. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  51971. this.useCloseExponentialShadowMap = true;
  51972. return;
  51973. }
  51974. }
  51975. if (this._filter === value) {
  51976. return;
  51977. }
  51978. this._filter = value;
  51979. this._disposeBlurPostProcesses();
  51980. this._applyFilterValues();
  51981. this._light._markMeshesAsLightDirty();
  51982. },
  51983. enumerable: true,
  51984. configurable: true
  51985. });
  51986. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  51987. get: function () {
  51988. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  51989. },
  51990. set: function (value) {
  51991. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  51992. return;
  51993. }
  51994. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  51995. },
  51996. enumerable: true,
  51997. configurable: true
  51998. });
  51999. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  52000. get: function () {
  52001. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  52002. return this.useExponentialShadowMap;
  52003. },
  52004. set: function (value) {
  52005. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  52006. this.useExponentialShadowMap = value;
  52007. },
  52008. enumerable: true,
  52009. configurable: true
  52010. });
  52011. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  52012. get: function () {
  52013. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  52014. return this.useBlurExponentialShadowMap;
  52015. },
  52016. set: function (value) {
  52017. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  52018. this.useBlurExponentialShadowMap = value;
  52019. },
  52020. enumerable: true,
  52021. configurable: true
  52022. });
  52023. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  52024. get: function () {
  52025. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  52026. },
  52027. set: function (value) {
  52028. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  52029. return;
  52030. }
  52031. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  52032. },
  52033. enumerable: true,
  52034. configurable: true
  52035. });
  52036. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  52037. get: function () {
  52038. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  52039. },
  52040. set: function (value) {
  52041. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  52042. return;
  52043. }
  52044. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  52045. },
  52046. enumerable: true,
  52047. configurable: true
  52048. });
  52049. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  52050. get: function () {
  52051. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  52052. },
  52053. set: function (value) {
  52054. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  52055. return;
  52056. }
  52057. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  52058. },
  52059. enumerable: true,
  52060. configurable: true
  52061. });
  52062. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  52063. get: function () {
  52064. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  52065. },
  52066. set: function (value) {
  52067. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  52068. return;
  52069. }
  52070. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  52071. },
  52072. enumerable: true,
  52073. configurable: true
  52074. });
  52075. /**
  52076. * Returns the darkness value (float).
  52077. */
  52078. ShadowGenerator.prototype.getDarkness = function () {
  52079. return this._darkness;
  52080. };
  52081. /**
  52082. * Sets the ShadowGenerator darkness value (float <= 1.0).
  52083. * Returns the ShadowGenerator.
  52084. */
  52085. ShadowGenerator.prototype.setDarkness = function (darkness) {
  52086. if (darkness >= 1.0)
  52087. this._darkness = 1.0;
  52088. else if (darkness <= 0.0)
  52089. this._darkness = 0.0;
  52090. else
  52091. this._darkness = darkness;
  52092. return this;
  52093. };
  52094. /**
  52095. * Sets the ability to have transparent shadow (boolean).
  52096. * Returns the ShadowGenerator.
  52097. */
  52098. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  52099. this._transparencyShadow = hasShadow;
  52100. return this;
  52101. };
  52102. /**
  52103. * Returns a RenderTargetTexture object : the shadow map texture.
  52104. */
  52105. ShadowGenerator.prototype.getShadowMap = function () {
  52106. return this._shadowMap;
  52107. };
  52108. /**
  52109. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  52110. */
  52111. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  52112. if (this._shadowMap2) {
  52113. return this._shadowMap2;
  52114. }
  52115. return this._shadowMap;
  52116. };
  52117. /**
  52118. * Helper function to add a mesh and its descendants to the list of shadow casters
  52119. * @param mesh Mesh to add
  52120. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  52121. */
  52122. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  52123. if (includeDescendants === void 0) { includeDescendants = true; }
  52124. if (!this._shadowMap) {
  52125. return this;
  52126. }
  52127. if (!this._shadowMap.renderList) {
  52128. this._shadowMap.renderList = [];
  52129. }
  52130. this._shadowMap.renderList.push(mesh);
  52131. if (includeDescendants) {
  52132. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  52133. }
  52134. return this;
  52135. var _a;
  52136. };
  52137. /**
  52138. * Helper function to remove a mesh and its descendants from the list of shadow casters
  52139. * @param mesh Mesh to remove
  52140. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  52141. */
  52142. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  52143. if (includeDescendants === void 0) { includeDescendants = true; }
  52144. if (!this._shadowMap || !this._shadowMap.renderList) {
  52145. return this;
  52146. }
  52147. var index = this._shadowMap.renderList.indexOf(mesh);
  52148. if (index !== -1) {
  52149. this._shadowMap.renderList.splice(index, 1);
  52150. }
  52151. if (includeDescendants) {
  52152. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  52153. var child = _a[_i];
  52154. this.removeShadowCaster(child);
  52155. }
  52156. }
  52157. return this;
  52158. };
  52159. /**
  52160. * Returns the associated light object.
  52161. */
  52162. ShadowGenerator.prototype.getLight = function () {
  52163. return this._light;
  52164. };
  52165. ShadowGenerator.prototype._initializeGenerator = function () {
  52166. this._light._markMeshesAsLightDirty();
  52167. this._initializeShadowMap();
  52168. };
  52169. ShadowGenerator.prototype._initializeShadowMap = function () {
  52170. var _this = this;
  52171. // Render target
  52172. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  52173. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52174. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52175. this._shadowMap.anisotropicFilteringLevel = 1;
  52176. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52177. this._shadowMap.renderParticles = false;
  52178. this._shadowMap.ignoreCameraViewport = true;
  52179. // Record Face Index before render.
  52180. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  52181. _this._currentFaceIndex = faceIndex;
  52182. });
  52183. // Custom render function.
  52184. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  52185. // Blur if required afer render.
  52186. this._shadowMap.onAfterUnbindObservable.add(function () {
  52187. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  52188. return;
  52189. }
  52190. if (!_this._blurPostProcesses || !_this._blurPostProcesses.length) {
  52191. _this._initializeBlurRTTAndPostProcesses();
  52192. }
  52193. var shadowMap = _this.getShadowMapForRendering();
  52194. if (shadowMap) {
  52195. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  52196. }
  52197. });
  52198. // Clear according to the chosen filter.
  52199. this._shadowMap.onClearObservable.add(function (engine) {
  52200. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  52201. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  52202. }
  52203. else {
  52204. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  52205. }
  52206. });
  52207. };
  52208. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  52209. var _this = this;
  52210. var engine = this._scene.getEngine();
  52211. var targetSize = this._mapSize / this.blurScale;
  52212. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  52213. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  52214. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52215. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52216. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52217. }
  52218. if (this.useKernelBlur) {
  52219. 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);
  52220. this._kernelBlurXPostprocess.width = targetSize;
  52221. this._kernelBlurXPostprocess.height = targetSize;
  52222. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  52223. effect.setTexture("textureSampler", _this._shadowMap);
  52224. });
  52225. 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);
  52226. this._kernelBlurXPostprocess.autoClear = false;
  52227. this._kernelBlurYPostprocess.autoClear = false;
  52228. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  52229. this._kernelBlurXPostprocess.packedFloat = true;
  52230. this._kernelBlurYPostprocess.packedFloat = true;
  52231. }
  52232. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  52233. }
  52234. else {
  52235. 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);
  52236. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  52237. effect.setFloat2("screenSize", targetSize, targetSize);
  52238. effect.setTexture("textureSampler", _this._shadowMap);
  52239. });
  52240. this._boxBlurPostprocess.autoClear = false;
  52241. this._blurPostProcesses = [this._boxBlurPostprocess];
  52242. }
  52243. };
  52244. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  52245. var index;
  52246. var engine = this._scene.getEngine();
  52247. if (depthOnlySubMeshes.length) {
  52248. engine.setColorWrite(false);
  52249. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  52250. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  52251. }
  52252. engine.setColorWrite(true);
  52253. }
  52254. for (index = 0; index < opaqueSubMeshes.length; index++) {
  52255. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  52256. }
  52257. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  52258. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  52259. }
  52260. if (this._transparencyShadow) {
  52261. for (index = 0; index < transparentSubMeshes.length; index++) {
  52262. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  52263. }
  52264. }
  52265. };
  52266. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  52267. var _this = this;
  52268. var mesh = subMesh.getRenderingMesh();
  52269. var scene = this._scene;
  52270. var engine = scene.getEngine();
  52271. var material = subMesh.getMaterial();
  52272. if (!material) {
  52273. return;
  52274. }
  52275. // Culling
  52276. engine.setState(material.backFaceCulling);
  52277. // Managing instances
  52278. var batch = mesh._getInstancesRenderList(subMesh._id);
  52279. if (batch.mustReturn) {
  52280. return;
  52281. }
  52282. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  52283. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  52284. engine.enableEffect(this._effect);
  52285. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  52286. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  52287. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  52288. this._effect.setVector3("lightPosition", this.getLight().position);
  52289. if (scene.activeCamera) {
  52290. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  52291. }
  52292. // Alpha test
  52293. if (material && material.needAlphaTesting()) {
  52294. var alphaTexture = material.getAlphaTestTexture();
  52295. if (alphaTexture) {
  52296. this._effect.setTexture("diffuseSampler", alphaTexture);
  52297. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  52298. }
  52299. }
  52300. // Bones
  52301. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52302. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  52303. }
  52304. if (this.forceBackFacesOnly) {
  52305. engine.setState(true, 0, false, true);
  52306. }
  52307. // Draw
  52308. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  52309. if (this.forceBackFacesOnly) {
  52310. engine.setState(true, 0, false, false);
  52311. }
  52312. }
  52313. else {
  52314. // Need to reset refresh rate of the shadowMap
  52315. if (this._shadowMap) {
  52316. this._shadowMap.resetRefreshCounter();
  52317. }
  52318. }
  52319. };
  52320. ShadowGenerator.prototype._applyFilterValues = function () {
  52321. if (!this._shadowMap) {
  52322. return;
  52323. }
  52324. if (this.filter === ShadowGenerator.FILTER_NONE) {
  52325. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  52326. }
  52327. else {
  52328. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52329. }
  52330. };
  52331. /**
  52332. * Force shader compilation including textures ready check
  52333. */
  52334. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  52335. var _this = this;
  52336. var localOptions = __assign({ useInstances: false }, options);
  52337. var shadowMap = this.getShadowMap();
  52338. if (!shadowMap) {
  52339. if (onCompiled) {
  52340. onCompiled(this);
  52341. }
  52342. return;
  52343. }
  52344. var renderList = shadowMap.renderList;
  52345. if (!renderList) {
  52346. if (onCompiled) {
  52347. onCompiled(this);
  52348. }
  52349. return;
  52350. }
  52351. var subMeshes = new Array();
  52352. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  52353. var mesh = renderList_1[_i];
  52354. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  52355. }
  52356. if (subMeshes.length === 0) {
  52357. if (onCompiled) {
  52358. onCompiled(this);
  52359. }
  52360. return;
  52361. }
  52362. var currentIndex = 0;
  52363. var checkReady = function () {
  52364. if (!_this._scene || !_this._scene.getEngine()) {
  52365. return;
  52366. }
  52367. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  52368. currentIndex++;
  52369. if (currentIndex >= subMeshes.length) {
  52370. if (onCompiled) {
  52371. onCompiled(_this);
  52372. }
  52373. return;
  52374. }
  52375. }
  52376. setTimeout(checkReady, 16);
  52377. };
  52378. checkReady();
  52379. };
  52380. /**
  52381. * Boolean : true when the ShadowGenerator is finally computed.
  52382. */
  52383. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  52384. var defines = [];
  52385. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  52386. defines.push("#define FLOAT");
  52387. }
  52388. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  52389. defines.push("#define ESM");
  52390. }
  52391. var attribs = [BABYLON.VertexBuffer.PositionKind];
  52392. var mesh = subMesh.getMesh();
  52393. var material = subMesh.getMaterial();
  52394. // Alpha test
  52395. if (material && material.needAlphaTesting()) {
  52396. var alphaTexture = material.getAlphaTestTexture();
  52397. if (alphaTexture) {
  52398. defines.push("#define ALPHATEST");
  52399. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  52400. attribs.push(BABYLON.VertexBuffer.UVKind);
  52401. defines.push("#define UV1");
  52402. }
  52403. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  52404. if (alphaTexture.coordinatesIndex === 1) {
  52405. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  52406. defines.push("#define UV2");
  52407. }
  52408. }
  52409. }
  52410. }
  52411. // Bones
  52412. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52413. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52414. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52415. if (mesh.numBoneInfluencers > 4) {
  52416. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  52417. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  52418. }
  52419. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52420. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52421. }
  52422. else {
  52423. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52424. }
  52425. // Instances
  52426. if (useInstances) {
  52427. defines.push("#define INSTANCES");
  52428. attribs.push("world0");
  52429. attribs.push("world1");
  52430. attribs.push("world2");
  52431. attribs.push("world3");
  52432. }
  52433. // Get correct effect
  52434. var join = defines.join("\n");
  52435. if (this._cachedDefines !== join) {
  52436. this._cachedDefines = join;
  52437. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  52438. }
  52439. return this._effect.isReady();
  52440. };
  52441. /**
  52442. * This creates the defines related to the standard BJS materials.
  52443. */
  52444. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  52445. var scene = this._scene;
  52446. var light = this._light;
  52447. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  52448. return;
  52449. }
  52450. defines["SHADOW" + lightIndex] = true;
  52451. if (this.usePoissonSampling) {
  52452. defines["SHADOWPCF" + lightIndex] = true;
  52453. }
  52454. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  52455. defines["SHADOWESM" + lightIndex] = true;
  52456. }
  52457. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  52458. defines["SHADOWCLOSEESM" + lightIndex] = true;
  52459. }
  52460. if (light.needCube()) {
  52461. defines["SHADOWCUBE" + lightIndex] = true;
  52462. }
  52463. };
  52464. /**
  52465. * This binds shadow lights related to the standard BJS materials.
  52466. * It implies the unifroms available on the materials are the standard BJS ones.
  52467. */
  52468. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  52469. var light = this._light;
  52470. var scene = this._scene;
  52471. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  52472. return;
  52473. }
  52474. var camera = scene.activeCamera;
  52475. if (!camera) {
  52476. return;
  52477. }
  52478. var shadowMap = this.getShadowMap();
  52479. if (!shadowMap) {
  52480. return;
  52481. }
  52482. if (!light.needCube()) {
  52483. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  52484. }
  52485. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  52486. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  52487. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  52488. };
  52489. // Methods
  52490. /**
  52491. * Returns a Matrix object : the updated transformation matrix.
  52492. */
  52493. ShadowGenerator.prototype.getTransformMatrix = function () {
  52494. var scene = this._scene;
  52495. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  52496. return this._transformMatrix;
  52497. }
  52498. this._currentRenderID = scene.getRenderId();
  52499. this._currentFaceIndexCache = this._currentFaceIndex;
  52500. var lightPosition = this._light.position;
  52501. if (this._light.computeTransformedInformation()) {
  52502. lightPosition = this._light.transformedPosition;
  52503. }
  52504. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  52505. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  52506. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  52507. }
  52508. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  52509. this._cachedPosition = lightPosition.clone();
  52510. this._cachedDirection = this._lightDirection.clone();
  52511. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  52512. var shadowMap = this.getShadowMap();
  52513. if (shadowMap) {
  52514. var renderList = shadowMap.renderList;
  52515. if (renderList) {
  52516. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  52517. }
  52518. }
  52519. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  52520. }
  52521. return this._transformMatrix;
  52522. };
  52523. ShadowGenerator.prototype.recreateShadowMap = function () {
  52524. var shadowMap = this._shadowMap;
  52525. if (!shadowMap) {
  52526. return;
  52527. }
  52528. // Track render list.
  52529. var renderList = shadowMap.renderList;
  52530. // Clean up existing data.
  52531. this._disposeRTTandPostProcesses();
  52532. // Reinitializes.
  52533. this._initializeGenerator();
  52534. // Reaffect the filter to ensure a correct fallback if necessary.
  52535. this.filter = this.filter;
  52536. // Reaffect the filter.
  52537. this._applyFilterValues();
  52538. // Reaffect Render List.
  52539. this._shadowMap.renderList = renderList;
  52540. };
  52541. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  52542. if (this._shadowMap2) {
  52543. this._shadowMap2.dispose();
  52544. this._shadowMap2 = null;
  52545. }
  52546. if (this._downSamplePostprocess) {
  52547. this._downSamplePostprocess.dispose();
  52548. this._downSamplePostprocess = null;
  52549. }
  52550. if (this._boxBlurPostprocess) {
  52551. this._boxBlurPostprocess.dispose();
  52552. this._boxBlurPostprocess = null;
  52553. }
  52554. if (this._kernelBlurXPostprocess) {
  52555. this._kernelBlurXPostprocess.dispose();
  52556. this._kernelBlurXPostprocess = null;
  52557. }
  52558. if (this._kernelBlurYPostprocess) {
  52559. this._kernelBlurYPostprocess.dispose();
  52560. this._kernelBlurYPostprocess = null;
  52561. }
  52562. this._blurPostProcesses = [];
  52563. };
  52564. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  52565. if (this._shadowMap) {
  52566. this._shadowMap.dispose();
  52567. this._shadowMap = null;
  52568. }
  52569. this._disposeBlurPostProcesses();
  52570. };
  52571. /**
  52572. * Disposes the ShadowGenerator.
  52573. * Returns nothing.
  52574. */
  52575. ShadowGenerator.prototype.dispose = function () {
  52576. this._disposeRTTandPostProcesses();
  52577. if (this._light) {
  52578. this._light._shadowGenerator = null;
  52579. this._light._markMeshesAsLightDirty();
  52580. }
  52581. };
  52582. /**
  52583. * Serializes the ShadowGenerator and returns a serializationObject.
  52584. */
  52585. ShadowGenerator.prototype.serialize = function () {
  52586. var serializationObject = {};
  52587. var shadowMap = this.getShadowMap();
  52588. if (!shadowMap) {
  52589. return serializationObject;
  52590. }
  52591. serializationObject.lightId = this._light.id;
  52592. serializationObject.mapSize = shadowMap.getRenderSize();
  52593. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  52594. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  52595. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  52596. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  52597. serializationObject.usePoissonSampling = this.usePoissonSampling;
  52598. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  52599. serializationObject.depthScale = this.depthScale;
  52600. serializationObject.darkness = this.getDarkness();
  52601. serializationObject.blurBoxOffset = this.blurBoxOffset;
  52602. serializationObject.blurKernel = this.blurKernel;
  52603. serializationObject.blurScale = this.blurScale;
  52604. serializationObject.useKernelBlur = this.useKernelBlur;
  52605. serializationObject.transparencyShadow = this._transparencyShadow;
  52606. serializationObject.renderList = [];
  52607. if (shadowMap.renderList) {
  52608. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  52609. var mesh = shadowMap.renderList[meshIndex];
  52610. serializationObject.renderList.push(mesh.id);
  52611. }
  52612. }
  52613. return serializationObject;
  52614. };
  52615. /**
  52616. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  52617. */
  52618. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  52619. //casting to point light, as light is missing the position attr and typescript complains.
  52620. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  52621. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  52622. var shadowMap = shadowGenerator.getShadowMap();
  52623. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  52624. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  52625. meshes.forEach(function (mesh) {
  52626. if (!shadowMap) {
  52627. return;
  52628. }
  52629. if (!shadowMap.renderList) {
  52630. shadowMap.renderList = [];
  52631. }
  52632. shadowMap.renderList.push(mesh);
  52633. });
  52634. }
  52635. if (parsedShadowGenerator.usePoissonSampling) {
  52636. shadowGenerator.usePoissonSampling = true;
  52637. }
  52638. else if (parsedShadowGenerator.useExponentialShadowMap) {
  52639. shadowGenerator.useExponentialShadowMap = true;
  52640. }
  52641. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  52642. shadowGenerator.useBlurExponentialShadowMap = true;
  52643. }
  52644. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  52645. shadowGenerator.useCloseExponentialShadowMap = true;
  52646. }
  52647. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  52648. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  52649. }
  52650. else if (parsedShadowGenerator.useVarianceShadowMap) {
  52651. shadowGenerator.useExponentialShadowMap = true;
  52652. }
  52653. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  52654. shadowGenerator.useBlurExponentialShadowMap = true;
  52655. }
  52656. if (parsedShadowGenerator.depthScale) {
  52657. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  52658. }
  52659. if (parsedShadowGenerator.blurScale) {
  52660. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  52661. }
  52662. if (parsedShadowGenerator.blurBoxOffset) {
  52663. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  52664. }
  52665. if (parsedShadowGenerator.useKernelBlur) {
  52666. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  52667. }
  52668. if (parsedShadowGenerator.blurKernel) {
  52669. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  52670. }
  52671. if (parsedShadowGenerator.bias !== undefined) {
  52672. shadowGenerator.bias = parsedShadowGenerator.bias;
  52673. }
  52674. if (parsedShadowGenerator.darkness) {
  52675. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  52676. }
  52677. if (parsedShadowGenerator.transparencyShadow) {
  52678. shadowGenerator.setTransparencyShadow(true);
  52679. }
  52680. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  52681. return shadowGenerator;
  52682. };
  52683. ShadowGenerator._FILTER_NONE = 0;
  52684. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  52685. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  52686. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  52687. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  52688. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  52689. return ShadowGenerator;
  52690. }());
  52691. BABYLON.ShadowGenerator = ShadowGenerator;
  52692. })(BABYLON || (BABYLON = {}));
  52693. //# sourceMappingURL=babylon.shadowGenerator.js.map
  52694. var BABYLON;
  52695. (function (BABYLON) {
  52696. var DefaultLoadingScreen = /** @class */ (function () {
  52697. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  52698. if (_loadingText === void 0) { _loadingText = ""; }
  52699. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  52700. var _this = this;
  52701. this._renderingCanvas = _renderingCanvas;
  52702. this._loadingText = _loadingText;
  52703. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  52704. // Resize
  52705. this._resizeLoadingUI = function () {
  52706. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  52707. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  52708. if (!_this._loadingDiv) {
  52709. return;
  52710. }
  52711. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  52712. _this._loadingDiv.style.left = canvasRect.left + "px";
  52713. _this._loadingDiv.style.top = canvasRect.top + "px";
  52714. _this._loadingDiv.style.width = canvasRect.width + "px";
  52715. _this._loadingDiv.style.height = canvasRect.height + "px";
  52716. };
  52717. }
  52718. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  52719. if (this._loadingDiv) {
  52720. // Do not add a loading screen if there is already one
  52721. return;
  52722. }
  52723. this._loadingDiv = document.createElement("div");
  52724. this._loadingDiv.id = "babylonjsLoadingDiv";
  52725. this._loadingDiv.style.opacity = "0";
  52726. this._loadingDiv.style.transition = "opacity 1.5s ease";
  52727. this._loadingDiv.style.pointerEvents = "none";
  52728. // Loading text
  52729. this._loadingTextDiv = document.createElement("div");
  52730. this._loadingTextDiv.style.position = "absolute";
  52731. this._loadingTextDiv.style.left = "0";
  52732. this._loadingTextDiv.style.top = "50%";
  52733. this._loadingTextDiv.style.marginTop = "80px";
  52734. this._loadingTextDiv.style.width = "100%";
  52735. this._loadingTextDiv.style.height = "20px";
  52736. this._loadingTextDiv.style.fontFamily = "Arial";
  52737. this._loadingTextDiv.style.fontSize = "14px";
  52738. this._loadingTextDiv.style.color = "white";
  52739. this._loadingTextDiv.style.textAlign = "center";
  52740. this._loadingTextDiv.innerHTML = "Loading";
  52741. this._loadingDiv.appendChild(this._loadingTextDiv);
  52742. //set the predefined text
  52743. this._loadingTextDiv.innerHTML = this._loadingText;
  52744. // Generating keyframes
  52745. var style = document.createElement('style');
  52746. style.type = 'text/css';
  52747. 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 }";
  52748. style.innerHTML = keyFrames;
  52749. document.getElementsByTagName('head')[0].appendChild(style);
  52750. // Loading img
  52751. var imgBack = new Image();
  52752. 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";
  52753. imgBack.style.position = "absolute";
  52754. imgBack.style.left = "50%";
  52755. imgBack.style.top = "50%";
  52756. imgBack.style.marginLeft = "-60px";
  52757. imgBack.style.marginTop = "-60px";
  52758. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  52759. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  52760. imgBack.style.transformOrigin = "50% 50%";
  52761. imgBack.style.webkitTransformOrigin = "50% 50%";
  52762. this._loadingDiv.appendChild(imgBack);
  52763. this._resizeLoadingUI();
  52764. window.addEventListener("resize", this._resizeLoadingUI);
  52765. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  52766. document.body.appendChild(this._loadingDiv);
  52767. this._loadingDiv.style.opacity = "1";
  52768. };
  52769. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  52770. var _this = this;
  52771. if (!this._loadingDiv) {
  52772. return;
  52773. }
  52774. var onTransitionEnd = function () {
  52775. if (!_this._loadingDiv) {
  52776. return;
  52777. }
  52778. document.body.removeChild(_this._loadingDiv);
  52779. window.removeEventListener("resize", _this._resizeLoadingUI);
  52780. _this._loadingDiv = null;
  52781. };
  52782. this._loadingDiv.style.opacity = "0";
  52783. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  52784. };
  52785. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  52786. set: function (text) {
  52787. this._loadingText = text;
  52788. if (this._loadingTextDiv) {
  52789. this._loadingTextDiv.innerHTML = this._loadingText;
  52790. }
  52791. },
  52792. enumerable: true,
  52793. configurable: true
  52794. });
  52795. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  52796. get: function () {
  52797. return this._loadingDivBackgroundColor;
  52798. },
  52799. set: function (color) {
  52800. this._loadingDivBackgroundColor = color;
  52801. if (!this._loadingDiv) {
  52802. return;
  52803. }
  52804. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  52805. },
  52806. enumerable: true,
  52807. configurable: true
  52808. });
  52809. return DefaultLoadingScreen;
  52810. }());
  52811. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  52812. })(BABYLON || (BABYLON = {}));
  52813. //# sourceMappingURL=babylon.loadingScreen.js.map
  52814. var BABYLON;
  52815. (function (BABYLON) {
  52816. var SceneLoader = /** @class */ (function () {
  52817. function SceneLoader() {
  52818. }
  52819. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  52820. get: function () {
  52821. return 0;
  52822. },
  52823. enumerable: true,
  52824. configurable: true
  52825. });
  52826. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  52827. get: function () {
  52828. return 1;
  52829. },
  52830. enumerable: true,
  52831. configurable: true
  52832. });
  52833. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  52834. get: function () {
  52835. return 2;
  52836. },
  52837. enumerable: true,
  52838. configurable: true
  52839. });
  52840. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  52841. get: function () {
  52842. return 3;
  52843. },
  52844. enumerable: true,
  52845. configurable: true
  52846. });
  52847. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  52848. get: function () {
  52849. return SceneLoader._ForceFullSceneLoadingForIncremental;
  52850. },
  52851. set: function (value) {
  52852. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  52853. },
  52854. enumerable: true,
  52855. configurable: true
  52856. });
  52857. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  52858. get: function () {
  52859. return SceneLoader._ShowLoadingScreen;
  52860. },
  52861. set: function (value) {
  52862. SceneLoader._ShowLoadingScreen = value;
  52863. },
  52864. enumerable: true,
  52865. configurable: true
  52866. });
  52867. Object.defineProperty(SceneLoader, "loggingLevel", {
  52868. get: function () {
  52869. return SceneLoader._loggingLevel;
  52870. },
  52871. set: function (value) {
  52872. SceneLoader._loggingLevel = value;
  52873. },
  52874. enumerable: true,
  52875. configurable: true
  52876. });
  52877. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  52878. get: function () {
  52879. return SceneLoader._CleanBoneMatrixWeights;
  52880. },
  52881. set: function (value) {
  52882. SceneLoader._CleanBoneMatrixWeights = value;
  52883. },
  52884. enumerable: true,
  52885. configurable: true
  52886. });
  52887. SceneLoader._getDefaultPlugin = function () {
  52888. return SceneLoader._registeredPlugins[".babylon"];
  52889. };
  52890. SceneLoader._getPluginForExtension = function (extension) {
  52891. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  52892. if (registeredPlugin) {
  52893. return registeredPlugin;
  52894. }
  52895. return SceneLoader._getDefaultPlugin();
  52896. };
  52897. SceneLoader._getPluginForDirectLoad = function (data) {
  52898. for (var extension in SceneLoader._registeredPlugins) {
  52899. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  52900. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  52901. return SceneLoader._registeredPlugins[extension];
  52902. }
  52903. }
  52904. return SceneLoader._getDefaultPlugin();
  52905. };
  52906. SceneLoader._getPluginForFilename = function (sceneFilename) {
  52907. if (sceneFilename.name) {
  52908. sceneFilename = sceneFilename.name;
  52909. }
  52910. var queryStringPosition = sceneFilename.indexOf("?");
  52911. if (queryStringPosition !== -1) {
  52912. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  52913. }
  52914. var dotPosition = sceneFilename.lastIndexOf(".");
  52915. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  52916. return SceneLoader._getPluginForExtension(extension);
  52917. };
  52918. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  52919. SceneLoader._getDirectLoad = function (sceneFilename) {
  52920. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  52921. return sceneFilename.substr(5);
  52922. }
  52923. return null;
  52924. };
  52925. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  52926. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  52927. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  52928. var plugin;
  52929. if (registeredPlugin.plugin.createPlugin) {
  52930. plugin = registeredPlugin.plugin.createPlugin();
  52931. }
  52932. else {
  52933. plugin = registeredPlugin.plugin;
  52934. }
  52935. var useArrayBuffer = registeredPlugin.isBinary;
  52936. var database;
  52937. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  52938. var dataCallback = function (data, responseURL) {
  52939. if (scene.isDisposed) {
  52940. onError("Scene has been disposed");
  52941. return;
  52942. }
  52943. scene.database = database;
  52944. try {
  52945. onSuccess(plugin, data, responseURL);
  52946. }
  52947. catch (e) {
  52948. onError(null, e);
  52949. }
  52950. };
  52951. var manifestChecked = function (success) {
  52952. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  52953. if (request) {
  52954. onError(request.status + " " + request.statusText);
  52955. }
  52956. });
  52957. };
  52958. if (directLoad) {
  52959. dataCallback(directLoad);
  52960. return plugin;
  52961. }
  52962. if (rootUrl.indexOf("file:") === -1) {
  52963. if (scene.getEngine().enableOfflineSupport) {
  52964. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  52965. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  52966. }
  52967. else {
  52968. manifestChecked(true);
  52969. }
  52970. }
  52971. else {
  52972. var fileOrString = sceneFilename;
  52973. if (fileOrString.name) {
  52974. BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  52975. }
  52976. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  52977. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  52978. }
  52979. else {
  52980. onError("Unable to find file named " + sceneFilename);
  52981. }
  52982. }
  52983. return plugin;
  52984. };
  52985. // Public functions
  52986. SceneLoader.GetPluginForExtension = function (extension) {
  52987. return SceneLoader._getPluginForExtension(extension).plugin;
  52988. };
  52989. SceneLoader.RegisterPlugin = function (plugin) {
  52990. if (typeof plugin.extensions === "string") {
  52991. var extension = plugin.extensions;
  52992. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  52993. plugin: plugin,
  52994. isBinary: false
  52995. };
  52996. }
  52997. else {
  52998. var extensions = plugin.extensions;
  52999. Object.keys(extensions).forEach(function (extension) {
  53000. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  53001. plugin: plugin,
  53002. isBinary: extensions[extension].isBinary
  53003. };
  53004. });
  53005. }
  53006. };
  53007. /**
  53008. * Import meshes into a scene
  53009. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  53010. * @param rootUrl a string that defines the root url for scene and resources
  53011. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  53012. * @param scene the instance of BABYLON.Scene to append to
  53013. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  53014. * @param onProgress a callback with a progress event for each file being loaded
  53015. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  53016. */
  53017. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  53018. if (onSuccess === void 0) { onSuccess = null; }
  53019. if (onProgress === void 0) { onProgress = null; }
  53020. if (onError === void 0) { onError = null; }
  53021. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  53022. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  53023. return null;
  53024. }
  53025. var loadingToken = {};
  53026. scene._addPendingData(loadingToken);
  53027. var errorHandler = function (message, exception) {
  53028. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  53029. if (onError) {
  53030. onError(scene, errorMessage, exception);
  53031. }
  53032. else {
  53033. BABYLON.Tools.Error(errorMessage);
  53034. // should the exception be thrown?
  53035. }
  53036. scene._removePendingData(loadingToken);
  53037. };
  53038. var progressHandler = function (event) {
  53039. if (onProgress) {
  53040. onProgress(event);
  53041. }
  53042. };
  53043. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  53044. if (plugin.rewriteRootURL) {
  53045. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  53046. }
  53047. if (plugin.importMesh) {
  53048. var syncedPlugin = plugin;
  53049. var meshes = new Array();
  53050. var particleSystems = new Array();
  53051. var skeletons = new Array();
  53052. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  53053. return;
  53054. }
  53055. if (onSuccess) {
  53056. // wrap onSuccess with try-catch to know if something went wrong.
  53057. try {
  53058. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  53059. onSuccess(meshes, particleSystems, skeletons);
  53060. scene._removePendingData(loadingToken);
  53061. }
  53062. catch (e) {
  53063. var message = 'Error in onSuccess callback.';
  53064. errorHandler(message, e);
  53065. }
  53066. }
  53067. }
  53068. else {
  53069. var asyncedPlugin = plugin;
  53070. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  53071. if (onSuccess) {
  53072. try {
  53073. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  53074. onSuccess(meshes, particleSystems, skeletons);
  53075. scene._removePendingData(loadingToken);
  53076. }
  53077. catch (e) {
  53078. var message = 'Error in onSuccess callback.';
  53079. errorHandler(message, e);
  53080. }
  53081. }
  53082. }, progressHandler, errorHandler);
  53083. }
  53084. }, progressHandler, errorHandler, pluginExtension);
  53085. };
  53086. /**
  53087. * Load a scene
  53088. * @param rootUrl a string that defines the root url for scene and resources
  53089. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  53090. * @param engine is the instance of BABYLON.Engine to use to create the scene
  53091. * @param onSuccess a callback with the scene when import succeeds
  53092. * @param onProgress a callback with a progress event for each file being loaded
  53093. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  53094. */
  53095. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  53096. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  53097. };
  53098. /**
  53099. * Append a scene
  53100. * @param rootUrl a string that defines the root url for scene and resources
  53101. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  53102. * @param scene is the instance of BABYLON.Scene to append to
  53103. * @param onSuccess a callback with the scene when import succeeds
  53104. * @param onProgress a callback with a progress event for each file being loaded
  53105. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  53106. */
  53107. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  53108. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  53109. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  53110. return null;
  53111. }
  53112. if (SceneLoader.ShowLoadingScreen) {
  53113. scene.getEngine().displayLoadingUI();
  53114. }
  53115. var loadingToken = {};
  53116. scene._addPendingData(loadingToken);
  53117. var errorHandler = function (message, exception) {
  53118. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  53119. if (onError) {
  53120. onError(scene, errorMessage, exception);
  53121. }
  53122. else {
  53123. BABYLON.Tools.Error(errorMessage);
  53124. // should the exception be thrown?
  53125. }
  53126. scene._removePendingData(loadingToken);
  53127. scene.getEngine().hideLoadingUI();
  53128. };
  53129. var progressHandler = function (event) {
  53130. if (onProgress) {
  53131. onProgress(event);
  53132. }
  53133. };
  53134. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  53135. if (plugin.load) {
  53136. var syncedPlugin = plugin;
  53137. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  53138. return;
  53139. }
  53140. if (onSuccess) {
  53141. try {
  53142. onSuccess(scene);
  53143. }
  53144. catch (e) {
  53145. errorHandler("Error in onSuccess callback", e);
  53146. }
  53147. }
  53148. scene.loadingPluginName = plugin.name;
  53149. scene._removePendingData(loadingToken);
  53150. }
  53151. else {
  53152. var asyncedPlugin = plugin;
  53153. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  53154. if (onSuccess) {
  53155. onSuccess(scene);
  53156. }
  53157. scene.loadingPluginName = plugin.name;
  53158. scene._removePendingData(loadingToken);
  53159. }, progressHandler, errorHandler);
  53160. }
  53161. if (SceneLoader.ShowLoadingScreen) {
  53162. scene.executeWhenReady(function () {
  53163. scene.getEngine().hideLoadingUI();
  53164. });
  53165. }
  53166. }, progressHandler, errorHandler, pluginExtension);
  53167. };
  53168. // Flags
  53169. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  53170. SceneLoader._ShowLoadingScreen = true;
  53171. SceneLoader._CleanBoneMatrixWeights = false;
  53172. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  53173. // Members
  53174. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  53175. SceneLoader._registeredPlugins = {};
  53176. return SceneLoader;
  53177. }());
  53178. BABYLON.SceneLoader = SceneLoader;
  53179. ;
  53180. })(BABYLON || (BABYLON = {}));
  53181. //# sourceMappingURL=babylon.sceneLoader.js.map
  53182. var BABYLON;
  53183. (function (BABYLON) {
  53184. var Internals;
  53185. (function (Internals) {
  53186. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  53187. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  53188. var parsedMaterial = parsedData.materials[index];
  53189. if (parsedMaterial.id === id) {
  53190. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  53191. }
  53192. }
  53193. return null;
  53194. };
  53195. var isDescendantOf = function (mesh, names, hierarchyIds) {
  53196. for (var i in names) {
  53197. if (mesh.name === names[i]) {
  53198. hierarchyIds.push(mesh.id);
  53199. return true;
  53200. }
  53201. }
  53202. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  53203. hierarchyIds.push(mesh.id);
  53204. return true;
  53205. }
  53206. return false;
  53207. };
  53208. var logOperation = function (operation, producer) {
  53209. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  53210. };
  53211. BABYLON.SceneLoader.RegisterPlugin({
  53212. name: "babylon.js",
  53213. extensions: ".babylon",
  53214. canDirectLoad: function (data) {
  53215. if (data.indexOf("babylon") !== -1) {
  53216. return true;
  53217. }
  53218. return false;
  53219. },
  53220. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  53221. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  53222. // when SceneLoader.debugLogging = true (default), or exception encountered.
  53223. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  53224. // and avoid problems with multiple concurrent .babylon loads.
  53225. var log = "importMesh has failed JSON parse";
  53226. try {
  53227. var parsedData = JSON.parse(data);
  53228. log = "";
  53229. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  53230. if (!meshesNames) {
  53231. meshesNames = null;
  53232. }
  53233. else if (!Array.isArray(meshesNames)) {
  53234. meshesNames = [meshesNames];
  53235. }
  53236. var hierarchyIds = new Array();
  53237. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  53238. var loadedSkeletonsIds = [];
  53239. var loadedMaterialsIds = [];
  53240. var index;
  53241. var cache;
  53242. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  53243. var parsedMesh = parsedData.meshes[index];
  53244. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  53245. if (meshesNames !== null) {
  53246. // Remove found mesh name from list.
  53247. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  53248. }
  53249. //Geometry?
  53250. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  53251. //does the file contain geometries?
  53252. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  53253. //find the correct geometry and add it to the scene
  53254. var found = false;
  53255. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  53256. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  53257. return;
  53258. }
  53259. else {
  53260. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  53261. if (parsedGeometryData.id === parsedMesh.geometryId) {
  53262. switch (geometryType) {
  53263. case "boxes":
  53264. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  53265. break;
  53266. case "spheres":
  53267. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  53268. break;
  53269. case "cylinders":
  53270. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  53271. break;
  53272. case "toruses":
  53273. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  53274. break;
  53275. case "grounds":
  53276. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  53277. break;
  53278. case "planes":
  53279. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  53280. break;
  53281. case "torusKnots":
  53282. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  53283. break;
  53284. case "vertexData":
  53285. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  53286. break;
  53287. }
  53288. found = true;
  53289. }
  53290. });
  53291. }
  53292. });
  53293. if (found === false) {
  53294. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  53295. }
  53296. }
  53297. }
  53298. // Material ?
  53299. if (parsedMesh.materialId) {
  53300. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  53301. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  53302. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  53303. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  53304. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  53305. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  53306. var subMatId = parsedMultiMaterial.materials[matIndex];
  53307. loadedMaterialsIds.push(subMatId);
  53308. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  53309. log += "\n\tMaterial " + mat.toString(fullDetails);
  53310. }
  53311. loadedMaterialsIds.push(parsedMultiMaterial.id);
  53312. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  53313. materialFound = true;
  53314. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  53315. break;
  53316. }
  53317. }
  53318. }
  53319. if (materialFound === false) {
  53320. loadedMaterialsIds.push(parsedMesh.materialId);
  53321. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  53322. if (!mat) {
  53323. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  53324. }
  53325. else {
  53326. log += "\n\tMaterial " + mat.toString(fullDetails);
  53327. }
  53328. }
  53329. }
  53330. // Skeleton ?
  53331. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  53332. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  53333. if (skeletonAlreadyLoaded === false) {
  53334. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  53335. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  53336. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  53337. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  53338. skeletons.push(skeleton);
  53339. loadedSkeletonsIds.push(parsedSkeleton.id);
  53340. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  53341. }
  53342. }
  53343. }
  53344. }
  53345. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  53346. meshes.push(mesh);
  53347. log += "\n\tMesh " + mesh.toString(fullDetails);
  53348. }
  53349. }
  53350. // Connecting parents
  53351. var currentMesh;
  53352. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  53353. currentMesh = scene.meshes[index];
  53354. if (currentMesh._waitingParentId) {
  53355. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  53356. currentMesh._waitingParentId = null;
  53357. }
  53358. }
  53359. // freeze and compute world matrix application
  53360. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  53361. currentMesh = scene.meshes[index];
  53362. if (currentMesh._waitingFreezeWorldMatrix) {
  53363. currentMesh.freezeWorldMatrix();
  53364. currentMesh._waitingFreezeWorldMatrix = null;
  53365. }
  53366. else {
  53367. currentMesh.computeWorldMatrix(true);
  53368. }
  53369. }
  53370. }
  53371. // Particles
  53372. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  53373. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  53374. var parsedParticleSystem = parsedData.particleSystems[index];
  53375. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  53376. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  53377. }
  53378. }
  53379. }
  53380. return true;
  53381. }
  53382. catch (err) {
  53383. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  53384. if (onError) {
  53385. onError(msg, err);
  53386. }
  53387. else {
  53388. BABYLON.Tools.Log(msg);
  53389. throw err;
  53390. }
  53391. }
  53392. finally {
  53393. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  53394. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  53395. }
  53396. }
  53397. return false;
  53398. },
  53399. load: function (scene, data, rootUrl, onError) {
  53400. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  53401. // when SceneLoader.debugLogging = true (default), or exception encountered.
  53402. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  53403. // and avoid problems with multiple concurrent .babylon loads.
  53404. var log = "importScene has failed JSON parse";
  53405. try {
  53406. var parsedData = JSON.parse(data);
  53407. log = "";
  53408. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  53409. // Scene
  53410. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  53411. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  53412. }
  53413. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  53414. scene.autoClear = parsedData.autoClear;
  53415. }
  53416. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  53417. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  53418. }
  53419. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  53420. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  53421. }
  53422. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  53423. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  53424. }
  53425. // Fog
  53426. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  53427. scene.fogMode = parsedData.fogMode;
  53428. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  53429. scene.fogStart = parsedData.fogStart;
  53430. scene.fogEnd = parsedData.fogEnd;
  53431. scene.fogDensity = parsedData.fogDensity;
  53432. log += "\tFog mode for scene: ";
  53433. switch (scene.fogMode) {
  53434. // getters not compiling, so using hardcoded
  53435. case 1:
  53436. log += "exp\n";
  53437. break;
  53438. case 2:
  53439. log += "exp2\n";
  53440. break;
  53441. case 3:
  53442. log += "linear\n";
  53443. break;
  53444. }
  53445. }
  53446. //Physics
  53447. if (parsedData.physicsEnabled) {
  53448. var physicsPlugin;
  53449. if (parsedData.physicsEngine === "cannon") {
  53450. physicsPlugin = new BABYLON.CannonJSPlugin();
  53451. }
  53452. else if (parsedData.physicsEngine === "oimo") {
  53453. physicsPlugin = new BABYLON.OimoJSPlugin();
  53454. }
  53455. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  53456. //else - default engine, which is currently oimo
  53457. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  53458. scene.enablePhysics(physicsGravity, physicsPlugin);
  53459. }
  53460. // Metadata
  53461. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  53462. scene.metadata = parsedData.metadata;
  53463. }
  53464. //collisions, if defined. otherwise, default is true
  53465. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  53466. scene.collisionsEnabled = parsedData.collisionsEnabled;
  53467. }
  53468. scene.workerCollisions = !!parsedData.workerCollisions;
  53469. var index;
  53470. var cache;
  53471. // Lights
  53472. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  53473. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  53474. var parsedLight = parsedData.lights[index];
  53475. var light = BABYLON.Light.Parse(parsedLight, scene);
  53476. if (light) {
  53477. log += (index === 0 ? "\n\tLights:" : "");
  53478. log += "\n\t\t" + light.toString(fullDetails);
  53479. }
  53480. }
  53481. }
  53482. // Animations
  53483. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  53484. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  53485. var parsedAnimation = parsedData.animations[index];
  53486. var animation = BABYLON.Animation.Parse(parsedAnimation);
  53487. scene.animations.push(animation);
  53488. log += (index === 0 ? "\n\tAnimations:" : "");
  53489. log += "\n\t\t" + animation.toString(fullDetails);
  53490. }
  53491. }
  53492. if (parsedData.autoAnimate) {
  53493. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  53494. }
  53495. // Materials
  53496. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  53497. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  53498. var parsedMaterial = parsedData.materials[index];
  53499. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  53500. log += (index === 0 ? "\n\tMaterials:" : "");
  53501. log += "\n\t\t" + mat.toString(fullDetails);
  53502. }
  53503. }
  53504. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  53505. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  53506. var parsedMultiMaterial = parsedData.multiMaterials[index];
  53507. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  53508. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  53509. log += "\n\t\t" + mmat.toString(fullDetails);
  53510. }
  53511. }
  53512. // Morph targets
  53513. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  53514. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  53515. var managerData = _a[_i];
  53516. BABYLON.MorphTargetManager.Parse(managerData, scene);
  53517. }
  53518. }
  53519. // Skeletons
  53520. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  53521. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  53522. var parsedSkeleton = parsedData.skeletons[index];
  53523. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  53524. log += (index === 0 ? "\n\tSkeletons:" : "");
  53525. log += "\n\t\t" + skeleton.toString(fullDetails);
  53526. }
  53527. }
  53528. // Geometries
  53529. var geometries = parsedData.geometries;
  53530. if (geometries !== undefined && geometries !== null) {
  53531. // Boxes
  53532. var boxes = geometries.boxes;
  53533. if (boxes !== undefined && boxes !== null) {
  53534. for (index = 0, cache = boxes.length; index < cache; index++) {
  53535. var parsedBox = boxes[index];
  53536. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  53537. }
  53538. }
  53539. // Spheres
  53540. var spheres = geometries.spheres;
  53541. if (spheres !== undefined && spheres !== null) {
  53542. for (index = 0, cache = spheres.length; index < cache; index++) {
  53543. var parsedSphere = spheres[index];
  53544. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  53545. }
  53546. }
  53547. // Cylinders
  53548. var cylinders = geometries.cylinders;
  53549. if (cylinders !== undefined && cylinders !== null) {
  53550. for (index = 0, cache = cylinders.length; index < cache; index++) {
  53551. var parsedCylinder = cylinders[index];
  53552. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  53553. }
  53554. }
  53555. // Toruses
  53556. var toruses = geometries.toruses;
  53557. if (toruses !== undefined && toruses !== null) {
  53558. for (index = 0, cache = toruses.length; index < cache; index++) {
  53559. var parsedTorus = toruses[index];
  53560. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  53561. }
  53562. }
  53563. // Grounds
  53564. var grounds = geometries.grounds;
  53565. if (grounds !== undefined && grounds !== null) {
  53566. for (index = 0, cache = grounds.length; index < cache; index++) {
  53567. var parsedGround = grounds[index];
  53568. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  53569. }
  53570. }
  53571. // Planes
  53572. var planes = geometries.planes;
  53573. if (planes !== undefined && planes !== null) {
  53574. for (index = 0, cache = planes.length; index < cache; index++) {
  53575. var parsedPlane = planes[index];
  53576. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  53577. }
  53578. }
  53579. // TorusKnots
  53580. var torusKnots = geometries.torusKnots;
  53581. if (torusKnots !== undefined && torusKnots !== null) {
  53582. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  53583. var parsedTorusKnot = torusKnots[index];
  53584. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  53585. }
  53586. }
  53587. // VertexData
  53588. var vertexData = geometries.vertexData;
  53589. if (vertexData !== undefined && vertexData !== null) {
  53590. for (index = 0, cache = vertexData.length; index < cache; index++) {
  53591. var parsedVertexData = vertexData[index];
  53592. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  53593. }
  53594. }
  53595. }
  53596. // Transform nodes
  53597. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  53598. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  53599. var parsedTransformNode = parsedData.transformNodes[index];
  53600. BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  53601. }
  53602. }
  53603. // Meshes
  53604. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  53605. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  53606. var parsedMesh = parsedData.meshes[index];
  53607. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  53608. log += (index === 0 ? "\n\tMeshes:" : "");
  53609. log += "\n\t\t" + mesh.toString(fullDetails);
  53610. }
  53611. }
  53612. // Cameras
  53613. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  53614. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  53615. var parsedCamera = parsedData.cameras[index];
  53616. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  53617. log += (index === 0 ? "\n\tCameras:" : "");
  53618. log += "\n\t\t" + camera.toString(fullDetails);
  53619. }
  53620. }
  53621. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  53622. scene.setActiveCameraByID(parsedData.activeCameraID);
  53623. }
  53624. // Browsing all the graph to connect the dots
  53625. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  53626. var camera = scene.cameras[index];
  53627. if (camera._waitingParentId) {
  53628. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  53629. camera._waitingParentId = null;
  53630. }
  53631. }
  53632. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  53633. var light_1 = scene.lights[index];
  53634. if (light_1 && light_1._waitingParentId) {
  53635. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  53636. light_1._waitingParentId = null;
  53637. }
  53638. }
  53639. // Sounds
  53640. var loadedSounds = [];
  53641. var loadedSound;
  53642. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  53643. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  53644. var parsedSound = parsedData.sounds[index];
  53645. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53646. if (!parsedSound.url)
  53647. parsedSound.url = parsedSound.name;
  53648. if (!loadedSounds[parsedSound.url]) {
  53649. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  53650. loadedSounds[parsedSound.url] = loadedSound;
  53651. }
  53652. else {
  53653. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  53654. }
  53655. }
  53656. else {
  53657. new BABYLON.Sound(parsedSound.name, null, scene);
  53658. }
  53659. }
  53660. }
  53661. loadedSounds = [];
  53662. // Connect parents & children and parse actions
  53663. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  53664. var transformNode = scene.transformNodes[index];
  53665. if (transformNode._waitingParentId) {
  53666. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  53667. transformNode._waitingParentId = null;
  53668. }
  53669. }
  53670. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  53671. var mesh = scene.meshes[index];
  53672. if (mesh._waitingParentId) {
  53673. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  53674. mesh._waitingParentId = null;
  53675. }
  53676. if (mesh._waitingActions) {
  53677. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  53678. mesh._waitingActions = null;
  53679. }
  53680. }
  53681. // freeze world matrix application
  53682. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  53683. var currentMesh = scene.meshes[index];
  53684. if (currentMesh._waitingFreezeWorldMatrix) {
  53685. currentMesh.freezeWorldMatrix();
  53686. currentMesh._waitingFreezeWorldMatrix = null;
  53687. }
  53688. else {
  53689. currentMesh.computeWorldMatrix(true);
  53690. }
  53691. }
  53692. // Particles Systems
  53693. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  53694. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  53695. var parsedParticleSystem = parsedData.particleSystems[index];
  53696. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  53697. }
  53698. }
  53699. // Environment texture
  53700. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  53701. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  53702. if (parsedData.createDefaultSkybox === true) {
  53703. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  53704. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  53705. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  53706. }
  53707. }
  53708. // Lens flares
  53709. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  53710. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  53711. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  53712. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  53713. }
  53714. }
  53715. // Shadows
  53716. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  53717. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  53718. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  53719. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  53720. }
  53721. }
  53722. // Lights exclusions / inclusions
  53723. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  53724. var light_2 = scene.lights[index];
  53725. // Excluded check
  53726. if (light_2._excludedMeshesIds.length > 0) {
  53727. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  53728. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  53729. if (excludedMesh) {
  53730. light_2.excludedMeshes.push(excludedMesh);
  53731. }
  53732. }
  53733. light_2._excludedMeshesIds = [];
  53734. }
  53735. // Included check
  53736. if (light_2._includedOnlyMeshesIds.length > 0) {
  53737. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  53738. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  53739. if (includedOnlyMesh) {
  53740. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  53741. }
  53742. }
  53743. light_2._includedOnlyMeshesIds = [];
  53744. }
  53745. }
  53746. // Actions (scene)
  53747. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  53748. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  53749. }
  53750. // Finish
  53751. return true;
  53752. }
  53753. catch (err) {
  53754. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  53755. if (onError) {
  53756. onError(msg, err);
  53757. }
  53758. else {
  53759. BABYLON.Tools.Log(msg);
  53760. throw err;
  53761. }
  53762. }
  53763. finally {
  53764. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  53765. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  53766. }
  53767. }
  53768. return false;
  53769. }
  53770. });
  53771. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  53772. })(BABYLON || (BABYLON = {}));
  53773. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  53774. var BABYLON;
  53775. (function (BABYLON) {
  53776. var FilesInput = /** @class */ (function () {
  53777. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  53778. this.onProcessFileCallback = function () { return true; };
  53779. this._engine = engine;
  53780. this._currentScene = scene;
  53781. this._sceneLoadedCallback = sceneLoadedCallback;
  53782. this._progressCallback = progressCallback;
  53783. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  53784. this._textureLoadingCallback = textureLoadingCallback;
  53785. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  53786. this._onReloadCallback = onReloadCallback;
  53787. this._errorCallback = errorCallback;
  53788. }
  53789. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  53790. var _this = this;
  53791. if (elementToMonitor) {
  53792. this._elementToMonitor = elementToMonitor;
  53793. this._dragEnterHandler = function (e) { _this.drag(e); };
  53794. this._dragOverHandler = function (e) { _this.drag(e); };
  53795. this._dropHandler = function (e) { _this.drop(e); };
  53796. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  53797. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  53798. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  53799. }
  53800. };
  53801. FilesInput.prototype.dispose = function () {
  53802. if (!this._elementToMonitor) {
  53803. return;
  53804. }
  53805. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  53806. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  53807. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  53808. };
  53809. FilesInput.prototype.renderFunction = function () {
  53810. if (this._additionalRenderLoopLogicCallback) {
  53811. this._additionalRenderLoopLogicCallback();
  53812. }
  53813. if (this._currentScene) {
  53814. if (this._textureLoadingCallback) {
  53815. var remaining = this._currentScene.getWaitingItemsCount();
  53816. if (remaining > 0) {
  53817. this._textureLoadingCallback(remaining);
  53818. }
  53819. }
  53820. this._currentScene.render();
  53821. }
  53822. };
  53823. FilesInput.prototype.drag = function (e) {
  53824. e.stopPropagation();
  53825. e.preventDefault();
  53826. };
  53827. FilesInput.prototype.drop = function (eventDrop) {
  53828. eventDrop.stopPropagation();
  53829. eventDrop.preventDefault();
  53830. this.loadFiles(eventDrop);
  53831. };
  53832. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  53833. var _this = this;
  53834. var reader = folder.createReader();
  53835. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  53836. reader.readEntries(function (entries) {
  53837. remaining.count += entries.length;
  53838. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  53839. var entry = entries_1[_i];
  53840. if (entry.isFile) {
  53841. entry.file(function (file) {
  53842. file.correctName = relativePath + file.name;
  53843. files.push(file);
  53844. if (--remaining.count === 0) {
  53845. callback();
  53846. }
  53847. });
  53848. }
  53849. else if (entry.isDirectory) {
  53850. _this._traverseFolder(entry, files, remaining, callback);
  53851. }
  53852. }
  53853. if (--remaining.count) {
  53854. callback();
  53855. }
  53856. });
  53857. };
  53858. FilesInput.prototype._processFiles = function (files) {
  53859. var skippedFiles = 0;
  53860. for (var i = 0; i < files.length; i++) {
  53861. var name = files[i].correctName.toLowerCase();
  53862. var extension = name.split('.').pop();
  53863. if (!this.onProcessFileCallback(files[i], name, extension)) {
  53864. skippedFiles++;
  53865. continue;
  53866. }
  53867. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  53868. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  53869. this._sceneFileToLoad = files[i];
  53870. }
  53871. else {
  53872. FilesInput.FilesToLoad[name] = files[i];
  53873. }
  53874. }
  53875. if (this._onReloadCallback) {
  53876. this._onReloadCallback(this._sceneFileToLoad);
  53877. }
  53878. else if (skippedFiles < files.length) {
  53879. this.reload();
  53880. }
  53881. };
  53882. FilesInput.prototype.loadFiles = function (event) {
  53883. var _this = this;
  53884. if (this._startingProcessingFilesCallback)
  53885. this._startingProcessingFilesCallback();
  53886. // Handling data transfer via drag'n'drop
  53887. if (event && event.dataTransfer && event.dataTransfer.files) {
  53888. this._filesToLoad = event.dataTransfer.files;
  53889. }
  53890. // Handling files from input files
  53891. if (event && event.target && event.target.files) {
  53892. this._filesToLoad = event.target.files;
  53893. }
  53894. if (this._filesToLoad && this._filesToLoad.length > 0) {
  53895. var files_1 = new Array();
  53896. var folders = [];
  53897. var items = event.dataTransfer ? event.dataTransfer.items : null;
  53898. for (var i = 0; i < this._filesToLoad.length; i++) {
  53899. var fileToLoad = this._filesToLoad[i];
  53900. var name_1 = fileToLoad.name.toLowerCase();
  53901. var entry = void 0;
  53902. fileToLoad.correctName = name_1;
  53903. if (items) {
  53904. var item = items[i];
  53905. if (item.getAsEntry) {
  53906. entry = item.getAsEntry();
  53907. }
  53908. else if (item.webkitGetAsEntry) {
  53909. entry = item.webkitGetAsEntry();
  53910. }
  53911. }
  53912. if (!entry) {
  53913. files_1.push(fileToLoad);
  53914. }
  53915. else {
  53916. if (entry.isDirectory) {
  53917. folders.push(entry);
  53918. }
  53919. else {
  53920. files_1.push(fileToLoad);
  53921. }
  53922. }
  53923. }
  53924. if (folders.length === 0) {
  53925. this._processFiles(files_1);
  53926. }
  53927. else {
  53928. var remaining = { count: folders.length };
  53929. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  53930. var folder = folders_1[_i];
  53931. this._traverseFolder(folder, files_1, remaining, function () {
  53932. _this._processFiles(files_1);
  53933. });
  53934. }
  53935. }
  53936. }
  53937. };
  53938. FilesInput.prototype.reload = function () {
  53939. var _this = this;
  53940. // If a ".babylon" file has been provided
  53941. if (this._sceneFileToLoad) {
  53942. if (this._currentScene) {
  53943. if (BABYLON.Tools.errorsCount > 0) {
  53944. BABYLON.Tools.ClearLogCache();
  53945. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  53946. }
  53947. this._engine.stopRenderLoop();
  53948. this._currentScene.dispose();
  53949. }
  53950. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  53951. _this._currentScene = newScene;
  53952. if (_this._sceneLoadedCallback) {
  53953. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  53954. }
  53955. // Wait for textures and shaders to be ready
  53956. _this._currentScene.executeWhenReady(function () {
  53957. _this._engine.runRenderLoop(function () {
  53958. _this.renderFunction();
  53959. });
  53960. });
  53961. }, function (progress) {
  53962. if (_this._progressCallback) {
  53963. _this._progressCallback(progress);
  53964. }
  53965. }, function (scene, message) {
  53966. _this._currentScene = scene;
  53967. if (_this._errorCallback) {
  53968. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  53969. }
  53970. });
  53971. }
  53972. else {
  53973. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  53974. }
  53975. };
  53976. FilesInput.FilesToLoad = {};
  53977. return FilesInput;
  53978. }());
  53979. BABYLON.FilesInput = FilesInput;
  53980. })(BABYLON || (BABYLON = {}));
  53981. //# sourceMappingURL=babylon.filesInput.js.map
  53982. var BABYLON;
  53983. (function (BABYLON) {
  53984. /**
  53985. * This class implement a typical dictionary using a string as key and the generic type T as value.
  53986. * The underlying implementation relies on an associative array to ensure the best performances.
  53987. * The value can be anything including 'null' but except 'undefined'
  53988. */
  53989. var StringDictionary = /** @class */ (function () {
  53990. function StringDictionary() {
  53991. this._count = 0;
  53992. this._data = {};
  53993. }
  53994. /**
  53995. * This will clear this dictionary and copy the content from the 'source' one.
  53996. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  53997. * @param source the dictionary to take the content from and copy to this dictionary
  53998. */
  53999. StringDictionary.prototype.copyFrom = function (source) {
  54000. var _this = this;
  54001. this.clear();
  54002. source.forEach(function (t, v) { return _this.add(t, v); });
  54003. };
  54004. /**
  54005. * Get a value based from its key
  54006. * @param key the given key to get the matching value from
  54007. * @return the value if found, otherwise undefined is returned
  54008. */
  54009. StringDictionary.prototype.get = function (key) {
  54010. var val = this._data[key];
  54011. if (val !== undefined) {
  54012. return val;
  54013. }
  54014. return undefined;
  54015. };
  54016. /**
  54017. * Get a value from its key or add it if it doesn't exist.
  54018. * This method will ensure you that a given key/data will be present in the dictionary.
  54019. * @param key the given key to get the matching value from
  54020. * @param factory the factory that will create the value if the key is not present in the dictionary.
  54021. * The factory will only be invoked if there's no data for the given key.
  54022. * @return the value corresponding to the key.
  54023. */
  54024. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  54025. var val = this.get(key);
  54026. if (val !== undefined) {
  54027. return val;
  54028. }
  54029. val = factory(key);
  54030. if (val) {
  54031. this.add(key, val);
  54032. }
  54033. return val;
  54034. };
  54035. /**
  54036. * Get a value from its key if present in the dictionary otherwise add it
  54037. * @param key the key to get the value from
  54038. * @param val if there's no such key/value pair in the dictionary add it with this value
  54039. * @return the value corresponding to the key
  54040. */
  54041. StringDictionary.prototype.getOrAdd = function (key, val) {
  54042. var curVal = this.get(key);
  54043. if (curVal !== undefined) {
  54044. return curVal;
  54045. }
  54046. this.add(key, val);
  54047. return val;
  54048. };
  54049. /**
  54050. * Check if there's a given key in the dictionary
  54051. * @param key the key to check for
  54052. * @return true if the key is present, false otherwise
  54053. */
  54054. StringDictionary.prototype.contains = function (key) {
  54055. return this._data[key] !== undefined;
  54056. };
  54057. /**
  54058. * Add a new key and its corresponding value
  54059. * @param key the key to add
  54060. * @param value the value corresponding to the key
  54061. * @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
  54062. */
  54063. StringDictionary.prototype.add = function (key, value) {
  54064. if (this._data[key] !== undefined) {
  54065. return false;
  54066. }
  54067. this._data[key] = value;
  54068. ++this._count;
  54069. return true;
  54070. };
  54071. StringDictionary.prototype.set = function (key, value) {
  54072. if (this._data[key] === undefined) {
  54073. return false;
  54074. }
  54075. this._data[key] = value;
  54076. return true;
  54077. };
  54078. /**
  54079. * Get the element of the given key and remove it from the dictionary
  54080. * @param key
  54081. */
  54082. StringDictionary.prototype.getAndRemove = function (key) {
  54083. var val = this.get(key);
  54084. if (val !== undefined) {
  54085. delete this._data[key];
  54086. --this._count;
  54087. return val;
  54088. }
  54089. return null;
  54090. };
  54091. /**
  54092. * Remove a key/value from the dictionary.
  54093. * @param key the key to remove
  54094. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  54095. */
  54096. StringDictionary.prototype.remove = function (key) {
  54097. if (this.contains(key)) {
  54098. delete this._data[key];
  54099. --this._count;
  54100. return true;
  54101. }
  54102. return false;
  54103. };
  54104. /**
  54105. * Clear the whole content of the dictionary
  54106. */
  54107. StringDictionary.prototype.clear = function () {
  54108. this._data = {};
  54109. this._count = 0;
  54110. };
  54111. Object.defineProperty(StringDictionary.prototype, "count", {
  54112. get: function () {
  54113. return this._count;
  54114. },
  54115. enumerable: true,
  54116. configurable: true
  54117. });
  54118. /**
  54119. * Execute a callback on each key/val of the dictionary.
  54120. * Note that you can remove any element in this dictionary in the callback implementation
  54121. * @param callback the callback to execute on a given key/value pair
  54122. */
  54123. StringDictionary.prototype.forEach = function (callback) {
  54124. for (var cur in this._data) {
  54125. var val = this._data[cur];
  54126. callback(cur, val);
  54127. }
  54128. };
  54129. /**
  54130. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  54131. * If the callback returns null or undefined the method will iterate to the next key/value pair
  54132. * Note that you can remove any element in this dictionary in the callback implementation
  54133. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  54134. */
  54135. StringDictionary.prototype.first = function (callback) {
  54136. for (var cur in this._data) {
  54137. var val = this._data[cur];
  54138. var res = callback(cur, val);
  54139. if (res) {
  54140. return res;
  54141. }
  54142. }
  54143. return null;
  54144. };
  54145. return StringDictionary;
  54146. }());
  54147. BABYLON.StringDictionary = StringDictionary;
  54148. })(BABYLON || (BABYLON = {}));
  54149. //# sourceMappingURL=babylon.stringDictionary.js.map
  54150. var BABYLON;
  54151. (function (BABYLON) {
  54152. var Tags = /** @class */ (function () {
  54153. function Tags() {
  54154. }
  54155. Tags.EnableFor = function (obj) {
  54156. obj._tags = obj._tags || {};
  54157. obj.hasTags = function () {
  54158. return Tags.HasTags(obj);
  54159. };
  54160. obj.addTags = function (tagsString) {
  54161. return Tags.AddTagsTo(obj, tagsString);
  54162. };
  54163. obj.removeTags = function (tagsString) {
  54164. return Tags.RemoveTagsFrom(obj, tagsString);
  54165. };
  54166. obj.matchesTagsQuery = function (tagsQuery) {
  54167. return Tags.MatchesQuery(obj, tagsQuery);
  54168. };
  54169. };
  54170. Tags.DisableFor = function (obj) {
  54171. delete obj._tags;
  54172. delete obj.hasTags;
  54173. delete obj.addTags;
  54174. delete obj.removeTags;
  54175. delete obj.matchesTagsQuery;
  54176. };
  54177. Tags.HasTags = function (obj) {
  54178. if (!obj._tags) {
  54179. return false;
  54180. }
  54181. return !BABYLON.Tools.IsEmpty(obj._tags);
  54182. };
  54183. Tags.GetTags = function (obj, asString) {
  54184. if (asString === void 0) { asString = true; }
  54185. if (!obj._tags) {
  54186. return null;
  54187. }
  54188. if (asString) {
  54189. var tagsArray = [];
  54190. for (var tag in obj._tags) {
  54191. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  54192. tagsArray.push(tag);
  54193. }
  54194. }
  54195. return tagsArray.join(" ");
  54196. }
  54197. else {
  54198. return obj._tags;
  54199. }
  54200. };
  54201. // the tags 'true' and 'false' are reserved and cannot be used as tags
  54202. // a tag cannot start with '||', '&&', and '!'
  54203. // it cannot contain whitespaces
  54204. Tags.AddTagsTo = function (obj, tagsString) {
  54205. if (!tagsString) {
  54206. return;
  54207. }
  54208. if (typeof tagsString !== "string") {
  54209. return;
  54210. }
  54211. var tags = tagsString.split(" ");
  54212. tags.forEach(function (tag, index, array) {
  54213. Tags._AddTagTo(obj, tag);
  54214. });
  54215. };
  54216. Tags._AddTagTo = function (obj, tag) {
  54217. tag = tag.trim();
  54218. if (tag === "" || tag === "true" || tag === "false") {
  54219. return;
  54220. }
  54221. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  54222. return;
  54223. }
  54224. Tags.EnableFor(obj);
  54225. obj._tags[tag] = true;
  54226. };
  54227. Tags.RemoveTagsFrom = function (obj, tagsString) {
  54228. if (!Tags.HasTags(obj)) {
  54229. return;
  54230. }
  54231. var tags = tagsString.split(" ");
  54232. for (var t in tags) {
  54233. Tags._RemoveTagFrom(obj, tags[t]);
  54234. }
  54235. };
  54236. Tags._RemoveTagFrom = function (obj, tag) {
  54237. delete obj._tags[tag];
  54238. };
  54239. Tags.MatchesQuery = function (obj, tagsQuery) {
  54240. if (tagsQuery === undefined) {
  54241. return true;
  54242. }
  54243. if (tagsQuery === "") {
  54244. return Tags.HasTags(obj);
  54245. }
  54246. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  54247. };
  54248. return Tags;
  54249. }());
  54250. BABYLON.Tags = Tags;
  54251. })(BABYLON || (BABYLON = {}));
  54252. //# sourceMappingURL=babylon.tags.js.map
  54253. var BABYLON;
  54254. (function (BABYLON) {
  54255. var Internals;
  54256. (function (Internals) {
  54257. var AndOrNotEvaluator = /** @class */ (function () {
  54258. function AndOrNotEvaluator() {
  54259. }
  54260. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  54261. if (!query.match(/\([^\(\)]*\)/g)) {
  54262. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  54263. }
  54264. else {
  54265. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  54266. // remove parenthesis
  54267. r = r.slice(1, r.length - 1);
  54268. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  54269. });
  54270. }
  54271. if (query === "true") {
  54272. return true;
  54273. }
  54274. if (query === "false") {
  54275. return false;
  54276. }
  54277. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  54278. };
  54279. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  54280. evaluateCallback = evaluateCallback || (function (r) {
  54281. return r === "true" ? true : false;
  54282. });
  54283. var result;
  54284. var or = parenthesisContent.split("||");
  54285. for (var i in or) {
  54286. if (or.hasOwnProperty(i)) {
  54287. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  54288. var and = ori.split("&&");
  54289. if (and.length > 1) {
  54290. for (var j = 0; j < and.length; ++j) {
  54291. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  54292. if (andj !== "true" && andj !== "false") {
  54293. if (andj[0] === "!") {
  54294. result = !evaluateCallback(andj.substring(1));
  54295. }
  54296. else {
  54297. result = evaluateCallback(andj);
  54298. }
  54299. }
  54300. else {
  54301. result = andj === "true" ? true : false;
  54302. }
  54303. if (!result) {
  54304. ori = "false";
  54305. break;
  54306. }
  54307. }
  54308. }
  54309. if (result || ori === "true") {
  54310. result = true;
  54311. break;
  54312. }
  54313. // result equals false (or undefined)
  54314. if (ori !== "true" && ori !== "false") {
  54315. if (ori[0] === "!") {
  54316. result = !evaluateCallback(ori.substring(1));
  54317. }
  54318. else {
  54319. result = evaluateCallback(ori);
  54320. }
  54321. }
  54322. else {
  54323. result = ori === "true" ? true : false;
  54324. }
  54325. }
  54326. }
  54327. // the whole parenthesis scope is replaced by 'true' or 'false'
  54328. return result ? "true" : "false";
  54329. };
  54330. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  54331. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  54332. // remove whitespaces
  54333. r = r.replace(/[\s]/g, function () { return ""; });
  54334. return r.length % 2 ? "!" : "";
  54335. });
  54336. booleanString = booleanString.trim();
  54337. if (booleanString === "!true") {
  54338. booleanString = "false";
  54339. }
  54340. else if (booleanString === "!false") {
  54341. booleanString = "true";
  54342. }
  54343. return booleanString;
  54344. };
  54345. return AndOrNotEvaluator;
  54346. }());
  54347. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  54348. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  54349. })(BABYLON || (BABYLON = {}));
  54350. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  54351. var BABYLON;
  54352. (function (BABYLON) {
  54353. var Database = /** @class */ (function () {
  54354. function Database(urlToScene, callbackManifestChecked) {
  54355. // Handling various flavors of prefixed version of IndexedDB
  54356. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  54357. this.callbackManifestChecked = callbackManifestChecked;
  54358. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  54359. this.db = null;
  54360. this._enableSceneOffline = false;
  54361. this._enableTexturesOffline = false;
  54362. this.manifestVersionFound = 0;
  54363. this.mustUpdateRessources = false;
  54364. this.hasReachedQuota = false;
  54365. if (!Database.IDBStorageEnabled) {
  54366. this.callbackManifestChecked(true);
  54367. }
  54368. else {
  54369. this.checkManifestFile();
  54370. }
  54371. }
  54372. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  54373. get: function () {
  54374. return this._enableSceneOffline;
  54375. },
  54376. enumerable: true,
  54377. configurable: true
  54378. });
  54379. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  54380. get: function () {
  54381. return this._enableTexturesOffline;
  54382. },
  54383. enumerable: true,
  54384. configurable: true
  54385. });
  54386. Database.prototype.checkManifestFile = function () {
  54387. var _this = this;
  54388. var noManifestFile = function () {
  54389. _this._enableSceneOffline = false;
  54390. _this._enableTexturesOffline = false;
  54391. _this.callbackManifestChecked(false);
  54392. };
  54393. var timeStampUsed = false;
  54394. var manifestURL = this.currentSceneUrl + ".manifest";
  54395. var xhr = new XMLHttpRequest();
  54396. if (navigator.onLine) {
  54397. // Adding a timestamp to by-pass browsers' cache
  54398. timeStampUsed = true;
  54399. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  54400. }
  54401. xhr.open("GET", manifestURL, true);
  54402. xhr.addEventListener("load", function () {
  54403. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  54404. try {
  54405. var manifestFile = JSON.parse(xhr.response);
  54406. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  54407. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  54408. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  54409. _this.manifestVersionFound = manifestFile.version;
  54410. }
  54411. if (_this.callbackManifestChecked) {
  54412. _this.callbackManifestChecked(true);
  54413. }
  54414. }
  54415. catch (ex) {
  54416. noManifestFile();
  54417. }
  54418. }
  54419. else {
  54420. noManifestFile();
  54421. }
  54422. }, false);
  54423. xhr.addEventListener("error", function (event) {
  54424. if (timeStampUsed) {
  54425. timeStampUsed = false;
  54426. // Let's retry without the timeStamp
  54427. // It could fail when coupled with HTML5 Offline API
  54428. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  54429. xhr.open("GET", retryManifestURL, true);
  54430. xhr.send();
  54431. }
  54432. else {
  54433. noManifestFile();
  54434. }
  54435. }, false);
  54436. try {
  54437. xhr.send();
  54438. }
  54439. catch (ex) {
  54440. BABYLON.Tools.Error("Error on XHR send request.");
  54441. this.callbackManifestChecked(false);
  54442. }
  54443. };
  54444. Database.prototype.openAsync = function (successCallback, errorCallback) {
  54445. var _this = this;
  54446. var handleError = function () {
  54447. _this.isSupported = false;
  54448. if (errorCallback)
  54449. errorCallback();
  54450. };
  54451. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  54452. // Your browser doesn't support IndexedDB
  54453. this.isSupported = false;
  54454. if (errorCallback)
  54455. errorCallback();
  54456. }
  54457. else {
  54458. // If the DB hasn't been opened or created yet
  54459. if (!this.db) {
  54460. this.hasReachedQuota = false;
  54461. this.isSupported = true;
  54462. var request = this.idbFactory.open("babylonjs", 1);
  54463. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  54464. request.onerror = function (event) {
  54465. handleError();
  54466. };
  54467. // executes when a version change transaction cannot complete due to other active transactions
  54468. request.onblocked = function (event) {
  54469. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  54470. handleError();
  54471. };
  54472. // DB has been opened successfully
  54473. request.onsuccess = function (event) {
  54474. _this.db = request.result;
  54475. successCallback();
  54476. };
  54477. // Initialization of the DB. Creating Scenes & Textures stores
  54478. request.onupgradeneeded = function (event) {
  54479. _this.db = (event.target).result;
  54480. if (_this.db) {
  54481. try {
  54482. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  54483. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  54484. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  54485. }
  54486. catch (ex) {
  54487. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  54488. handleError();
  54489. }
  54490. }
  54491. };
  54492. }
  54493. else {
  54494. if (successCallback)
  54495. successCallback();
  54496. }
  54497. }
  54498. };
  54499. Database.prototype.loadImageFromDB = function (url, image) {
  54500. var _this = this;
  54501. var completeURL = Database.ReturnFullUrlLocation(url);
  54502. var saveAndLoadImage = function () {
  54503. if (!_this.hasReachedQuota && _this.db !== null) {
  54504. // the texture is not yet in the DB, let's try to save it
  54505. _this._saveImageIntoDBAsync(completeURL, image);
  54506. }
  54507. else {
  54508. image.src = url;
  54509. }
  54510. };
  54511. if (!this.mustUpdateRessources) {
  54512. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  54513. }
  54514. else {
  54515. saveAndLoadImage();
  54516. }
  54517. };
  54518. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  54519. if (this.isSupported && this.db !== null) {
  54520. var texture;
  54521. var transaction = this.db.transaction(["textures"]);
  54522. transaction.onabort = function (event) {
  54523. image.src = url;
  54524. };
  54525. transaction.oncomplete = function (event) {
  54526. var blobTextureURL;
  54527. if (texture) {
  54528. var URL = window.URL || window.webkitURL;
  54529. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  54530. image.onerror = function () {
  54531. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  54532. image.src = url;
  54533. };
  54534. image.src = blobTextureURL;
  54535. }
  54536. else {
  54537. notInDBCallback();
  54538. }
  54539. };
  54540. var getRequest = transaction.objectStore("textures").get(url);
  54541. getRequest.onsuccess = function (event) {
  54542. texture = (event.target).result;
  54543. };
  54544. getRequest.onerror = function (event) {
  54545. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  54546. image.src = url;
  54547. };
  54548. }
  54549. else {
  54550. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  54551. image.src = url;
  54552. }
  54553. };
  54554. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  54555. var _this = this;
  54556. if (this.isSupported) {
  54557. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  54558. var generateBlobUrl = function () {
  54559. var blobTextureURL;
  54560. if (blob) {
  54561. var URL = window.URL || window.webkitURL;
  54562. try {
  54563. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  54564. }
  54565. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  54566. catch (ex) {
  54567. blobTextureURL = URL.createObjectURL(blob);
  54568. }
  54569. }
  54570. if (blobTextureURL) {
  54571. image.src = blobTextureURL;
  54572. }
  54573. };
  54574. if (Database.IsUASupportingBlobStorage) {
  54575. var xhr = new XMLHttpRequest(), blob;
  54576. xhr.open("GET", url, true);
  54577. xhr.responseType = "blob";
  54578. xhr.addEventListener("load", function () {
  54579. if (xhr.status === 200 && _this.db) {
  54580. // Blob as response (XHR2)
  54581. blob = xhr.response;
  54582. var transaction = _this.db.transaction(["textures"], "readwrite");
  54583. // the transaction could abort because of a QuotaExceededError error
  54584. transaction.onabort = function (event) {
  54585. try {
  54586. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  54587. var srcElement = (event.srcElement || event.target);
  54588. var error = srcElement.error;
  54589. if (error && error.name === "QuotaExceededError") {
  54590. _this.hasReachedQuota = true;
  54591. }
  54592. }
  54593. catch (ex) { }
  54594. generateBlobUrl();
  54595. };
  54596. transaction.oncomplete = function (event) {
  54597. generateBlobUrl();
  54598. };
  54599. var newTexture = { textureUrl: url, data: blob };
  54600. try {
  54601. // Put the blob into the dabase
  54602. var addRequest = transaction.objectStore("textures").put(newTexture);
  54603. addRequest.onsuccess = function (event) {
  54604. };
  54605. addRequest.onerror = function (event) {
  54606. generateBlobUrl();
  54607. };
  54608. }
  54609. catch (ex) {
  54610. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  54611. if (ex.code === 25) {
  54612. Database.IsUASupportingBlobStorage = false;
  54613. }
  54614. image.src = url;
  54615. }
  54616. }
  54617. else {
  54618. image.src = url;
  54619. }
  54620. }, false);
  54621. xhr.addEventListener("error", function (event) {
  54622. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  54623. image.src = url;
  54624. }, false);
  54625. xhr.send();
  54626. }
  54627. else {
  54628. image.src = url;
  54629. }
  54630. }
  54631. else {
  54632. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  54633. image.src = url;
  54634. }
  54635. };
  54636. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  54637. var _this = this;
  54638. var updateVersion = function () {
  54639. // the version is not yet in the DB or we need to update it
  54640. _this._saveVersionIntoDBAsync(url, versionLoaded);
  54641. };
  54642. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  54643. };
  54644. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  54645. var _this = this;
  54646. if (this.isSupported && this.db) {
  54647. var version;
  54648. try {
  54649. var transaction = this.db.transaction(["versions"]);
  54650. transaction.oncomplete = function (event) {
  54651. if (version) {
  54652. // If the version in the JSON file is > than the version in DB
  54653. if (_this.manifestVersionFound > version.data) {
  54654. _this.mustUpdateRessources = true;
  54655. updateInDBCallback();
  54656. }
  54657. else {
  54658. callback(version.data);
  54659. }
  54660. }
  54661. else {
  54662. _this.mustUpdateRessources = true;
  54663. updateInDBCallback();
  54664. }
  54665. };
  54666. transaction.onabort = function (event) {
  54667. callback(-1);
  54668. };
  54669. var getRequest = transaction.objectStore("versions").get(url);
  54670. getRequest.onsuccess = function (event) {
  54671. version = (event.target).result;
  54672. };
  54673. getRequest.onerror = function (event) {
  54674. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  54675. callback(-1);
  54676. };
  54677. }
  54678. catch (ex) {
  54679. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  54680. callback(-1);
  54681. }
  54682. }
  54683. else {
  54684. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  54685. callback(-1);
  54686. }
  54687. };
  54688. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  54689. var _this = this;
  54690. if (this.isSupported && !this.hasReachedQuota && this.db) {
  54691. try {
  54692. // Open a transaction to the database
  54693. var transaction = this.db.transaction(["versions"], "readwrite");
  54694. // the transaction could abort because of a QuotaExceededError error
  54695. transaction.onabort = function (event) {
  54696. try {
  54697. var error = event.srcElement['error'];
  54698. if (error && error.name === "QuotaExceededError") {
  54699. _this.hasReachedQuota = true;
  54700. }
  54701. }
  54702. catch (ex) { }
  54703. callback(-1);
  54704. };
  54705. transaction.oncomplete = function (event) {
  54706. callback(_this.manifestVersionFound);
  54707. };
  54708. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  54709. // Put the scene into the database
  54710. var addRequest = transaction.objectStore("versions").put(newVersion);
  54711. addRequest.onsuccess = function (event) {
  54712. };
  54713. addRequest.onerror = function (event) {
  54714. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  54715. };
  54716. }
  54717. catch (ex) {
  54718. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  54719. callback(-1);
  54720. }
  54721. }
  54722. else {
  54723. callback(-1);
  54724. }
  54725. };
  54726. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  54727. var _this = this;
  54728. var completeUrl = Database.ReturnFullUrlLocation(url);
  54729. var saveAndLoadFile = function () {
  54730. // the scene is not yet in the DB, let's try to save it
  54731. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  54732. };
  54733. this._checkVersionFromDB(completeUrl, function (version) {
  54734. if (version !== -1) {
  54735. if (!_this.mustUpdateRessources) {
  54736. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  54737. }
  54738. else {
  54739. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  54740. }
  54741. }
  54742. else {
  54743. if (errorCallback) {
  54744. errorCallback();
  54745. }
  54746. }
  54747. });
  54748. };
  54749. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  54750. if (this.isSupported && this.db) {
  54751. var targetStore;
  54752. if (url.indexOf(".babylon") !== -1) {
  54753. targetStore = "scenes";
  54754. }
  54755. else {
  54756. targetStore = "textures";
  54757. }
  54758. var file;
  54759. var transaction = this.db.transaction([targetStore]);
  54760. transaction.oncomplete = function (event) {
  54761. if (file) {
  54762. callback(file.data);
  54763. }
  54764. else {
  54765. notInDBCallback();
  54766. }
  54767. };
  54768. transaction.onabort = function (event) {
  54769. notInDBCallback();
  54770. };
  54771. var getRequest = transaction.objectStore(targetStore).get(url);
  54772. getRequest.onsuccess = function (event) {
  54773. file = (event.target).result;
  54774. };
  54775. getRequest.onerror = function (event) {
  54776. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  54777. notInDBCallback();
  54778. };
  54779. }
  54780. else {
  54781. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  54782. callback();
  54783. }
  54784. };
  54785. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  54786. var _this = this;
  54787. if (this.isSupported) {
  54788. var targetStore;
  54789. if (url.indexOf(".babylon") !== -1) {
  54790. targetStore = "scenes";
  54791. }
  54792. else {
  54793. targetStore = "textures";
  54794. }
  54795. // Create XHR
  54796. var xhr = new XMLHttpRequest();
  54797. var fileData;
  54798. xhr.open("GET", url, true);
  54799. if (useArrayBuffer) {
  54800. xhr.responseType = "arraybuffer";
  54801. }
  54802. if (progressCallback) {
  54803. xhr.onprogress = progressCallback;
  54804. }
  54805. xhr.addEventListener("load", function () {
  54806. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  54807. // Blob as response (XHR2)
  54808. //fileData = xhr.responseText;
  54809. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  54810. if (!_this.hasReachedQuota && _this.db) {
  54811. // Open a transaction to the database
  54812. var transaction = _this.db.transaction([targetStore], "readwrite");
  54813. // the transaction could abort because of a QuotaExceededError error
  54814. transaction.onabort = function (event) {
  54815. try {
  54816. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  54817. var error = event.srcElement['error'];
  54818. if (error && error.name === "QuotaExceededError") {
  54819. _this.hasReachedQuota = true;
  54820. }
  54821. }
  54822. catch (ex) { }
  54823. callback(fileData);
  54824. };
  54825. transaction.oncomplete = function (event) {
  54826. callback(fileData);
  54827. };
  54828. var newFile;
  54829. if (targetStore === "scenes") {
  54830. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  54831. }
  54832. else {
  54833. newFile = { textureUrl: url, data: fileData };
  54834. }
  54835. try {
  54836. // Put the scene into the database
  54837. var addRequest = transaction.objectStore(targetStore).put(newFile);
  54838. addRequest.onsuccess = function (event) {
  54839. };
  54840. addRequest.onerror = function (event) {
  54841. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  54842. };
  54843. }
  54844. catch (ex) {
  54845. callback(fileData);
  54846. }
  54847. }
  54848. else {
  54849. callback(fileData);
  54850. }
  54851. }
  54852. else {
  54853. callback();
  54854. }
  54855. }, false);
  54856. xhr.addEventListener("error", function (event) {
  54857. BABYLON.Tools.Error("error on XHR request.");
  54858. callback();
  54859. }, false);
  54860. xhr.send();
  54861. }
  54862. else {
  54863. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  54864. callback();
  54865. }
  54866. };
  54867. Database.IsUASupportingBlobStorage = true;
  54868. Database.IDBStorageEnabled = true;
  54869. Database.parseURL = function (url) {
  54870. var a = document.createElement('a');
  54871. a.href = url;
  54872. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  54873. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  54874. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  54875. return absLocation;
  54876. };
  54877. Database.ReturnFullUrlLocation = function (url) {
  54878. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  54879. return (Database.parseURL(window.location.href) + url);
  54880. }
  54881. else {
  54882. return url;
  54883. }
  54884. };
  54885. return Database;
  54886. }());
  54887. BABYLON.Database = Database;
  54888. })(BABYLON || (BABYLON = {}));
  54889. //# sourceMappingURL=babylon.database.js.map
  54890. var BABYLON;
  54891. (function (BABYLON) {
  54892. var FresnelParameters = /** @class */ (function () {
  54893. function FresnelParameters() {
  54894. this._isEnabled = true;
  54895. this.leftColor = BABYLON.Color3.White();
  54896. this.rightColor = BABYLON.Color3.Black();
  54897. this.bias = 0;
  54898. this.power = 1;
  54899. }
  54900. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  54901. get: function () {
  54902. return this._isEnabled;
  54903. },
  54904. set: function (value) {
  54905. if (this._isEnabled === value) {
  54906. return;
  54907. }
  54908. this._isEnabled = value;
  54909. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  54910. },
  54911. enumerable: true,
  54912. configurable: true
  54913. });
  54914. FresnelParameters.prototype.clone = function () {
  54915. var newFresnelParameters = new FresnelParameters();
  54916. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  54917. return newFresnelParameters;
  54918. };
  54919. FresnelParameters.prototype.serialize = function () {
  54920. var serializationObject = {};
  54921. serializationObject.isEnabled = this.isEnabled;
  54922. serializationObject.leftColor = this.leftColor;
  54923. serializationObject.rightColor = this.rightColor;
  54924. serializationObject.bias = this.bias;
  54925. serializationObject.power = this.power;
  54926. return serializationObject;
  54927. };
  54928. FresnelParameters.Parse = function (parsedFresnelParameters) {
  54929. var fresnelParameters = new FresnelParameters();
  54930. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  54931. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  54932. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  54933. fresnelParameters.bias = parsedFresnelParameters.bias;
  54934. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  54935. return fresnelParameters;
  54936. };
  54937. return FresnelParameters;
  54938. }());
  54939. BABYLON.FresnelParameters = FresnelParameters;
  54940. })(BABYLON || (BABYLON = {}));
  54941. //# sourceMappingURL=babylon.fresnelParameters.js.map
  54942. var BABYLON;
  54943. (function (BABYLON) {
  54944. var MultiMaterial = /** @class */ (function (_super) {
  54945. __extends(MultiMaterial, _super);
  54946. function MultiMaterial(name, scene) {
  54947. var _this = _super.call(this, name, scene, true) || this;
  54948. scene.multiMaterials.push(_this);
  54949. _this.subMaterials = new Array();
  54950. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  54951. return _this;
  54952. }
  54953. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  54954. get: function () {
  54955. return this._subMaterials;
  54956. },
  54957. set: function (value) {
  54958. this._subMaterials = value;
  54959. this._hookArray(value);
  54960. },
  54961. enumerable: true,
  54962. configurable: true
  54963. });
  54964. MultiMaterial.prototype._hookArray = function (array) {
  54965. var _this = this;
  54966. var oldPush = array.push;
  54967. array.push = function () {
  54968. var items = [];
  54969. for (var _i = 0; _i < arguments.length; _i++) {
  54970. items[_i] = arguments[_i];
  54971. }
  54972. var result = oldPush.apply(array, items);
  54973. _this._markAllSubMeshesAsTexturesDirty();
  54974. return result;
  54975. };
  54976. var oldSplice = array.splice;
  54977. array.splice = function (index, deleteCount) {
  54978. var deleted = oldSplice.apply(array, [index, deleteCount]);
  54979. _this._markAllSubMeshesAsTexturesDirty();
  54980. return deleted;
  54981. };
  54982. };
  54983. // Properties
  54984. MultiMaterial.prototype.getSubMaterial = function (index) {
  54985. if (index < 0 || index >= this.subMaterials.length) {
  54986. return this.getScene().defaultMaterial;
  54987. }
  54988. return this.subMaterials[index];
  54989. };
  54990. MultiMaterial.prototype.getActiveTextures = function () {
  54991. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  54992. if (subMaterial) {
  54993. return subMaterial.getActiveTextures();
  54994. }
  54995. else {
  54996. return [];
  54997. }
  54998. }));
  54999. var _a;
  55000. };
  55001. // Methods
  55002. MultiMaterial.prototype.getClassName = function () {
  55003. return "MultiMaterial";
  55004. };
  55005. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  55006. for (var index = 0; index < this.subMaterials.length; index++) {
  55007. var subMaterial = this.subMaterials[index];
  55008. if (subMaterial) {
  55009. if (subMaterial.storeEffectOnSubMeshes) {
  55010. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  55011. return false;
  55012. }
  55013. continue;
  55014. }
  55015. if (!subMaterial.isReady(mesh)) {
  55016. return false;
  55017. }
  55018. }
  55019. }
  55020. return true;
  55021. };
  55022. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  55023. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  55024. for (var index = 0; index < this.subMaterials.length; index++) {
  55025. var subMaterial = null;
  55026. var current = this.subMaterials[index];
  55027. if (cloneChildren && current) {
  55028. subMaterial = current.clone(name + "-" + current.name);
  55029. }
  55030. else {
  55031. subMaterial = this.subMaterials[index];
  55032. }
  55033. newMultiMaterial.subMaterials.push(subMaterial);
  55034. }
  55035. return newMultiMaterial;
  55036. };
  55037. MultiMaterial.prototype.serialize = function () {
  55038. var serializationObject = {};
  55039. serializationObject.name = this.name;
  55040. serializationObject.id = this.id;
  55041. if (BABYLON.Tags) {
  55042. serializationObject.tags = BABYLON.Tags.GetTags(this);
  55043. }
  55044. serializationObject.materials = [];
  55045. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  55046. var subMat = this.subMaterials[matIndex];
  55047. if (subMat) {
  55048. serializationObject.materials.push(subMat.id);
  55049. }
  55050. else {
  55051. serializationObject.materials.push(null);
  55052. }
  55053. }
  55054. return serializationObject;
  55055. };
  55056. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  55057. var scene = this.getScene();
  55058. if (!scene) {
  55059. return;
  55060. }
  55061. var index = scene.multiMaterials.indexOf(this);
  55062. if (index >= 0) {
  55063. scene.multiMaterials.splice(index, 1);
  55064. }
  55065. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  55066. };
  55067. return MultiMaterial;
  55068. }(BABYLON.Material));
  55069. BABYLON.MultiMaterial = MultiMaterial;
  55070. })(BABYLON || (BABYLON = {}));
  55071. //# sourceMappingURL=babylon.multiMaterial.js.map
  55072. var BABYLON;
  55073. (function (BABYLON) {
  55074. var FreeCameraTouchInput = /** @class */ (function () {
  55075. function FreeCameraTouchInput() {
  55076. this._offsetX = null;
  55077. this._offsetY = null;
  55078. this._pointerPressed = new Array();
  55079. this.touchAngularSensibility = 200000.0;
  55080. this.touchMoveSensibility = 250.0;
  55081. }
  55082. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  55083. var _this = this;
  55084. var previousPosition = null;
  55085. if (this._pointerInput === undefined) {
  55086. this._onLostFocus = function (evt) {
  55087. _this._offsetX = null;
  55088. _this._offsetY = null;
  55089. };
  55090. this._pointerInput = function (p, s) {
  55091. var evt = p.event;
  55092. if (evt.pointerType === "mouse") {
  55093. return;
  55094. }
  55095. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  55096. if (!noPreventDefault) {
  55097. evt.preventDefault();
  55098. }
  55099. _this._pointerPressed.push(evt.pointerId);
  55100. if (_this._pointerPressed.length !== 1) {
  55101. return;
  55102. }
  55103. previousPosition = {
  55104. x: evt.clientX,
  55105. y: evt.clientY
  55106. };
  55107. }
  55108. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  55109. if (!noPreventDefault) {
  55110. evt.preventDefault();
  55111. }
  55112. var index = _this._pointerPressed.indexOf(evt.pointerId);
  55113. if (index === -1) {
  55114. return;
  55115. }
  55116. _this._pointerPressed.splice(index, 1);
  55117. if (index != 0) {
  55118. return;
  55119. }
  55120. previousPosition = null;
  55121. _this._offsetX = null;
  55122. _this._offsetY = null;
  55123. }
  55124. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  55125. if (!noPreventDefault) {
  55126. evt.preventDefault();
  55127. }
  55128. if (!previousPosition) {
  55129. return;
  55130. }
  55131. var index = _this._pointerPressed.indexOf(evt.pointerId);
  55132. if (index != 0) {
  55133. return;
  55134. }
  55135. _this._offsetX = evt.clientX - previousPosition.x;
  55136. _this._offsetY = -(evt.clientY - previousPosition.y);
  55137. }
  55138. };
  55139. }
  55140. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  55141. if (this._onLostFocus) {
  55142. element.addEventListener("blur", this._onLostFocus);
  55143. }
  55144. };
  55145. FreeCameraTouchInput.prototype.detachControl = function (element) {
  55146. if (this._pointerInput && element) {
  55147. if (this._observer) {
  55148. this.camera.getScene().onPointerObservable.remove(this._observer);
  55149. this._observer = null;
  55150. }
  55151. if (this._onLostFocus) {
  55152. element.removeEventListener("blur", this._onLostFocus);
  55153. this._onLostFocus = null;
  55154. }
  55155. this._pointerPressed = [];
  55156. this._offsetX = null;
  55157. this._offsetY = null;
  55158. }
  55159. };
  55160. FreeCameraTouchInput.prototype.checkInputs = function () {
  55161. if (this._offsetX && this._offsetY) {
  55162. var camera = this.camera;
  55163. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  55164. if (this._pointerPressed.length > 1) {
  55165. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  55166. }
  55167. else {
  55168. var speed = camera._computeLocalCameraSpeed();
  55169. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  55170. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  55171. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  55172. }
  55173. }
  55174. };
  55175. FreeCameraTouchInput.prototype.getClassName = function () {
  55176. return "FreeCameraTouchInput";
  55177. };
  55178. FreeCameraTouchInput.prototype.getSimpleName = function () {
  55179. return "touch";
  55180. };
  55181. __decorate([
  55182. BABYLON.serialize()
  55183. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  55184. __decorate([
  55185. BABYLON.serialize()
  55186. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  55187. return FreeCameraTouchInput;
  55188. }());
  55189. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  55190. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  55191. })(BABYLON || (BABYLON = {}));
  55192. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  55193. var BABYLON;
  55194. (function (BABYLON) {
  55195. // We're mainly based on the logic defined into the FreeCamera code
  55196. var TouchCamera = /** @class */ (function (_super) {
  55197. __extends(TouchCamera, _super);
  55198. //-- end properties for backward compatibility for inputs
  55199. function TouchCamera(name, position, scene) {
  55200. var _this = _super.call(this, name, position, scene) || this;
  55201. _this.inputs.addTouch();
  55202. _this._setupInputs();
  55203. return _this;
  55204. }
  55205. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  55206. //-- Begin properties for backward compatibility for inputs
  55207. get: function () {
  55208. var touch = this.inputs.attached["touch"];
  55209. if (touch)
  55210. return touch.touchAngularSensibility;
  55211. return 0;
  55212. },
  55213. set: function (value) {
  55214. var touch = this.inputs.attached["touch"];
  55215. if (touch)
  55216. touch.touchAngularSensibility = value;
  55217. },
  55218. enumerable: true,
  55219. configurable: true
  55220. });
  55221. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  55222. get: function () {
  55223. var touch = this.inputs.attached["touch"];
  55224. if (touch)
  55225. return touch.touchMoveSensibility;
  55226. return 0;
  55227. },
  55228. set: function (value) {
  55229. var touch = this.inputs.attached["touch"];
  55230. if (touch)
  55231. touch.touchMoveSensibility = value;
  55232. },
  55233. enumerable: true,
  55234. configurable: true
  55235. });
  55236. TouchCamera.prototype.getClassName = function () {
  55237. return "TouchCamera";
  55238. };
  55239. TouchCamera.prototype._setupInputs = function () {
  55240. var mouse = this.inputs.attached["mouse"];
  55241. if (mouse) {
  55242. mouse.touchEnabled = false;
  55243. }
  55244. };
  55245. return TouchCamera;
  55246. }(BABYLON.FreeCamera));
  55247. BABYLON.TouchCamera = TouchCamera;
  55248. })(BABYLON || (BABYLON = {}));
  55249. //# sourceMappingURL=babylon.touchCamera.js.map
  55250. var BABYLON;
  55251. (function (BABYLON) {
  55252. var ProceduralTexture = /** @class */ (function (_super) {
  55253. __extends(ProceduralTexture, _super);
  55254. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  55255. if (fallbackTexture === void 0) { fallbackTexture = null; }
  55256. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55257. if (isCube === void 0) { isCube = false; }
  55258. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  55259. _this.isCube = isCube;
  55260. _this.isEnabled = true;
  55261. _this._currentRefreshId = -1;
  55262. _this._refreshRate = 1;
  55263. _this._vertexBuffers = {};
  55264. _this._uniforms = new Array();
  55265. _this._samplers = new Array();
  55266. _this._textures = {};
  55267. _this._floats = {};
  55268. _this._floatsArrays = {};
  55269. _this._colors3 = {};
  55270. _this._colors4 = {};
  55271. _this._vectors2 = {};
  55272. _this._vectors3 = {};
  55273. _this._matrices = {};
  55274. _this._fallbackTextureUsed = false;
  55275. scene._proceduralTextures.push(_this);
  55276. _this._engine = scene.getEngine();
  55277. _this.name = name;
  55278. _this.isRenderTarget = true;
  55279. _this._size = size;
  55280. _this._generateMipMaps = generateMipMaps;
  55281. _this.setFragment(fragment);
  55282. _this._fallbackTexture = fallbackTexture;
  55283. if (isCube) {
  55284. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  55285. _this.setFloat("face", 0);
  55286. }
  55287. else {
  55288. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  55289. }
  55290. // VBO
  55291. var vertices = [];
  55292. vertices.push(1, 1);
  55293. vertices.push(-1, 1);
  55294. vertices.push(-1, -1);
  55295. vertices.push(1, -1);
  55296. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  55297. _this._createIndexBuffer();
  55298. return _this;
  55299. }
  55300. ProceduralTexture.prototype._createIndexBuffer = function () {
  55301. var engine = this._engine;
  55302. // Indices
  55303. var indices = [];
  55304. indices.push(0);
  55305. indices.push(1);
  55306. indices.push(2);
  55307. indices.push(0);
  55308. indices.push(2);
  55309. indices.push(3);
  55310. this._indexBuffer = engine.createIndexBuffer(indices);
  55311. };
  55312. ProceduralTexture.prototype._rebuild = function () {
  55313. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  55314. if (vb) {
  55315. vb._rebuild();
  55316. }
  55317. this._createIndexBuffer();
  55318. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  55319. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  55320. }
  55321. };
  55322. ProceduralTexture.prototype.reset = function () {
  55323. if (this._effect === undefined) {
  55324. return;
  55325. }
  55326. var engine = this._engine;
  55327. engine._releaseEffect(this._effect);
  55328. };
  55329. ProceduralTexture.prototype.isReady = function () {
  55330. var _this = this;
  55331. var engine = this._engine;
  55332. var shaders;
  55333. if (!this._fragment) {
  55334. return false;
  55335. }
  55336. if (this._fallbackTextureUsed) {
  55337. return true;
  55338. }
  55339. if (this._fragment.fragmentElement !== undefined) {
  55340. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  55341. }
  55342. else {
  55343. shaders = { vertex: "procedural", fragment: this._fragment };
  55344. }
  55345. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  55346. _this.releaseInternalTexture();
  55347. if (_this._fallbackTexture) {
  55348. _this._texture = _this._fallbackTexture._texture;
  55349. if (_this._texture) {
  55350. _this._texture.incrementReferences();
  55351. }
  55352. }
  55353. _this._fallbackTextureUsed = true;
  55354. });
  55355. return this._effect.isReady();
  55356. };
  55357. ProceduralTexture.prototype.resetRefreshCounter = function () {
  55358. this._currentRefreshId = -1;
  55359. };
  55360. ProceduralTexture.prototype.setFragment = function (fragment) {
  55361. this._fragment = fragment;
  55362. };
  55363. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  55364. get: function () {
  55365. return this._refreshRate;
  55366. },
  55367. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  55368. set: function (value) {
  55369. this._refreshRate = value;
  55370. this.resetRefreshCounter();
  55371. },
  55372. enumerable: true,
  55373. configurable: true
  55374. });
  55375. ProceduralTexture.prototype._shouldRender = function () {
  55376. if (!this.isEnabled || !this.isReady() || !this._texture) {
  55377. return false;
  55378. }
  55379. if (this._fallbackTextureUsed) {
  55380. return false;
  55381. }
  55382. if (this._currentRefreshId === -1) {
  55383. this._currentRefreshId = 1;
  55384. return true;
  55385. }
  55386. if (this.refreshRate === this._currentRefreshId) {
  55387. this._currentRefreshId = 1;
  55388. return true;
  55389. }
  55390. this._currentRefreshId++;
  55391. return false;
  55392. };
  55393. ProceduralTexture.prototype.getRenderSize = function () {
  55394. return this._size;
  55395. };
  55396. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  55397. if (this._fallbackTextureUsed) {
  55398. return;
  55399. }
  55400. this.releaseInternalTexture();
  55401. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  55402. };
  55403. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  55404. if (this._uniforms.indexOf(uniformName) === -1) {
  55405. this._uniforms.push(uniformName);
  55406. }
  55407. };
  55408. ProceduralTexture.prototype.setTexture = function (name, texture) {
  55409. if (this._samplers.indexOf(name) === -1) {
  55410. this._samplers.push(name);
  55411. }
  55412. this._textures[name] = texture;
  55413. return this;
  55414. };
  55415. ProceduralTexture.prototype.setFloat = function (name, value) {
  55416. this._checkUniform(name);
  55417. this._floats[name] = value;
  55418. return this;
  55419. };
  55420. ProceduralTexture.prototype.setFloats = function (name, value) {
  55421. this._checkUniform(name);
  55422. this._floatsArrays[name] = value;
  55423. return this;
  55424. };
  55425. ProceduralTexture.prototype.setColor3 = function (name, value) {
  55426. this._checkUniform(name);
  55427. this._colors3[name] = value;
  55428. return this;
  55429. };
  55430. ProceduralTexture.prototype.setColor4 = function (name, value) {
  55431. this._checkUniform(name);
  55432. this._colors4[name] = value;
  55433. return this;
  55434. };
  55435. ProceduralTexture.prototype.setVector2 = function (name, value) {
  55436. this._checkUniform(name);
  55437. this._vectors2[name] = value;
  55438. return this;
  55439. };
  55440. ProceduralTexture.prototype.setVector3 = function (name, value) {
  55441. this._checkUniform(name);
  55442. this._vectors3[name] = value;
  55443. return this;
  55444. };
  55445. ProceduralTexture.prototype.setMatrix = function (name, value) {
  55446. this._checkUniform(name);
  55447. this._matrices[name] = value;
  55448. return this;
  55449. };
  55450. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  55451. var scene = this.getScene();
  55452. if (!scene) {
  55453. return;
  55454. }
  55455. var engine = this._engine;
  55456. // Render
  55457. engine.enableEffect(this._effect);
  55458. engine.setState(false);
  55459. // Texture
  55460. for (var name in this._textures) {
  55461. this._effect.setTexture(name, this._textures[name]);
  55462. }
  55463. // Float
  55464. for (name in this._floats) {
  55465. this._effect.setFloat(name, this._floats[name]);
  55466. }
  55467. // Floats
  55468. for (name in this._floatsArrays) {
  55469. this._effect.setArray(name, this._floatsArrays[name]);
  55470. }
  55471. // Color3
  55472. for (name in this._colors3) {
  55473. this._effect.setColor3(name, this._colors3[name]);
  55474. }
  55475. // Color4
  55476. for (name in this._colors4) {
  55477. var color = this._colors4[name];
  55478. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  55479. }
  55480. // Vector2
  55481. for (name in this._vectors2) {
  55482. this._effect.setVector2(name, this._vectors2[name]);
  55483. }
  55484. // Vector3
  55485. for (name in this._vectors3) {
  55486. this._effect.setVector3(name, this._vectors3[name]);
  55487. }
  55488. // Matrix
  55489. for (name in this._matrices) {
  55490. this._effect.setMatrix(name, this._matrices[name]);
  55491. }
  55492. if (!this._texture) {
  55493. return;
  55494. }
  55495. if (this.isCube) {
  55496. for (var face = 0; face < 6; face++) {
  55497. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  55498. // VBOs
  55499. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  55500. this._effect.setFloat("face", face);
  55501. // Clear
  55502. engine.clear(scene.clearColor, true, true, true);
  55503. // Draw order
  55504. engine.draw(true, 0, 6);
  55505. // Mipmaps
  55506. if (face === 5) {
  55507. engine.generateMipMapsForCubemap(this._texture);
  55508. }
  55509. }
  55510. }
  55511. else {
  55512. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  55513. // VBOs
  55514. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  55515. // Clear
  55516. engine.clear(scene.clearColor, true, true, true);
  55517. // Draw order
  55518. engine.draw(true, 0, 6);
  55519. }
  55520. // Unbind
  55521. engine.unBindFramebuffer(this._texture, this.isCube);
  55522. if (this.onGenerated) {
  55523. this.onGenerated();
  55524. }
  55525. };
  55526. ProceduralTexture.prototype.clone = function () {
  55527. var textureSize = this.getSize();
  55528. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  55529. // Base texture
  55530. newTexture.hasAlpha = this.hasAlpha;
  55531. newTexture.level = this.level;
  55532. // RenderTarget Texture
  55533. newTexture.coordinatesMode = this.coordinatesMode;
  55534. return newTexture;
  55535. };
  55536. ProceduralTexture.prototype.dispose = function () {
  55537. var scene = this.getScene();
  55538. if (!scene) {
  55539. return;
  55540. }
  55541. var index = scene._proceduralTextures.indexOf(this);
  55542. if (index >= 0) {
  55543. scene._proceduralTextures.splice(index, 1);
  55544. }
  55545. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  55546. if (vertexBuffer) {
  55547. vertexBuffer.dispose();
  55548. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  55549. }
  55550. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  55551. this._indexBuffer = null;
  55552. }
  55553. _super.prototype.dispose.call(this);
  55554. };
  55555. return ProceduralTexture;
  55556. }(BABYLON.Texture));
  55557. BABYLON.ProceduralTexture = ProceduralTexture;
  55558. })(BABYLON || (BABYLON = {}));
  55559. //# sourceMappingURL=babylon.proceduralTexture.js.map
  55560. var BABYLON;
  55561. (function (BABYLON) {
  55562. var CustomProceduralTexture = /** @class */ (function (_super) {
  55563. __extends(CustomProceduralTexture, _super);
  55564. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  55565. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  55566. _this._animate = true;
  55567. _this._time = 0;
  55568. _this._texturePath = texturePath;
  55569. //Try to load json
  55570. _this.loadJson(texturePath);
  55571. _this.refreshRate = 1;
  55572. return _this;
  55573. }
  55574. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  55575. var _this = this;
  55576. var noConfigFile = function () {
  55577. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  55578. try {
  55579. _this.setFragment(_this._texturePath);
  55580. }
  55581. catch (ex) {
  55582. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  55583. }
  55584. };
  55585. var configFileUrl = jsonUrl + "/config.json";
  55586. var xhr = new XMLHttpRequest();
  55587. xhr.open("GET", configFileUrl, true);
  55588. xhr.addEventListener("load", function () {
  55589. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  55590. try {
  55591. _this._config = JSON.parse(xhr.response);
  55592. _this.updateShaderUniforms();
  55593. _this.updateTextures();
  55594. _this.setFragment(_this._texturePath + "/custom");
  55595. _this._animate = _this._config.animate;
  55596. _this.refreshRate = _this._config.refreshrate;
  55597. }
  55598. catch (ex) {
  55599. noConfigFile();
  55600. }
  55601. }
  55602. else {
  55603. noConfigFile();
  55604. }
  55605. }, false);
  55606. xhr.addEventListener("error", function () {
  55607. noConfigFile();
  55608. }, false);
  55609. try {
  55610. xhr.send();
  55611. }
  55612. catch (ex) {
  55613. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  55614. }
  55615. };
  55616. CustomProceduralTexture.prototype.isReady = function () {
  55617. if (!_super.prototype.isReady.call(this)) {
  55618. return false;
  55619. }
  55620. for (var name in this._textures) {
  55621. var texture = this._textures[name];
  55622. if (!texture.isReady()) {
  55623. return false;
  55624. }
  55625. }
  55626. return true;
  55627. };
  55628. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  55629. var scene = this.getScene();
  55630. if (this._animate && scene) {
  55631. this._time += scene.getAnimationRatio() * 0.03;
  55632. this.updateShaderUniforms();
  55633. }
  55634. _super.prototype.render.call(this, useCameraPostProcess);
  55635. };
  55636. CustomProceduralTexture.prototype.updateTextures = function () {
  55637. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  55638. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  55639. }
  55640. };
  55641. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  55642. if (this._config) {
  55643. for (var j = 0; j < this._config.uniforms.length; j++) {
  55644. var uniform = this._config.uniforms[j];
  55645. switch (uniform.type) {
  55646. case "float":
  55647. this.setFloat(uniform.name, uniform.value);
  55648. break;
  55649. case "color3":
  55650. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  55651. break;
  55652. case "color4":
  55653. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  55654. break;
  55655. case "vector2":
  55656. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  55657. break;
  55658. case "vector3":
  55659. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  55660. break;
  55661. }
  55662. }
  55663. }
  55664. this.setFloat("time", this._time);
  55665. };
  55666. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  55667. get: function () {
  55668. return this._animate;
  55669. },
  55670. set: function (value) {
  55671. this._animate = value;
  55672. },
  55673. enumerable: true,
  55674. configurable: true
  55675. });
  55676. return CustomProceduralTexture;
  55677. }(BABYLON.ProceduralTexture));
  55678. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  55679. })(BABYLON || (BABYLON = {}));
  55680. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  55681. var BABYLON;
  55682. (function (BABYLON) {
  55683. var FreeCameraGamepadInput = /** @class */ (function () {
  55684. function FreeCameraGamepadInput() {
  55685. this.gamepadAngularSensibility = 200;
  55686. this.gamepadMoveSensibility = 40;
  55687. // private members
  55688. this._cameraTransform = BABYLON.Matrix.Identity();
  55689. this._deltaTransform = BABYLON.Vector3.Zero();
  55690. this._vector3 = BABYLON.Vector3.Zero();
  55691. this._vector2 = BABYLON.Vector2.Zero();
  55692. }
  55693. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  55694. var _this = this;
  55695. var manager = this.camera.getScene().gamepadManager;
  55696. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  55697. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  55698. // prioritize XBOX gamepads.
  55699. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  55700. _this.gamepad = gamepad;
  55701. }
  55702. }
  55703. });
  55704. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  55705. if (_this.gamepad === gamepad) {
  55706. _this.gamepad = null;
  55707. }
  55708. });
  55709. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  55710. };
  55711. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  55712. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  55713. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  55714. this.gamepad = null;
  55715. };
  55716. FreeCameraGamepadInput.prototype.checkInputs = function () {
  55717. if (this.gamepad && this.gamepad.leftStick) {
  55718. var camera = this.camera;
  55719. var LSValues = this.gamepad.leftStick;
  55720. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  55721. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  55722. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  55723. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  55724. var RSValues = this.gamepad.rightStick;
  55725. if (RSValues) {
  55726. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  55727. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  55728. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  55729. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  55730. }
  55731. else {
  55732. RSValues = { x: 0, y: 0 };
  55733. }
  55734. if (!camera.rotationQuaternion) {
  55735. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  55736. }
  55737. else {
  55738. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  55739. }
  55740. var speed = camera._computeLocalCameraSpeed() * 50.0;
  55741. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  55742. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  55743. camera.cameraDirection.addInPlace(this._deltaTransform);
  55744. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  55745. camera.cameraRotation.addInPlace(this._vector2);
  55746. }
  55747. };
  55748. FreeCameraGamepadInput.prototype.getClassName = function () {
  55749. return "FreeCameraGamepadInput";
  55750. };
  55751. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  55752. return "gamepad";
  55753. };
  55754. __decorate([
  55755. BABYLON.serialize()
  55756. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  55757. __decorate([
  55758. BABYLON.serialize()
  55759. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  55760. return FreeCameraGamepadInput;
  55761. }());
  55762. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  55763. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  55764. })(BABYLON || (BABYLON = {}));
  55765. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  55766. var BABYLON;
  55767. (function (BABYLON) {
  55768. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  55769. function ArcRotateCameraGamepadInput() {
  55770. this.gamepadRotationSensibility = 80;
  55771. this.gamepadMoveSensibility = 40;
  55772. }
  55773. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  55774. var _this = this;
  55775. var manager = this.camera.getScene().gamepadManager;
  55776. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  55777. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  55778. // prioritize XBOX gamepads.
  55779. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  55780. _this.gamepad = gamepad;
  55781. }
  55782. }
  55783. });
  55784. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  55785. if (_this.gamepad === gamepad) {
  55786. _this.gamepad = null;
  55787. }
  55788. });
  55789. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  55790. };
  55791. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  55792. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  55793. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  55794. this.gamepad = null;
  55795. };
  55796. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  55797. if (this.gamepad) {
  55798. var camera = this.camera;
  55799. var RSValues = this.gamepad.rightStick;
  55800. if (RSValues) {
  55801. if (RSValues.x != 0) {
  55802. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  55803. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  55804. camera.inertialAlphaOffset += normalizedRX;
  55805. }
  55806. }
  55807. if (RSValues.y != 0) {
  55808. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  55809. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  55810. camera.inertialBetaOffset += normalizedRY;
  55811. }
  55812. }
  55813. }
  55814. var LSValues = this.gamepad.leftStick;
  55815. if (LSValues && LSValues.y != 0) {
  55816. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  55817. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  55818. this.camera.inertialRadiusOffset -= normalizedLY;
  55819. }
  55820. }
  55821. }
  55822. };
  55823. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  55824. return "ArcRotateCameraGamepadInput";
  55825. };
  55826. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  55827. return "gamepad";
  55828. };
  55829. __decorate([
  55830. BABYLON.serialize()
  55831. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  55832. __decorate([
  55833. BABYLON.serialize()
  55834. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  55835. return ArcRotateCameraGamepadInput;
  55836. }());
  55837. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  55838. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  55839. })(BABYLON || (BABYLON = {}));
  55840. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  55841. var BABYLON;
  55842. (function (BABYLON) {
  55843. var GamepadManager = /** @class */ (function () {
  55844. function GamepadManager(_scene) {
  55845. var _this = this;
  55846. this._scene = _scene;
  55847. this._babylonGamepads = [];
  55848. this._oneGamepadConnected = false;
  55849. this._isMonitoring = false;
  55850. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  55851. if (!BABYLON.Tools.IsWindowObjectExist()) {
  55852. this._gamepadEventSupported = false;
  55853. }
  55854. else {
  55855. this._gamepadEventSupported = 'GamepadEvent' in window;
  55856. this._gamepadSupport = (navigator.getGamepads ||
  55857. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  55858. }
  55859. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  55860. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  55861. for (var i in _this._babylonGamepads) {
  55862. var gamepad = _this._babylonGamepads[i];
  55863. if (gamepad && gamepad._isConnected) {
  55864. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  55865. }
  55866. }
  55867. });
  55868. this._onGamepadConnectedEvent = function (evt) {
  55869. var gamepad = evt.gamepad;
  55870. if (gamepad.index in _this._babylonGamepads) {
  55871. if (_this._babylonGamepads[gamepad.index].isConnected) {
  55872. return;
  55873. }
  55874. }
  55875. var newGamepad;
  55876. if (_this._babylonGamepads[gamepad.index]) {
  55877. newGamepad = _this._babylonGamepads[gamepad.index];
  55878. newGamepad.browserGamepad = gamepad;
  55879. newGamepad._isConnected = true;
  55880. }
  55881. else {
  55882. newGamepad = _this._addNewGamepad(gamepad);
  55883. }
  55884. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  55885. _this._startMonitoringGamepads();
  55886. };
  55887. this._onGamepadDisconnectedEvent = function (evt) {
  55888. var gamepad = evt.gamepad;
  55889. // Remove the gamepad from the list of gamepads to monitor.
  55890. for (var i in _this._babylonGamepads) {
  55891. if (_this._babylonGamepads[i].index === gamepad.index) {
  55892. var disconnectedGamepad = _this._babylonGamepads[i];
  55893. disconnectedGamepad._isConnected = false;
  55894. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  55895. break;
  55896. }
  55897. }
  55898. };
  55899. if (this._gamepadSupport) {
  55900. //first add already-connected gamepads
  55901. this._updateGamepadObjects();
  55902. if (this._babylonGamepads.length) {
  55903. this._startMonitoringGamepads();
  55904. }
  55905. // Checking if the gamepad connected event is supported (like in Firefox)
  55906. if (this._gamepadEventSupported) {
  55907. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  55908. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  55909. }
  55910. else {
  55911. this._startMonitoringGamepads();
  55912. }
  55913. }
  55914. }
  55915. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  55916. get: function () {
  55917. return this._babylonGamepads;
  55918. },
  55919. enumerable: true,
  55920. configurable: true
  55921. });
  55922. GamepadManager.prototype.getGamepadByType = function (type) {
  55923. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  55924. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  55925. var gamepad = _a[_i];
  55926. if (gamepad && gamepad.type === type) {
  55927. return gamepad;
  55928. }
  55929. }
  55930. return null;
  55931. };
  55932. GamepadManager.prototype.dispose = function () {
  55933. if (this._gamepadEventSupported) {
  55934. if (this._onGamepadConnectedEvent) {
  55935. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  55936. }
  55937. if (this._onGamepadDisconnectedEvent) {
  55938. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  55939. }
  55940. this._onGamepadConnectedEvent = null;
  55941. this._onGamepadDisconnectedEvent = null;
  55942. }
  55943. this._babylonGamepads.forEach(function (gamepad) {
  55944. gamepad.dispose();
  55945. });
  55946. this.onGamepadConnectedObservable.clear();
  55947. this.onGamepadDisconnectedObservable.clear();
  55948. this._oneGamepadConnected = false;
  55949. this._stopMonitoringGamepads();
  55950. this._babylonGamepads = [];
  55951. };
  55952. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  55953. if (!this._oneGamepadConnected) {
  55954. this._oneGamepadConnected = true;
  55955. }
  55956. var newGamepad;
  55957. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  55958. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  55959. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  55960. }
  55961. else if (gamepad.pose) {
  55962. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  55963. }
  55964. else {
  55965. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  55966. }
  55967. this._babylonGamepads[newGamepad.index] = newGamepad;
  55968. return newGamepad;
  55969. };
  55970. GamepadManager.prototype._startMonitoringGamepads = function () {
  55971. if (!this._isMonitoring) {
  55972. this._isMonitoring = true;
  55973. //back-comp
  55974. if (!this._scene) {
  55975. this._checkGamepadsStatus();
  55976. }
  55977. }
  55978. };
  55979. GamepadManager.prototype._stopMonitoringGamepads = function () {
  55980. this._isMonitoring = false;
  55981. };
  55982. GamepadManager.prototype._checkGamepadsStatus = function () {
  55983. var _this = this;
  55984. // Hack to be compatible Chrome
  55985. this._updateGamepadObjects();
  55986. for (var i in this._babylonGamepads) {
  55987. var gamepad = this._babylonGamepads[i];
  55988. if (!gamepad || !gamepad.isConnected) {
  55989. continue;
  55990. }
  55991. gamepad.update();
  55992. }
  55993. if (this._isMonitoring && !this._scene) {
  55994. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  55995. }
  55996. };
  55997. // This function is called only on Chrome, which does not properly support
  55998. // connection/disconnection events and forces you to recopy again the gamepad object
  55999. GamepadManager.prototype._updateGamepadObjects = function () {
  56000. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  56001. for (var i = 0; i < gamepads.length; i++) {
  56002. if (gamepads[i]) {
  56003. if (!this._babylonGamepads[gamepads[i].index]) {
  56004. var newGamepad = this._addNewGamepad(gamepads[i]);
  56005. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  56006. }
  56007. else {
  56008. // Forced to copy again this object for Chrome for unknown reason
  56009. this._babylonGamepads[i].browserGamepad = gamepads[i];
  56010. if (!this._babylonGamepads[i].isConnected) {
  56011. this._babylonGamepads[i]._isConnected = true;
  56012. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  56013. }
  56014. }
  56015. }
  56016. }
  56017. };
  56018. return GamepadManager;
  56019. }());
  56020. BABYLON.GamepadManager = GamepadManager;
  56021. })(BABYLON || (BABYLON = {}));
  56022. //# sourceMappingURL=babylon.gamepadManager.js.map
  56023. var BABYLON;
  56024. (function (BABYLON) {
  56025. var StickValues = /** @class */ (function () {
  56026. function StickValues(x, y) {
  56027. this.x = x;
  56028. this.y = y;
  56029. }
  56030. return StickValues;
  56031. }());
  56032. BABYLON.StickValues = StickValues;
  56033. var Gamepad = /** @class */ (function () {
  56034. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  56035. if (leftStickX === void 0) { leftStickX = 0; }
  56036. if (leftStickY === void 0) { leftStickY = 1; }
  56037. if (rightStickX === void 0) { rightStickX = 2; }
  56038. if (rightStickY === void 0) { rightStickY = 3; }
  56039. this.id = id;
  56040. this.index = index;
  56041. this.browserGamepad = browserGamepad;
  56042. this._isConnected = true;
  56043. this.type = Gamepad.GAMEPAD;
  56044. this._leftStickAxisX = leftStickX;
  56045. this._leftStickAxisY = leftStickY;
  56046. this._rightStickAxisX = rightStickX;
  56047. this._rightStickAxisY = rightStickY;
  56048. if (this.browserGamepad.axes.length >= 2) {
  56049. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  56050. }
  56051. if (this.browserGamepad.axes.length >= 4) {
  56052. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  56053. }
  56054. }
  56055. Object.defineProperty(Gamepad.prototype, "isConnected", {
  56056. get: function () {
  56057. return this._isConnected;
  56058. },
  56059. enumerable: true,
  56060. configurable: true
  56061. });
  56062. Gamepad.prototype.onleftstickchanged = function (callback) {
  56063. this._onleftstickchanged = callback;
  56064. };
  56065. Gamepad.prototype.onrightstickchanged = function (callback) {
  56066. this._onrightstickchanged = callback;
  56067. };
  56068. Object.defineProperty(Gamepad.prototype, "leftStick", {
  56069. get: function () {
  56070. return this._leftStick;
  56071. },
  56072. set: function (newValues) {
  56073. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  56074. this._onleftstickchanged(newValues);
  56075. }
  56076. this._leftStick = newValues;
  56077. },
  56078. enumerable: true,
  56079. configurable: true
  56080. });
  56081. Object.defineProperty(Gamepad.prototype, "rightStick", {
  56082. get: function () {
  56083. return this._rightStick;
  56084. },
  56085. set: function (newValues) {
  56086. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  56087. this._onrightstickchanged(newValues);
  56088. }
  56089. this._rightStick = newValues;
  56090. },
  56091. enumerable: true,
  56092. configurable: true
  56093. });
  56094. Gamepad.prototype.update = function () {
  56095. if (this._leftStick) {
  56096. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  56097. }
  56098. if (this._rightStick) {
  56099. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  56100. }
  56101. };
  56102. Gamepad.prototype.dispose = function () {
  56103. };
  56104. Gamepad.GAMEPAD = 0;
  56105. Gamepad.GENERIC = 1;
  56106. Gamepad.XBOX = 2;
  56107. Gamepad.POSE_ENABLED = 3;
  56108. return Gamepad;
  56109. }());
  56110. BABYLON.Gamepad = Gamepad;
  56111. var GenericPad = /** @class */ (function (_super) {
  56112. __extends(GenericPad, _super);
  56113. function GenericPad(id, index, browserGamepad) {
  56114. var _this = _super.call(this, id, index, browserGamepad) || this;
  56115. _this.onButtonDownObservable = new BABYLON.Observable();
  56116. _this.onButtonUpObservable = new BABYLON.Observable();
  56117. _this.type = Gamepad.GENERIC;
  56118. _this._buttons = new Array(browserGamepad.buttons.length);
  56119. return _this;
  56120. }
  56121. GenericPad.prototype.onbuttondown = function (callback) {
  56122. this._onbuttondown = callback;
  56123. };
  56124. GenericPad.prototype.onbuttonup = function (callback) {
  56125. this._onbuttonup = callback;
  56126. };
  56127. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  56128. if (newValue !== currentValue) {
  56129. if (newValue === 1) {
  56130. if (this._onbuttondown) {
  56131. this._onbuttondown(buttonIndex);
  56132. }
  56133. this.onButtonDownObservable.notifyObservers(buttonIndex);
  56134. }
  56135. if (newValue === 0) {
  56136. if (this._onbuttonup) {
  56137. this._onbuttonup(buttonIndex);
  56138. }
  56139. this.onButtonUpObservable.notifyObservers(buttonIndex);
  56140. }
  56141. }
  56142. return newValue;
  56143. };
  56144. GenericPad.prototype.update = function () {
  56145. _super.prototype.update.call(this);
  56146. for (var index = 0; index < this._buttons.length; index++) {
  56147. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  56148. }
  56149. };
  56150. return GenericPad;
  56151. }(Gamepad));
  56152. BABYLON.GenericPad = GenericPad;
  56153. })(BABYLON || (BABYLON = {}));
  56154. //# sourceMappingURL=babylon.gamepad.js.map
  56155. var BABYLON;
  56156. (function (BABYLON) {
  56157. var Xbox360Button;
  56158. (function (Xbox360Button) {
  56159. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  56160. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  56161. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  56162. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  56163. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  56164. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  56165. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  56166. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  56167. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  56168. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  56169. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  56170. var Xbox360Dpad;
  56171. (function (Xbox360Dpad) {
  56172. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  56173. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  56174. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  56175. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  56176. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  56177. var Xbox360Pad = /** @class */ (function (_super) {
  56178. __extends(Xbox360Pad, _super);
  56179. function Xbox360Pad(id, index, gamepad, xboxOne) {
  56180. if (xboxOne === void 0) { xboxOne = false; }
  56181. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  56182. _this._leftTrigger = 0;
  56183. _this._rightTrigger = 0;
  56184. _this.onButtonDownObservable = new BABYLON.Observable();
  56185. _this.onButtonUpObservable = new BABYLON.Observable();
  56186. _this.onPadDownObservable = new BABYLON.Observable();
  56187. _this.onPadUpObservable = new BABYLON.Observable();
  56188. _this._buttonA = 0;
  56189. _this._buttonB = 0;
  56190. _this._buttonX = 0;
  56191. _this._buttonY = 0;
  56192. _this._buttonBack = 0;
  56193. _this._buttonStart = 0;
  56194. _this._buttonLB = 0;
  56195. _this._buttonRB = 0;
  56196. _this._buttonLeftStick = 0;
  56197. _this._buttonRightStick = 0;
  56198. _this._dPadUp = 0;
  56199. _this._dPadDown = 0;
  56200. _this._dPadLeft = 0;
  56201. _this._dPadRight = 0;
  56202. _this._isXboxOnePad = false;
  56203. _this.type = BABYLON.Gamepad.XBOX;
  56204. _this._isXboxOnePad = xboxOne;
  56205. return _this;
  56206. }
  56207. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  56208. this._onlefttriggerchanged = callback;
  56209. };
  56210. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  56211. this._onrighttriggerchanged = callback;
  56212. };
  56213. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  56214. get: function () {
  56215. return this._leftTrigger;
  56216. },
  56217. set: function (newValue) {
  56218. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  56219. this._onlefttriggerchanged(newValue);
  56220. }
  56221. this._leftTrigger = newValue;
  56222. },
  56223. enumerable: true,
  56224. configurable: true
  56225. });
  56226. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  56227. get: function () {
  56228. return this._rightTrigger;
  56229. },
  56230. set: function (newValue) {
  56231. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  56232. this._onrighttriggerchanged(newValue);
  56233. }
  56234. this._rightTrigger = newValue;
  56235. },
  56236. enumerable: true,
  56237. configurable: true
  56238. });
  56239. Xbox360Pad.prototype.onbuttondown = function (callback) {
  56240. this._onbuttondown = callback;
  56241. };
  56242. Xbox360Pad.prototype.onbuttonup = function (callback) {
  56243. this._onbuttonup = callback;
  56244. };
  56245. Xbox360Pad.prototype.ondpaddown = function (callback) {
  56246. this._ondpaddown = callback;
  56247. };
  56248. Xbox360Pad.prototype.ondpadup = function (callback) {
  56249. this._ondpadup = callback;
  56250. };
  56251. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  56252. if (newValue !== currentValue) {
  56253. if (newValue === 1) {
  56254. if (this._onbuttondown) {
  56255. this._onbuttondown(buttonType);
  56256. }
  56257. this.onButtonDownObservable.notifyObservers(buttonType);
  56258. }
  56259. if (newValue === 0) {
  56260. if (this._onbuttonup) {
  56261. this._onbuttonup(buttonType);
  56262. }
  56263. this.onButtonUpObservable.notifyObservers(buttonType);
  56264. }
  56265. }
  56266. return newValue;
  56267. };
  56268. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  56269. if (newValue !== currentValue) {
  56270. if (newValue === 1) {
  56271. if (this._ondpaddown) {
  56272. this._ondpaddown(buttonType);
  56273. }
  56274. this.onPadDownObservable.notifyObservers(buttonType);
  56275. }
  56276. if (newValue === 0) {
  56277. if (this._ondpadup) {
  56278. this._ondpadup(buttonType);
  56279. }
  56280. this.onPadUpObservable.notifyObservers(buttonType);
  56281. }
  56282. }
  56283. return newValue;
  56284. };
  56285. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  56286. get: function () {
  56287. return this._buttonA;
  56288. },
  56289. set: function (value) {
  56290. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  56291. },
  56292. enumerable: true,
  56293. configurable: true
  56294. });
  56295. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  56296. get: function () {
  56297. return this._buttonB;
  56298. },
  56299. set: function (value) {
  56300. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  56301. },
  56302. enumerable: true,
  56303. configurable: true
  56304. });
  56305. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  56306. get: function () {
  56307. return this._buttonX;
  56308. },
  56309. set: function (value) {
  56310. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  56311. },
  56312. enumerable: true,
  56313. configurable: true
  56314. });
  56315. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  56316. get: function () {
  56317. return this._buttonY;
  56318. },
  56319. set: function (value) {
  56320. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  56321. },
  56322. enumerable: true,
  56323. configurable: true
  56324. });
  56325. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  56326. get: function () {
  56327. return this._buttonStart;
  56328. },
  56329. set: function (value) {
  56330. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  56331. },
  56332. enumerable: true,
  56333. configurable: true
  56334. });
  56335. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  56336. get: function () {
  56337. return this._buttonBack;
  56338. },
  56339. set: function (value) {
  56340. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  56341. },
  56342. enumerable: true,
  56343. configurable: true
  56344. });
  56345. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  56346. get: function () {
  56347. return this._buttonLB;
  56348. },
  56349. set: function (value) {
  56350. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  56351. },
  56352. enumerable: true,
  56353. configurable: true
  56354. });
  56355. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  56356. get: function () {
  56357. return this._buttonRB;
  56358. },
  56359. set: function (value) {
  56360. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  56361. },
  56362. enumerable: true,
  56363. configurable: true
  56364. });
  56365. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  56366. get: function () {
  56367. return this._buttonLeftStick;
  56368. },
  56369. set: function (value) {
  56370. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  56371. },
  56372. enumerable: true,
  56373. configurable: true
  56374. });
  56375. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  56376. get: function () {
  56377. return this._buttonRightStick;
  56378. },
  56379. set: function (value) {
  56380. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  56381. },
  56382. enumerable: true,
  56383. configurable: true
  56384. });
  56385. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  56386. get: function () {
  56387. return this._dPadUp;
  56388. },
  56389. set: function (value) {
  56390. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  56391. },
  56392. enumerable: true,
  56393. configurable: true
  56394. });
  56395. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  56396. get: function () {
  56397. return this._dPadDown;
  56398. },
  56399. set: function (value) {
  56400. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  56401. },
  56402. enumerable: true,
  56403. configurable: true
  56404. });
  56405. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  56406. get: function () {
  56407. return this._dPadLeft;
  56408. },
  56409. set: function (value) {
  56410. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  56411. },
  56412. enumerable: true,
  56413. configurable: true
  56414. });
  56415. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  56416. get: function () {
  56417. return this._dPadRight;
  56418. },
  56419. set: function (value) {
  56420. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  56421. },
  56422. enumerable: true,
  56423. configurable: true
  56424. });
  56425. Xbox360Pad.prototype.update = function () {
  56426. _super.prototype.update.call(this);
  56427. if (this._isXboxOnePad) {
  56428. this.buttonA = this.browserGamepad.buttons[0].value;
  56429. this.buttonB = this.browserGamepad.buttons[1].value;
  56430. this.buttonX = this.browserGamepad.buttons[2].value;
  56431. this.buttonY = this.browserGamepad.buttons[3].value;
  56432. this.buttonLB = this.browserGamepad.buttons[4].value;
  56433. this.buttonRB = this.browserGamepad.buttons[5].value;
  56434. this.leftTrigger = this.browserGamepad.axes[2];
  56435. this.rightTrigger = this.browserGamepad.axes[5];
  56436. this.buttonBack = this.browserGamepad.buttons[9].value;
  56437. this.buttonStart = this.browserGamepad.buttons[8].value;
  56438. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  56439. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  56440. this.dPadUp = this.browserGamepad.buttons[11].value;
  56441. this.dPadDown = this.browserGamepad.buttons[12].value;
  56442. this.dPadLeft = this.browserGamepad.buttons[13].value;
  56443. this.dPadRight = this.browserGamepad.buttons[14].value;
  56444. }
  56445. else {
  56446. this.buttonA = this.browserGamepad.buttons[0].value;
  56447. this.buttonB = this.browserGamepad.buttons[1].value;
  56448. this.buttonX = this.browserGamepad.buttons[2].value;
  56449. this.buttonY = this.browserGamepad.buttons[3].value;
  56450. this.buttonLB = this.browserGamepad.buttons[4].value;
  56451. this.buttonRB = this.browserGamepad.buttons[5].value;
  56452. this.leftTrigger = this.browserGamepad.buttons[6].value;
  56453. this.rightTrigger = this.browserGamepad.buttons[7].value;
  56454. this.buttonBack = this.browserGamepad.buttons[8].value;
  56455. this.buttonStart = this.browserGamepad.buttons[9].value;
  56456. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  56457. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  56458. this.dPadUp = this.browserGamepad.buttons[12].value;
  56459. this.dPadDown = this.browserGamepad.buttons[13].value;
  56460. this.dPadLeft = this.browserGamepad.buttons[14].value;
  56461. this.dPadRight = this.browserGamepad.buttons[15].value;
  56462. }
  56463. };
  56464. return Xbox360Pad;
  56465. }(BABYLON.Gamepad));
  56466. BABYLON.Xbox360Pad = Xbox360Pad;
  56467. })(BABYLON || (BABYLON = {}));
  56468. //# sourceMappingURL=babylon.xboxGamepad.js.map
  56469. var BABYLON;
  56470. (function (BABYLON) {
  56471. var PoseEnabledControllerType;
  56472. (function (PoseEnabledControllerType) {
  56473. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  56474. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  56475. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  56476. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 3] = "GENERIC";
  56477. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  56478. var PoseEnabledControllerHelper = /** @class */ (function () {
  56479. function PoseEnabledControllerHelper() {
  56480. }
  56481. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  56482. // Oculus Touch
  56483. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  56484. return new BABYLON.OculusTouchController(vrGamepad);
  56485. }
  56486. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  56487. return new BABYLON.WindowsMotionController(vrGamepad);
  56488. }
  56489. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  56490. return new BABYLON.ViveController(vrGamepad);
  56491. }
  56492. else {
  56493. return new BABYLON.GenericController(vrGamepad);
  56494. }
  56495. };
  56496. return PoseEnabledControllerHelper;
  56497. }());
  56498. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  56499. var PoseEnabledController = /** @class */ (function (_super) {
  56500. __extends(PoseEnabledController, _super);
  56501. function PoseEnabledController(browserGamepad) {
  56502. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  56503. _this.deviceScaleFactor = 1;
  56504. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  56505. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  56506. _this.controllerType = PoseEnabledControllerType.GENERIC;
  56507. _this.position = BABYLON.Vector3.Zero();
  56508. _this.rotationQuaternion = new BABYLON.Quaternion();
  56509. _this.devicePosition = BABYLON.Vector3.Zero();
  56510. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  56511. _this._calculatedPosition = BABYLON.Vector3.Zero();
  56512. _this._calculatedRotation = new BABYLON.Quaternion();
  56513. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  56514. return _this;
  56515. }
  56516. PoseEnabledController.prototype.update = function () {
  56517. _super.prototype.update.call(this);
  56518. var pose = this.browserGamepad.pose;
  56519. this.updateFromDevice(pose);
  56520. if (this._mesh) {
  56521. this._mesh.position.copyFrom(this._calculatedPosition);
  56522. if (this._mesh.rotationQuaternion) {
  56523. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  56524. }
  56525. }
  56526. };
  56527. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  56528. if (poseData) {
  56529. this.rawPose = poseData;
  56530. if (poseData.position) {
  56531. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  56532. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  56533. this.devicePosition.z *= -1;
  56534. }
  56535. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  56536. this._calculatedPosition.addInPlace(this.position);
  56537. }
  56538. var pose = this.rawPose;
  56539. if (poseData.orientation && pose.orientation) {
  56540. this.deviceRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  56541. if (this._mesh) {
  56542. if (this._mesh.getScene().useRightHandedSystem) {
  56543. this.deviceRotationQuaternion.z *= -1;
  56544. this.deviceRotationQuaternion.w *= -1;
  56545. }
  56546. else {
  56547. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  56548. }
  56549. }
  56550. // if the camera is set, rotate to the camera's rotation
  56551. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  56552. }
  56553. }
  56554. };
  56555. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  56556. if (this._mesh) {
  56557. this._mesh.parent = null;
  56558. }
  56559. this._mesh = mesh;
  56560. if (this._poseControlledCamera) {
  56561. this._mesh.parent = this._poseControlledCamera;
  56562. }
  56563. if (!this._mesh.rotationQuaternion) {
  56564. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  56565. }
  56566. };
  56567. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  56568. this._poseControlledCamera = camera;
  56569. if (this._mesh) {
  56570. this._mesh.parent = this._poseControlledCamera;
  56571. }
  56572. };
  56573. PoseEnabledController.prototype.dispose = function () {
  56574. if (this._mesh) {
  56575. this._mesh.dispose();
  56576. }
  56577. this._mesh = null;
  56578. _super.prototype.dispose.call(this);
  56579. };
  56580. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  56581. get: function () {
  56582. return this._mesh;
  56583. },
  56584. enumerable: true,
  56585. configurable: true
  56586. });
  56587. PoseEnabledController.prototype.getForwardRay = function (length) {
  56588. if (length === void 0) { length = 100; }
  56589. if (!this.mesh) {
  56590. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  56591. }
  56592. var m = this.mesh.getWorldMatrix();
  56593. var origin = m.getTranslation();
  56594. var forward = new BABYLON.Vector3(0, 0, -1);
  56595. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  56596. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  56597. return new BABYLON.Ray(origin, direction, length);
  56598. };
  56599. return PoseEnabledController;
  56600. }(BABYLON.Gamepad));
  56601. BABYLON.PoseEnabledController = PoseEnabledController;
  56602. })(BABYLON || (BABYLON = {}));
  56603. //# sourceMappingURL=babylon.poseEnabledController.js.map
  56604. var BABYLON;
  56605. (function (BABYLON) {
  56606. var WebVRController = /** @class */ (function (_super) {
  56607. __extends(WebVRController, _super);
  56608. function WebVRController(vrGamepad) {
  56609. var _this = _super.call(this, vrGamepad) || this;
  56610. // Observables
  56611. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  56612. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  56613. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  56614. _this.onPadStateChangedObservable = new BABYLON.Observable();
  56615. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  56616. _this.pad = { x: 0, y: 0 };
  56617. // avoid GC, store state in a tmp object
  56618. _this._changes = {
  56619. pressChanged: false,
  56620. touchChanged: false,
  56621. valueChanged: false,
  56622. changed: false
  56623. };
  56624. _this._buttons = new Array(vrGamepad.buttons.length);
  56625. _this.hand = vrGamepad.hand;
  56626. return _this;
  56627. }
  56628. WebVRController.prototype.onButtonStateChange = function (callback) {
  56629. this._onButtonStateChange = callback;
  56630. };
  56631. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  56632. get: function () {
  56633. return this._defaultModel;
  56634. },
  56635. enumerable: true,
  56636. configurable: true
  56637. });
  56638. WebVRController.prototype.update = function () {
  56639. _super.prototype.update.call(this);
  56640. for (var index = 0; index < this._buttons.length; index++) {
  56641. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  56642. }
  56643. ;
  56644. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  56645. this.pad.x = this.leftStick.x;
  56646. this.pad.y = this.leftStick.y;
  56647. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  56648. }
  56649. };
  56650. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  56651. if (!newState) {
  56652. newState = {
  56653. pressed: false,
  56654. touched: false,
  56655. value: 0
  56656. };
  56657. }
  56658. if (!currentState) {
  56659. this._buttons[buttonIndex] = {
  56660. pressed: newState.pressed,
  56661. touched: newState.touched,
  56662. value: newState.value
  56663. };
  56664. return;
  56665. }
  56666. this._checkChanges(newState, currentState);
  56667. if (this._changes.changed) {
  56668. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  56669. this.handleButtonChange(buttonIndex, newState, this._changes);
  56670. }
  56671. this._buttons[buttonIndex].pressed = newState.pressed;
  56672. this._buttons[buttonIndex].touched = newState.touched;
  56673. // oculus triggers are never 0, thou not touched.
  56674. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  56675. };
  56676. WebVRController.prototype._checkChanges = function (newState, currentState) {
  56677. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  56678. this._changes.touchChanged = newState.touched !== currentState.touched;
  56679. this._changes.valueChanged = newState.value !== currentState.value;
  56680. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  56681. return this._changes;
  56682. };
  56683. WebVRController.prototype.dispose = function () {
  56684. _super.prototype.dispose.call(this);
  56685. this.onTriggerStateChangedObservable.clear();
  56686. this.onMainButtonStateChangedObservable.clear();
  56687. this.onSecondaryButtonStateChangedObservable.clear();
  56688. this.onPadStateChangedObservable.clear();
  56689. this.onPadValuesChangedObservable.clear();
  56690. };
  56691. return WebVRController;
  56692. }(BABYLON.PoseEnabledController));
  56693. BABYLON.WebVRController = WebVRController;
  56694. })(BABYLON || (BABYLON = {}));
  56695. //# sourceMappingURL=babylon.webVRController.js.map
  56696. var BABYLON;
  56697. (function (BABYLON) {
  56698. var OculusTouchController = /** @class */ (function (_super) {
  56699. __extends(OculusTouchController, _super);
  56700. function OculusTouchController(vrGamepad) {
  56701. var _this = _super.call(this, vrGamepad) || this;
  56702. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  56703. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  56704. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  56705. return _this;
  56706. }
  56707. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  56708. var _this = this;
  56709. var meshName;
  56710. // Hand
  56711. if (this.hand === 'left') {
  56712. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  56713. }
  56714. else {
  56715. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  56716. }
  56717. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  56718. /*
  56719. Parent Mesh name: oculus_touch_left
  56720. - body
  56721. - trigger
  56722. - thumbstick
  56723. - grip
  56724. - button_y
  56725. - button_x
  56726. - button_enter
  56727. */
  56728. _this._defaultModel = newMeshes[1];
  56729. _this.attachToMesh(_this._defaultModel);
  56730. if (meshLoaded) {
  56731. meshLoaded(_this._defaultModel);
  56732. }
  56733. });
  56734. };
  56735. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  56736. // helper getters for left and right hand.
  56737. get: function () {
  56738. if (this.hand === 'right') {
  56739. return this.onMainButtonStateChangedObservable;
  56740. }
  56741. else {
  56742. throw new Error('No A button on left hand');
  56743. }
  56744. },
  56745. enumerable: true,
  56746. configurable: true
  56747. });
  56748. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  56749. get: function () {
  56750. if (this.hand === 'right') {
  56751. return this.onSecondaryButtonStateChangedObservable;
  56752. }
  56753. else {
  56754. throw new Error('No B button on left hand');
  56755. }
  56756. },
  56757. enumerable: true,
  56758. configurable: true
  56759. });
  56760. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  56761. get: function () {
  56762. if (this.hand === 'left') {
  56763. return this.onMainButtonStateChangedObservable;
  56764. }
  56765. else {
  56766. throw new Error('No X button on right hand');
  56767. }
  56768. },
  56769. enumerable: true,
  56770. configurable: true
  56771. });
  56772. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  56773. get: function () {
  56774. if (this.hand === 'left') {
  56775. return this.onSecondaryButtonStateChangedObservable;
  56776. }
  56777. else {
  56778. throw new Error('No Y button on right hand');
  56779. }
  56780. },
  56781. enumerable: true,
  56782. configurable: true
  56783. });
  56784. /*
  56785. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  56786. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  56787. 2) secondary trigger (same)
  56788. 3) A (right) X (left), touch, pressed = value
  56789. 4) B / Y
  56790. 5) thumb rest
  56791. */
  56792. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  56793. var notifyObject = state; //{ state: state, changes: changes };
  56794. var triggerDirection = this.hand === 'right' ? -1 : 1;
  56795. switch (buttonIdx) {
  56796. case 0:
  56797. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  56798. return;
  56799. case 1:// index trigger
  56800. if (this._defaultModel) {
  56801. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  56802. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  56803. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  56804. }
  56805. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  56806. return;
  56807. case 2:// secondary trigger
  56808. if (this._defaultModel) {
  56809. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  56810. }
  56811. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  56812. return;
  56813. case 3:
  56814. if (this._defaultModel) {
  56815. if (notifyObject.pressed) {
  56816. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  56817. }
  56818. else {
  56819. (this._defaultModel.getChildren()[1]).position.y = 0;
  56820. }
  56821. }
  56822. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  56823. return;
  56824. case 4:
  56825. if (this._defaultModel) {
  56826. if (notifyObject.pressed) {
  56827. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  56828. }
  56829. else {
  56830. (this._defaultModel.getChildren()[2]).position.y = 0;
  56831. }
  56832. }
  56833. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  56834. return;
  56835. case 5:
  56836. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  56837. return;
  56838. }
  56839. };
  56840. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  56841. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  56842. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  56843. return OculusTouchController;
  56844. }(BABYLON.WebVRController));
  56845. BABYLON.OculusTouchController = OculusTouchController;
  56846. })(BABYLON || (BABYLON = {}));
  56847. //# sourceMappingURL=babylon.oculusTouchController.js.map
  56848. var BABYLON;
  56849. (function (BABYLON) {
  56850. var ViveController = /** @class */ (function (_super) {
  56851. __extends(ViveController, _super);
  56852. function ViveController(vrGamepad) {
  56853. var _this = _super.call(this, vrGamepad) || this;
  56854. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  56855. return _this;
  56856. }
  56857. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  56858. var _this = this;
  56859. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  56860. /*
  56861. Parent Mesh name: ViveWand
  56862. - body
  56863. - r_gripper
  56864. - l_gripper
  56865. - menu_button
  56866. - system_button
  56867. - trackpad
  56868. - trigger
  56869. - LED
  56870. */
  56871. _this._defaultModel = newMeshes[1];
  56872. _this.attachToMesh(_this._defaultModel);
  56873. if (meshLoaded) {
  56874. meshLoaded(_this._defaultModel);
  56875. }
  56876. });
  56877. };
  56878. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  56879. get: function () {
  56880. return this.onMainButtonStateChangedObservable;
  56881. },
  56882. enumerable: true,
  56883. configurable: true
  56884. });
  56885. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  56886. get: function () {
  56887. return this.onMainButtonStateChangedObservable;
  56888. },
  56889. enumerable: true,
  56890. configurable: true
  56891. });
  56892. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  56893. get: function () {
  56894. return this.onSecondaryButtonStateChangedObservable;
  56895. },
  56896. enumerable: true,
  56897. configurable: true
  56898. });
  56899. /**
  56900. * Vive mapping:
  56901. * 0: touchpad
  56902. * 1: trigger
  56903. * 2: left AND right buttons
  56904. * 3: menu button
  56905. */
  56906. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  56907. var notifyObject = state; //{ state: state, changes: changes };
  56908. switch (buttonIdx) {
  56909. case 0:
  56910. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  56911. return;
  56912. case 1:// index trigger
  56913. if (this._defaultModel) {
  56914. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  56915. }
  56916. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  56917. return;
  56918. case 2:// left AND right button
  56919. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  56920. return;
  56921. case 3:
  56922. if (this._defaultModel) {
  56923. if (notifyObject.pressed) {
  56924. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  56925. }
  56926. else {
  56927. (this._defaultModel.getChildren()[2]).position.y = 0;
  56928. }
  56929. }
  56930. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  56931. return;
  56932. }
  56933. };
  56934. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  56935. ViveController.MODEL_FILENAME = 'wand.babylon';
  56936. return ViveController;
  56937. }(BABYLON.WebVRController));
  56938. BABYLON.ViveController = ViveController;
  56939. })(BABYLON || (BABYLON = {}));
  56940. //# sourceMappingURL=babylon.viveController.js.map
  56941. var BABYLON;
  56942. (function (BABYLON) {
  56943. var GenericController = /** @class */ (function (_super) {
  56944. __extends(GenericController, _super);
  56945. function GenericController(vrGamepad) {
  56946. return _super.call(this, vrGamepad) || this;
  56947. }
  56948. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  56949. var _this = this;
  56950. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  56951. _this._defaultModel = newMeshes[1];
  56952. _this.attachToMesh(_this._defaultModel);
  56953. if (meshLoaded) {
  56954. meshLoaded(_this._defaultModel);
  56955. }
  56956. });
  56957. };
  56958. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  56959. console.log("Button id: " + buttonIdx + "state: ");
  56960. console.dir(state);
  56961. };
  56962. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  56963. GenericController.MODEL_FILENAME = 'generic.babylon';
  56964. return GenericController;
  56965. }(BABYLON.WebVRController));
  56966. BABYLON.GenericController = GenericController;
  56967. })(BABYLON || (BABYLON = {}));
  56968. //# sourceMappingURL=babylon.genericController.js.map
  56969. var BABYLON;
  56970. (function (BABYLON) {
  56971. var LoadedMeshInfo = /** @class */ (function () {
  56972. function LoadedMeshInfo() {
  56973. this.buttonMeshes = {};
  56974. this.axisMeshes = {};
  56975. }
  56976. return LoadedMeshInfo;
  56977. }());
  56978. var WindowsMotionController = /** @class */ (function (_super) {
  56979. __extends(WindowsMotionController, _super);
  56980. function WindowsMotionController(vrGamepad) {
  56981. var _this = _super.call(this, vrGamepad) || this;
  56982. _this._mapping = {
  56983. // Semantic button names
  56984. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  56985. // A mapping of the button name to glTF model node name
  56986. // that should be transformed by button value.
  56987. buttonMeshNames: {
  56988. 'trigger': 'SELECT',
  56989. 'menu': 'MENU',
  56990. 'grip': 'GRASP',
  56991. 'thumbstick': 'THUMBSTICK_PRESS',
  56992. 'trackpad': 'TOUCHPAD_PRESS'
  56993. },
  56994. // This mapping is used to translate from the Motion Controller to Babylon semantics
  56995. buttonObservableNames: {
  56996. 'trigger': 'onTriggerStateChangedObservable',
  56997. 'menu': 'onSecondaryButtonStateChangedObservable',
  56998. 'grip': 'onMainButtonStateChangedObservable',
  56999. 'thumbstick': 'onPadStateChangedObservable',
  57000. 'trackpad': 'onTrackpadChangedObservable'
  57001. },
  57002. // A mapping of the axis name to glTF model node name
  57003. // that should be transformed by axis value.
  57004. // This array mirrors the browserGamepad.axes array, such that
  57005. // the mesh corresponding to axis 0 is in this array index 0.
  57006. axisMeshNames: [
  57007. 'THUMBSTICK_X',
  57008. 'THUMBSTICK_Y',
  57009. 'TOUCHPAD_TOUCH_X',
  57010. 'TOUCHPAD_TOUCH_Y'
  57011. ],
  57012. pointingPoseMeshName: 'POINTING_POSE'
  57013. };
  57014. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  57015. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  57016. _this.trackpad = { x: 0, y: 0 };
  57017. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  57018. _this._loadedMeshInfo = null;
  57019. return _this;
  57020. }
  57021. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  57022. get: function () {
  57023. return this.onTriggerStateChangedObservable;
  57024. },
  57025. enumerable: true,
  57026. configurable: true
  57027. });
  57028. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  57029. get: function () {
  57030. return this.onSecondaryButtonStateChangedObservable;
  57031. },
  57032. enumerable: true,
  57033. configurable: true
  57034. });
  57035. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  57036. get: function () {
  57037. return this.onMainButtonStateChangedObservable;
  57038. },
  57039. enumerable: true,
  57040. configurable: true
  57041. });
  57042. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  57043. get: function () {
  57044. return this.onPadStateChangedObservable;
  57045. },
  57046. enumerable: true,
  57047. configurable: true
  57048. });
  57049. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  57050. get: function () {
  57051. return this.onTrackpadChangedObservable;
  57052. },
  57053. enumerable: true,
  57054. configurable: true
  57055. });
  57056. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  57057. get: function () {
  57058. return this.onTrackpadValuesChangedObservable;
  57059. },
  57060. enumerable: true,
  57061. configurable: true
  57062. });
  57063. /**
  57064. * Called once per frame by the engine.
  57065. */
  57066. WindowsMotionController.prototype.update = function () {
  57067. _super.prototype.update.call(this);
  57068. // Only need to animate axes if there is a loaded mesh
  57069. if (this._loadedMeshInfo) {
  57070. if (this.browserGamepad.axes) {
  57071. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  57072. this.trackpad.x = this.browserGamepad["axes"][2];
  57073. this.trackpad.y = this.browserGamepad["axes"][3];
  57074. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  57075. }
  57076. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  57077. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  57078. }
  57079. }
  57080. }
  57081. };
  57082. /**
  57083. * Called once for each button that changed state since the last frame
  57084. * @param buttonIdx Which button index changed
  57085. * @param state New state of the button
  57086. * @param changes Which properties on the state changed since last frame
  57087. */
  57088. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  57089. var buttonName = this._mapping.buttons[buttonIdx];
  57090. if (!buttonName) {
  57091. return;
  57092. }
  57093. // Only emit events for buttons that we know how to map from index to name
  57094. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  57095. if (observable) {
  57096. observable.notifyObservers(state);
  57097. }
  57098. this.lerpButtonTransform(buttonName, state.value);
  57099. };
  57100. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  57101. // If there is no loaded mesh, there is nothing to transform.
  57102. if (!this._loadedMeshInfo) {
  57103. return;
  57104. }
  57105. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  57106. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  57107. return;
  57108. }
  57109. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  57110. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  57111. };
  57112. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  57113. if (!this._loadedMeshInfo) {
  57114. return;
  57115. }
  57116. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  57117. if (!meshInfo) {
  57118. return;
  57119. }
  57120. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  57121. return;
  57122. }
  57123. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  57124. var lerpValue = axisValue * 0.5 + 0.5;
  57125. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  57126. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  57127. };
  57128. /**
  57129. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  57130. * @param scene scene in which to add meshes
  57131. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  57132. */
  57133. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  57134. var _this = this;
  57135. if (forceDefault === void 0) { forceDefault = false; }
  57136. var path;
  57137. var filename;
  57138. // Checking if GLB loader is present
  57139. if (BABYLON.SceneLoader.GetPluginForExtension("glb")) {
  57140. // Determine the device specific folder based on the ID suffix
  57141. var device = 'default';
  57142. if (this.id && !forceDefault) {
  57143. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  57144. device = ((match && match[0]) || device);
  57145. }
  57146. // Hand
  57147. if (this.hand === 'left') {
  57148. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  57149. }
  57150. else {
  57151. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  57152. }
  57153. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  57154. }
  57155. else {
  57156. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  57157. path = BABYLON.GenericController.MODEL_BASE_URL;
  57158. filename = BABYLON.GenericController.MODEL_FILENAME;
  57159. }
  57160. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  57161. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  57162. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  57163. if (!_this._loadedMeshInfo) {
  57164. return;
  57165. }
  57166. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  57167. _this.attachToMesh(_this._defaultModel);
  57168. if (meshLoaded) {
  57169. meshLoaded(_this._defaultModel);
  57170. }
  57171. }, null, function (scene, message) {
  57172. BABYLON.Tools.Log(message);
  57173. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  57174. if (!forceDefault) {
  57175. _this.initControllerMesh(scene, meshLoaded, true);
  57176. }
  57177. });
  57178. };
  57179. /**
  57180. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  57181. * can be transformed by button presses and axes values, based on this._mapping.
  57182. *
  57183. * @param scene scene in which the meshes exist
  57184. * @param meshes list of meshes that make up the controller model to process
  57185. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  57186. */
  57187. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  57188. var loadedMeshInfo = null;
  57189. // Create a new mesh to contain the glTF hierarchy
  57190. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  57191. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  57192. var childMesh = null;
  57193. for (var i = 0; i < meshes.length; i++) {
  57194. var mesh = meshes[i];
  57195. if (!mesh.parent) {
  57196. // Exclude controller meshes from picking results
  57197. mesh.isPickable = false;
  57198. // Handle root node, attach to the new parentMesh
  57199. childMesh = mesh;
  57200. break;
  57201. }
  57202. }
  57203. if (childMesh) {
  57204. childMesh.setParent(parentMesh);
  57205. // Create our mesh info. Note that this method will always return non-null.
  57206. loadedMeshInfo = this.createMeshInfo(parentMesh);
  57207. }
  57208. else {
  57209. BABYLON.Tools.Warn('Could not find root node in model file.');
  57210. }
  57211. return loadedMeshInfo;
  57212. };
  57213. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  57214. var loadedMeshInfo = new LoadedMeshInfo();
  57215. var i;
  57216. loadedMeshInfo.rootNode = rootNode;
  57217. // Reset the caches
  57218. loadedMeshInfo.buttonMeshes = {};
  57219. loadedMeshInfo.axisMeshes = {};
  57220. // Button Meshes
  57221. for (i = 0; i < this._mapping.buttons.length; i++) {
  57222. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  57223. if (!buttonMeshName) {
  57224. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  57225. continue;
  57226. }
  57227. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  57228. if (!buttonMesh) {
  57229. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  57230. continue;
  57231. }
  57232. var buttonMeshInfo = {
  57233. index: i,
  57234. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  57235. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  57236. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  57237. };
  57238. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  57239. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  57240. }
  57241. else {
  57242. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  57243. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  57244. '(VALUE: ' + !!buttonMeshInfo.value +
  57245. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  57246. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  57247. ')');
  57248. }
  57249. }
  57250. // Axis Meshes
  57251. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  57252. var axisMeshName = this._mapping.axisMeshNames[i];
  57253. if (!axisMeshName) {
  57254. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  57255. continue;
  57256. }
  57257. var axisMesh = getChildByName(rootNode, axisMeshName);
  57258. if (!axisMesh) {
  57259. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  57260. continue;
  57261. }
  57262. var axisMeshInfo = {
  57263. index: i,
  57264. value: getImmediateChildByName(axisMesh, 'VALUE'),
  57265. min: getImmediateChildByName(axisMesh, 'MIN'),
  57266. max: getImmediateChildByName(axisMesh, 'MAX')
  57267. };
  57268. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  57269. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  57270. }
  57271. else {
  57272. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  57273. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  57274. '(VALUE: ' + !!axisMeshInfo.value +
  57275. ', MIN: ' + !!axisMeshInfo.min +
  57276. ', MAX:' + !!axisMeshInfo.max +
  57277. ')');
  57278. }
  57279. }
  57280. // Pointing Ray
  57281. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  57282. if (!loadedMeshInfo.pointingPoseNode) {
  57283. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  57284. }
  57285. return loadedMeshInfo;
  57286. // Look through all children recursively. This will return null if no mesh exists with the given name.
  57287. function getChildByName(node, name) {
  57288. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  57289. }
  57290. // Look through only immediate children. This will return null if no mesh exists with the given name.
  57291. function getImmediateChildByName(node, name) {
  57292. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  57293. }
  57294. };
  57295. WindowsMotionController.prototype.getForwardRay = function (length) {
  57296. if (length === void 0) { length = 100; }
  57297. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  57298. return _super.prototype.getForwardRay.call(this, length);
  57299. }
  57300. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  57301. var origin = m.getTranslation();
  57302. var forward = new BABYLON.Vector3(0, 0, -1);
  57303. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  57304. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  57305. return new BABYLON.Ray(origin, direction, length);
  57306. };
  57307. WindowsMotionController.prototype.dispose = function () {
  57308. _super.prototype.dispose.call(this);
  57309. this.onTrackpadChangedObservable.clear();
  57310. };
  57311. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  57312. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  57313. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  57314. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  57315. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  57316. return WindowsMotionController;
  57317. }(BABYLON.WebVRController));
  57318. BABYLON.WindowsMotionController = WindowsMotionController;
  57319. })(BABYLON || (BABYLON = {}));
  57320. //# sourceMappingURL=babylon.windowsMotionController.js.map
  57321. var BABYLON;
  57322. (function (BABYLON) {
  57323. var FollowCamera = /** @class */ (function (_super) {
  57324. __extends(FollowCamera, _super);
  57325. function FollowCamera(name, position, scene, lockedTarget) {
  57326. if (lockedTarget === void 0) { lockedTarget = null; }
  57327. var _this = _super.call(this, name, position, scene) || this;
  57328. _this.radius = 12;
  57329. _this.rotationOffset = 0;
  57330. _this.heightOffset = 4;
  57331. _this.cameraAcceleration = 0.05;
  57332. _this.maxCameraSpeed = 20;
  57333. _this.lockedTarget = lockedTarget;
  57334. return _this;
  57335. }
  57336. FollowCamera.prototype.getRadians = function (degrees) {
  57337. return degrees * Math.PI / 180;
  57338. };
  57339. FollowCamera.prototype.follow = function (cameraTarget) {
  57340. if (!cameraTarget)
  57341. return;
  57342. var yRotation;
  57343. if (cameraTarget.rotationQuaternion) {
  57344. var rotMatrix = new BABYLON.Matrix();
  57345. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  57346. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  57347. }
  57348. else {
  57349. yRotation = cameraTarget.rotation.y;
  57350. }
  57351. var radians = this.getRadians(this.rotationOffset) + yRotation;
  57352. var targetPosition = cameraTarget.getAbsolutePosition();
  57353. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  57354. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  57355. var dx = targetX - this.position.x;
  57356. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  57357. var dz = (targetZ) - this.position.z;
  57358. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  57359. var vy = dy * this.cameraAcceleration;
  57360. var vz = dz * this.cameraAcceleration * 2;
  57361. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  57362. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  57363. }
  57364. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  57365. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  57366. }
  57367. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  57368. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  57369. }
  57370. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  57371. this.setTarget(targetPosition);
  57372. };
  57373. FollowCamera.prototype._checkInputs = function () {
  57374. _super.prototype._checkInputs.call(this);
  57375. if (this.lockedTarget) {
  57376. this.follow(this.lockedTarget);
  57377. }
  57378. };
  57379. FollowCamera.prototype.getClassName = function () {
  57380. return "FollowCamera";
  57381. };
  57382. __decorate([
  57383. BABYLON.serialize()
  57384. ], FollowCamera.prototype, "radius", void 0);
  57385. __decorate([
  57386. BABYLON.serialize()
  57387. ], FollowCamera.prototype, "rotationOffset", void 0);
  57388. __decorate([
  57389. BABYLON.serialize()
  57390. ], FollowCamera.prototype, "heightOffset", void 0);
  57391. __decorate([
  57392. BABYLON.serialize()
  57393. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  57394. __decorate([
  57395. BABYLON.serialize()
  57396. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  57397. __decorate([
  57398. BABYLON.serializeAsMeshReference("lockedTargetId")
  57399. ], FollowCamera.prototype, "lockedTarget", void 0);
  57400. return FollowCamera;
  57401. }(BABYLON.TargetCamera));
  57402. BABYLON.FollowCamera = FollowCamera;
  57403. var ArcFollowCamera = /** @class */ (function (_super) {
  57404. __extends(ArcFollowCamera, _super);
  57405. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  57406. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  57407. _this.alpha = alpha;
  57408. _this.beta = beta;
  57409. _this.radius = radius;
  57410. _this.target = target;
  57411. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  57412. _this.follow();
  57413. return _this;
  57414. }
  57415. ArcFollowCamera.prototype.follow = function () {
  57416. if (!this.target) {
  57417. return;
  57418. }
  57419. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  57420. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  57421. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  57422. var targetPosition = this.target.getAbsolutePosition();
  57423. this.position = targetPosition.add(this._cartesianCoordinates);
  57424. this.setTarget(targetPosition);
  57425. };
  57426. ArcFollowCamera.prototype._checkInputs = function () {
  57427. _super.prototype._checkInputs.call(this);
  57428. this.follow();
  57429. };
  57430. ArcFollowCamera.prototype.getClassName = function () {
  57431. return "ArcFollowCamera";
  57432. };
  57433. return ArcFollowCamera;
  57434. }(BABYLON.TargetCamera));
  57435. BABYLON.ArcFollowCamera = ArcFollowCamera;
  57436. })(BABYLON || (BABYLON = {}));
  57437. //# sourceMappingURL=babylon.followCamera.js.map
  57438. var BABYLON;
  57439. (function (BABYLON) {
  57440. // We're mainly based on the logic defined into the FreeCamera code
  57441. var UniversalCamera = /** @class */ (function (_super) {
  57442. __extends(UniversalCamera, _super);
  57443. //-- end properties for backward compatibility for inputs
  57444. function UniversalCamera(name, position, scene) {
  57445. var _this = _super.call(this, name, position, scene) || this;
  57446. _this.inputs.addGamepad();
  57447. return _this;
  57448. }
  57449. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  57450. //-- Begin properties for backward compatibility for inputs
  57451. get: function () {
  57452. var gamepad = this.inputs.attached["gamepad"];
  57453. if (gamepad)
  57454. return gamepad.gamepadAngularSensibility;
  57455. return 0;
  57456. },
  57457. set: function (value) {
  57458. var gamepad = this.inputs.attached["gamepad"];
  57459. if (gamepad)
  57460. gamepad.gamepadAngularSensibility = value;
  57461. },
  57462. enumerable: true,
  57463. configurable: true
  57464. });
  57465. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  57466. get: function () {
  57467. var gamepad = this.inputs.attached["gamepad"];
  57468. if (gamepad)
  57469. return gamepad.gamepadMoveSensibility;
  57470. return 0;
  57471. },
  57472. set: function (value) {
  57473. var gamepad = this.inputs.attached["gamepad"];
  57474. if (gamepad)
  57475. gamepad.gamepadMoveSensibility = value;
  57476. },
  57477. enumerable: true,
  57478. configurable: true
  57479. });
  57480. UniversalCamera.prototype.getClassName = function () {
  57481. return "UniversalCamera";
  57482. };
  57483. return UniversalCamera;
  57484. }(BABYLON.TouchCamera));
  57485. BABYLON.UniversalCamera = UniversalCamera;
  57486. })(BABYLON || (BABYLON = {}));
  57487. //# sourceMappingURL=babylon.universalCamera.js.map
  57488. var BABYLON;
  57489. (function (BABYLON) {
  57490. // We're mainly based on the logic defined into the FreeCamera code
  57491. var GamepadCamera = /** @class */ (function (_super) {
  57492. __extends(GamepadCamera, _super);
  57493. //-- end properties for backward compatibility for inputs
  57494. function GamepadCamera(name, position, scene) {
  57495. return _super.call(this, name, position, scene) || this;
  57496. }
  57497. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  57498. //-- Begin properties for backward compatibility for inputs
  57499. get: function () {
  57500. var gamepad = this.inputs.attached["gamepad"];
  57501. if (gamepad)
  57502. return gamepad.gamepadAngularSensibility;
  57503. return 0;
  57504. },
  57505. set: function (value) {
  57506. var gamepad = this.inputs.attached["gamepad"];
  57507. if (gamepad)
  57508. gamepad.gamepadAngularSensibility = value;
  57509. },
  57510. enumerable: true,
  57511. configurable: true
  57512. });
  57513. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  57514. get: function () {
  57515. var gamepad = this.inputs.attached["gamepad"];
  57516. if (gamepad)
  57517. return gamepad.gamepadMoveSensibility;
  57518. return 0;
  57519. },
  57520. set: function (value) {
  57521. var gamepad = this.inputs.attached["gamepad"];
  57522. if (gamepad)
  57523. gamepad.gamepadMoveSensibility = value;
  57524. },
  57525. enumerable: true,
  57526. configurable: true
  57527. });
  57528. GamepadCamera.prototype.getClassName = function () {
  57529. return "GamepadCamera";
  57530. };
  57531. return GamepadCamera;
  57532. }(BABYLON.UniversalCamera));
  57533. BABYLON.GamepadCamera = GamepadCamera;
  57534. })(BABYLON || (BABYLON = {}));
  57535. //# sourceMappingURL=babylon.gamepadCamera.js.map
  57536. var BABYLON;
  57537. (function (BABYLON) {
  57538. var PostProcessRenderPipelineManager = /** @class */ (function () {
  57539. function PostProcessRenderPipelineManager() {
  57540. this._renderPipelines = {};
  57541. }
  57542. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  57543. this._renderPipelines[renderPipeline._name] = renderPipeline;
  57544. };
  57545. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  57546. if (unique === void 0) { unique = false; }
  57547. var renderPipeline = this._renderPipelines[renderPipelineName];
  57548. if (!renderPipeline) {
  57549. return;
  57550. }
  57551. renderPipeline._attachCameras(cameras, unique);
  57552. };
  57553. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  57554. var renderPipeline = this._renderPipelines[renderPipelineName];
  57555. if (!renderPipeline) {
  57556. return;
  57557. }
  57558. renderPipeline._detachCameras(cameras);
  57559. };
  57560. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  57561. var renderPipeline = this._renderPipelines[renderPipelineName];
  57562. if (!renderPipeline) {
  57563. return;
  57564. }
  57565. renderPipeline._enableEffect(renderEffectName, cameras);
  57566. };
  57567. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  57568. var renderPipeline = this._renderPipelines[renderPipelineName];
  57569. if (!renderPipeline) {
  57570. return;
  57571. }
  57572. renderPipeline._disableEffect(renderEffectName, cameras);
  57573. };
  57574. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  57575. var renderPipeline = this._renderPipelines[renderPipelineName];
  57576. if (!renderPipeline) {
  57577. return;
  57578. }
  57579. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  57580. };
  57581. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  57582. var renderPipeline = this._renderPipelines[renderPipelineName];
  57583. if (!renderPipeline) {
  57584. return;
  57585. }
  57586. renderPipeline._disableDisplayOnlyPass(cameras);
  57587. };
  57588. PostProcessRenderPipelineManager.prototype.update = function () {
  57589. for (var renderPipelineName in this._renderPipelines) {
  57590. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  57591. var pipeline = this._renderPipelines[renderPipelineName];
  57592. if (!pipeline.isSupported) {
  57593. pipeline.dispose();
  57594. delete this._renderPipelines[renderPipelineName];
  57595. }
  57596. else {
  57597. pipeline._update();
  57598. }
  57599. }
  57600. }
  57601. };
  57602. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  57603. for (var renderPipelineName in this._renderPipelines) {
  57604. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  57605. var pipeline = this._renderPipelines[renderPipelineName];
  57606. pipeline._rebuild();
  57607. }
  57608. }
  57609. };
  57610. PostProcessRenderPipelineManager.prototype.dispose = function () {
  57611. for (var renderPipelineName in this._renderPipelines) {
  57612. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  57613. var pipeline = this._renderPipelines[renderPipelineName];
  57614. pipeline.dispose();
  57615. }
  57616. }
  57617. };
  57618. return PostProcessRenderPipelineManager;
  57619. }());
  57620. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  57621. })(BABYLON || (BABYLON = {}));
  57622. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  57623. var BABYLON;
  57624. (function (BABYLON) {
  57625. var PostProcessRenderPass = /** @class */ (function () {
  57626. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  57627. this._refCount = 0;
  57628. this._name = name;
  57629. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  57630. this.setRenderList(renderList);
  57631. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  57632. this._renderTexture.onAfterRenderObservable.add(afterRender);
  57633. this._scene = scene;
  57634. this._renderList = renderList;
  57635. }
  57636. // private
  57637. PostProcessRenderPass.prototype._incRefCount = function () {
  57638. if (this._refCount === 0) {
  57639. this._scene.customRenderTargets.push(this._renderTexture);
  57640. }
  57641. return ++this._refCount;
  57642. };
  57643. PostProcessRenderPass.prototype._decRefCount = function () {
  57644. this._refCount--;
  57645. if (this._refCount <= 0) {
  57646. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  57647. }
  57648. return this._refCount;
  57649. };
  57650. PostProcessRenderPass.prototype._update = function () {
  57651. this.setRenderList(this._renderList);
  57652. };
  57653. // public
  57654. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  57655. this._renderTexture.renderList = renderList;
  57656. };
  57657. PostProcessRenderPass.prototype.getRenderTexture = function () {
  57658. return this._renderTexture;
  57659. };
  57660. return PostProcessRenderPass;
  57661. }());
  57662. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  57663. })(BABYLON || (BABYLON = {}));
  57664. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  57665. var BABYLON;
  57666. (function (BABYLON) {
  57667. var PostProcessRenderEffect = /** @class */ (function () {
  57668. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  57669. this._name = name;
  57670. this._singleInstance = singleInstance || true;
  57671. this._getPostProcess = getPostProcess;
  57672. this._cameras = {};
  57673. this._indicesForCamera = {};
  57674. this._postProcesses = {};
  57675. this._renderPasses = {};
  57676. this._renderEffectAsPasses = {};
  57677. }
  57678. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  57679. get: function () {
  57680. for (var index in this._postProcesses) {
  57681. if (!this._postProcesses[index].isSupported) {
  57682. return false;
  57683. }
  57684. }
  57685. return true;
  57686. },
  57687. enumerable: true,
  57688. configurable: true
  57689. });
  57690. PostProcessRenderEffect.prototype._update = function () {
  57691. for (var renderPassName in this._renderPasses) {
  57692. this._renderPasses[renderPassName]._update();
  57693. }
  57694. };
  57695. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  57696. this._renderPasses[renderPass._name] = renderPass;
  57697. this._linkParameters();
  57698. };
  57699. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  57700. delete this._renderPasses[renderPass._name];
  57701. this._linkParameters();
  57702. };
  57703. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  57704. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  57705. this._linkParameters();
  57706. };
  57707. PostProcessRenderEffect.prototype.getPass = function (passName) {
  57708. for (var renderPassName in this._renderPasses) {
  57709. if (renderPassName === passName) {
  57710. return this._renderPasses[passName];
  57711. }
  57712. }
  57713. return null;
  57714. };
  57715. PostProcessRenderEffect.prototype.emptyPasses = function () {
  57716. this._renderPasses = {};
  57717. this._linkParameters();
  57718. };
  57719. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  57720. var cameraKey;
  57721. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57722. if (!cams) {
  57723. return;
  57724. }
  57725. for (var i = 0; i < cams.length; i++) {
  57726. var camera = cams[i];
  57727. var cameraName = camera.name;
  57728. if (this._singleInstance) {
  57729. cameraKey = 0;
  57730. }
  57731. else {
  57732. cameraKey = cameraName;
  57733. }
  57734. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  57735. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  57736. if (!this._indicesForCamera[cameraName]) {
  57737. this._indicesForCamera[cameraName] = [];
  57738. }
  57739. this._indicesForCamera[cameraName].push(index);
  57740. if (!this._cameras[cameraName]) {
  57741. this._cameras[cameraName] = camera;
  57742. }
  57743. for (var passName in this._renderPasses) {
  57744. this._renderPasses[passName]._incRefCount();
  57745. }
  57746. }
  57747. this._linkParameters();
  57748. };
  57749. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  57750. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57751. if (!cams) {
  57752. return;
  57753. }
  57754. for (var i = 0; i < cams.length; i++) {
  57755. var camera = cams[i];
  57756. var cameraName = camera.name;
  57757. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  57758. if (this._cameras[cameraName]) {
  57759. //this._indicesForCamera.splice(index, 1);
  57760. this._cameras[cameraName] = null;
  57761. }
  57762. for (var passName in this._renderPasses) {
  57763. this._renderPasses[passName]._decRefCount();
  57764. }
  57765. }
  57766. };
  57767. PostProcessRenderEffect.prototype._enable = function (cameras) {
  57768. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57769. if (!cams) {
  57770. return;
  57771. }
  57772. for (var i = 0; i < cams.length; i++) {
  57773. var camera = cams[i];
  57774. var cameraName = camera.name;
  57775. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  57776. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  57777. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  57778. }
  57779. }
  57780. for (var passName in this._renderPasses) {
  57781. this._renderPasses[passName]._incRefCount();
  57782. }
  57783. }
  57784. };
  57785. PostProcessRenderEffect.prototype._disable = function (cameras) {
  57786. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57787. if (!cams) {
  57788. return;
  57789. }
  57790. for (var i = 0; i < cams.length; i++) {
  57791. var camera = cams[i];
  57792. var cameraName = camera.Name;
  57793. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  57794. for (var passName in this._renderPasses) {
  57795. this._renderPasses[passName]._decRefCount();
  57796. }
  57797. }
  57798. };
  57799. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  57800. if (this._singleInstance) {
  57801. return this._postProcesses[0];
  57802. }
  57803. else {
  57804. if (!camera) {
  57805. return null;
  57806. }
  57807. return this._postProcesses[camera.name];
  57808. }
  57809. };
  57810. PostProcessRenderEffect.prototype._linkParameters = function () {
  57811. var _this = this;
  57812. for (var index in this._postProcesses) {
  57813. if (this.applyParameters) {
  57814. this.applyParameters(this._postProcesses[index]);
  57815. }
  57816. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  57817. _this._linkTextures(effect);
  57818. });
  57819. }
  57820. };
  57821. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  57822. for (var renderPassName in this._renderPasses) {
  57823. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  57824. }
  57825. for (var renderEffectName in this._renderEffectAsPasses) {
  57826. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  57827. }
  57828. };
  57829. return PostProcessRenderEffect;
  57830. }());
  57831. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  57832. })(BABYLON || (BABYLON = {}));
  57833. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  57834. var BABYLON;
  57835. (function (BABYLON) {
  57836. var PostProcessRenderPipeline = /** @class */ (function () {
  57837. function PostProcessRenderPipeline(engine, name) {
  57838. this._engine = engine;
  57839. this._name = name;
  57840. this._renderEffects = {};
  57841. this._renderEffectsForIsolatedPass = new Array();
  57842. this._cameras = [];
  57843. }
  57844. PostProcessRenderPipeline.prototype.getClassName = function () {
  57845. return "PostProcessRenderPipeline";
  57846. };
  57847. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  57848. get: function () {
  57849. for (var renderEffectName in this._renderEffects) {
  57850. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57851. if (!this._renderEffects[renderEffectName].isSupported) {
  57852. return false;
  57853. }
  57854. }
  57855. }
  57856. return true;
  57857. },
  57858. enumerable: true,
  57859. configurable: true
  57860. });
  57861. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  57862. this._renderEffects[renderEffect._name] = renderEffect;
  57863. };
  57864. // private
  57865. PostProcessRenderPipeline.prototype._rebuild = function () {
  57866. };
  57867. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  57868. var renderEffects = this._renderEffects[renderEffectName];
  57869. if (!renderEffects) {
  57870. return;
  57871. }
  57872. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  57873. };
  57874. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  57875. var renderEffects = this._renderEffects[renderEffectName];
  57876. if (!renderEffects) {
  57877. return;
  57878. }
  57879. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  57880. };
  57881. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  57882. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57883. if (!cams) {
  57884. return;
  57885. }
  57886. var indicesToDelete = [];
  57887. var i;
  57888. for (i = 0; i < cams.length; i++) {
  57889. var camera = cams[i];
  57890. var cameraName = camera.name;
  57891. if (this._cameras.indexOf(camera) === -1) {
  57892. this._cameras[cameraName] = camera;
  57893. }
  57894. else if (unique) {
  57895. indicesToDelete.push(i);
  57896. }
  57897. }
  57898. for (i = 0; i < indicesToDelete.length; i++) {
  57899. cameras.splice(indicesToDelete[i], 1);
  57900. }
  57901. for (var renderEffectName in this._renderEffects) {
  57902. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57903. this._renderEffects[renderEffectName]._attachCameras(cams);
  57904. }
  57905. }
  57906. };
  57907. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  57908. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57909. if (!cams) {
  57910. return;
  57911. }
  57912. for (var renderEffectName in this._renderEffects) {
  57913. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57914. this._renderEffects[renderEffectName]._detachCameras(cams);
  57915. }
  57916. }
  57917. for (var i = 0; i < cams.length; i++) {
  57918. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  57919. }
  57920. };
  57921. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  57922. var _this = this;
  57923. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57924. if (!cams) {
  57925. return;
  57926. }
  57927. var pass = null;
  57928. var renderEffectName;
  57929. for (renderEffectName in this._renderEffects) {
  57930. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57931. pass = this._renderEffects[renderEffectName].getPass(passName);
  57932. if (pass != null) {
  57933. break;
  57934. }
  57935. }
  57936. }
  57937. if (pass === null) {
  57938. return;
  57939. }
  57940. for (renderEffectName in this._renderEffects) {
  57941. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57942. this._renderEffects[renderEffectName]._disable(cams);
  57943. }
  57944. }
  57945. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  57946. for (var i = 0; i < cams.length; i++) {
  57947. var camera = cams[i];
  57948. var cameraName = camera.name;
  57949. 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); });
  57950. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  57951. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  57952. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  57953. }
  57954. };
  57955. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  57956. var _this = this;
  57957. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57958. if (!cams) {
  57959. return;
  57960. }
  57961. for (var i = 0; i < cams.length; i++) {
  57962. var camera = cams[i];
  57963. var cameraName = camera.name;
  57964. 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); });
  57965. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  57966. }
  57967. for (var renderEffectName in this._renderEffects) {
  57968. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57969. this._renderEffects[renderEffectName]._enable(cams);
  57970. }
  57971. }
  57972. };
  57973. PostProcessRenderPipeline.prototype._update = function () {
  57974. for (var renderEffectName in this._renderEffects) {
  57975. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57976. this._renderEffects[renderEffectName]._update();
  57977. }
  57978. }
  57979. for (var i = 0; i < this._cameras.length; i++) {
  57980. var cameraName = this._cameras[i].name;
  57981. if (this._renderEffectsForIsolatedPass[cameraName]) {
  57982. this._renderEffectsForIsolatedPass[cameraName]._update();
  57983. }
  57984. }
  57985. };
  57986. PostProcessRenderPipeline.prototype._reset = function () {
  57987. this._renderEffects = {};
  57988. this._renderEffectsForIsolatedPass = new Array();
  57989. };
  57990. PostProcessRenderPipeline.prototype.dispose = function () {
  57991. // Must be implemented by children
  57992. };
  57993. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  57994. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  57995. __decorate([
  57996. BABYLON.serialize()
  57997. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  57998. return PostProcessRenderPipeline;
  57999. }());
  58000. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  58001. })(BABYLON || (BABYLON = {}));
  58002. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  58003. var BABYLON;
  58004. (function (BABYLON) {
  58005. var DepthRenderer = /** @class */ (function () {
  58006. function DepthRenderer(scene, type) {
  58007. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  58008. var _this = this;
  58009. this._scene = scene;
  58010. var engine = scene.getEngine();
  58011. // Render target
  58012. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  58013. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58014. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58015. this._depthMap.refreshRate = 1;
  58016. this._depthMap.renderParticles = false;
  58017. this._depthMap.renderList = null;
  58018. // set default depth value to 1.0 (far away)
  58019. this._depthMap.onClearObservable.add(function (engine) {
  58020. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  58021. });
  58022. // Custom render function
  58023. var renderSubMesh = function (subMesh) {
  58024. var mesh = subMesh.getRenderingMesh();
  58025. var scene = _this._scene;
  58026. var engine = scene.getEngine();
  58027. var material = subMesh.getMaterial();
  58028. if (!material) {
  58029. return;
  58030. }
  58031. // Culling and reverse (right handed system)
  58032. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  58033. // Managing instances
  58034. var batch = mesh._getInstancesRenderList(subMesh._id);
  58035. if (batch.mustReturn) {
  58036. return;
  58037. }
  58038. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  58039. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  58040. engine.enableEffect(_this._effect);
  58041. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  58042. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  58043. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  58044. // Alpha test
  58045. if (material && material.needAlphaTesting()) {
  58046. var alphaTexture = material.getAlphaTestTexture();
  58047. if (alphaTexture) {
  58048. _this._effect.setTexture("diffuseSampler", alphaTexture);
  58049. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  58050. }
  58051. }
  58052. // Bones
  58053. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  58054. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  58055. }
  58056. // Draw
  58057. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  58058. }
  58059. };
  58060. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  58061. var index;
  58062. if (depthOnlySubMeshes.length) {
  58063. engine.setColorWrite(false);
  58064. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  58065. renderSubMesh(depthOnlySubMeshes.data[index]);
  58066. }
  58067. engine.setColorWrite(true);
  58068. }
  58069. for (index = 0; index < opaqueSubMeshes.length; index++) {
  58070. renderSubMesh(opaqueSubMeshes.data[index]);
  58071. }
  58072. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  58073. renderSubMesh(alphaTestSubMeshes.data[index]);
  58074. }
  58075. };
  58076. }
  58077. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  58078. var material = subMesh.getMaterial();
  58079. if (material.disableDepthWrite) {
  58080. return false;
  58081. }
  58082. var defines = [];
  58083. var attribs = [BABYLON.VertexBuffer.PositionKind];
  58084. var mesh = subMesh.getMesh();
  58085. // Alpha test
  58086. if (material && material.needAlphaTesting()) {
  58087. defines.push("#define ALPHATEST");
  58088. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  58089. attribs.push(BABYLON.VertexBuffer.UVKind);
  58090. defines.push("#define UV1");
  58091. }
  58092. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  58093. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  58094. defines.push("#define UV2");
  58095. }
  58096. }
  58097. // Bones
  58098. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58099. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58100. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58101. if (mesh.numBoneInfluencers > 4) {
  58102. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58103. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58104. }
  58105. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58106. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  58107. }
  58108. else {
  58109. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58110. }
  58111. // Instances
  58112. if (useInstances) {
  58113. defines.push("#define INSTANCES");
  58114. attribs.push("world0");
  58115. attribs.push("world1");
  58116. attribs.push("world2");
  58117. attribs.push("world3");
  58118. }
  58119. // Get correct effect
  58120. var join = defines.join("\n");
  58121. if (this._cachedDefines !== join) {
  58122. this._cachedDefines = join;
  58123. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  58124. }
  58125. return this._effect.isReady();
  58126. };
  58127. DepthRenderer.prototype.getDepthMap = function () {
  58128. return this._depthMap;
  58129. };
  58130. // Methods
  58131. DepthRenderer.prototype.dispose = function () {
  58132. this._depthMap.dispose();
  58133. };
  58134. return DepthRenderer;
  58135. }());
  58136. BABYLON.DepthRenderer = DepthRenderer;
  58137. })(BABYLON || (BABYLON = {}));
  58138. //# sourceMappingURL=babylon.depthRenderer.js.map
  58139. var BABYLON;
  58140. (function (BABYLON) {
  58141. var SSAORenderingPipeline = /** @class */ (function (_super) {
  58142. __extends(SSAORenderingPipeline, _super);
  58143. /**
  58144. * @constructor
  58145. * @param {string} name - The rendering pipeline name
  58146. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58147. * @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 }
  58148. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58149. */
  58150. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  58151. var _this = _super.call(this, scene.getEngine(), name) || this;
  58152. // Members
  58153. /**
  58154. * The PassPostProcess id in the pipeline that contains the original scene color
  58155. * @type {string}
  58156. */
  58157. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  58158. /**
  58159. * The SSAO PostProcess id in the pipeline
  58160. * @type {string}
  58161. */
  58162. _this.SSAORenderEffect = "SSAORenderEffect";
  58163. /**
  58164. * The horizontal blur PostProcess id in the pipeline
  58165. * @type {string}
  58166. */
  58167. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  58168. /**
  58169. * The vertical blur PostProcess id in the pipeline
  58170. * @type {string}
  58171. */
  58172. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  58173. /**
  58174. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  58175. * @type {string}
  58176. */
  58177. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  58178. /**
  58179. * The output strength of the SSAO post-process. Default value is 1.0.
  58180. * @type {number}
  58181. */
  58182. _this.totalStrength = 1.0;
  58183. /**
  58184. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  58185. * @type {number}
  58186. */
  58187. _this.radius = 0.0001;
  58188. /**
  58189. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  58190. * Must not be equal to fallOff and superior to fallOff.
  58191. * Default value is 0.975
  58192. * @type {number}
  58193. */
  58194. _this.area = 0.0075;
  58195. /**
  58196. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  58197. * Must not be equal to area and inferior to area.
  58198. * Default value is 0.0
  58199. * @type {number}
  58200. */
  58201. _this.fallOff = 0.000001;
  58202. /**
  58203. * The base color of the SSAO post-process
  58204. * The final result is "base + ssao" between [0, 1]
  58205. * @type {number}
  58206. */
  58207. _this.base = 0.5;
  58208. _this._firstUpdate = true;
  58209. _this._scene = scene;
  58210. // Set up assets
  58211. _this._createRandomTexture();
  58212. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  58213. var ssaoRatio = ratio.ssaoRatio || ratio;
  58214. var combineRatio = ratio.combineRatio || ratio;
  58215. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  58216. _this._createSSAOPostProcess(ssaoRatio);
  58217. _this._createBlurPostProcess(ssaoRatio);
  58218. _this._createSSAOCombinePostProcess(combineRatio);
  58219. // Set up pipeline
  58220. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  58221. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  58222. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  58223. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  58224. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  58225. // Finish
  58226. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58227. if (cameras)
  58228. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  58229. return _this;
  58230. }
  58231. // Public Methods
  58232. /**
  58233. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  58234. */
  58235. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  58236. if (disableDepthRender === void 0) { disableDepthRender = false; }
  58237. for (var i = 0; i < this._scene.cameras.length; i++) {
  58238. var camera = this._scene.cameras[i];
  58239. this._originalColorPostProcess.dispose(camera);
  58240. this._ssaoPostProcess.dispose(camera);
  58241. this._blurHPostProcess.dispose(camera);
  58242. this._blurVPostProcess.dispose(camera);
  58243. this._ssaoCombinePostProcess.dispose(camera);
  58244. }
  58245. this._randomTexture.dispose();
  58246. if (disableDepthRender)
  58247. this._scene.disableDepthRenderer();
  58248. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  58249. _super.prototype.dispose.call(this);
  58250. };
  58251. // Private Methods
  58252. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  58253. var _this = this;
  58254. var size = 16;
  58255. 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);
  58256. 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);
  58257. this._blurHPostProcess.onActivateObservable.add(function () {
  58258. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  58259. _this._blurHPostProcess.kernel = size * dw;
  58260. });
  58261. this._blurVPostProcess.onActivateObservable.add(function () {
  58262. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  58263. _this._blurVPostProcess.kernel = size * dw;
  58264. });
  58265. };
  58266. SSAORenderingPipeline.prototype._rebuild = function () {
  58267. this._firstUpdate = true;
  58268. _super.prototype._rebuild.call(this);
  58269. };
  58270. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  58271. var _this = this;
  58272. var numSamples = 16;
  58273. var sampleSphere = [
  58274. 0.5381, 0.1856, -0.4319,
  58275. 0.1379, 0.2486, 0.4430,
  58276. 0.3371, 0.5679, -0.0057,
  58277. -0.6999, -0.0451, -0.0019,
  58278. 0.0689, -0.1598, -0.8547,
  58279. 0.0560, 0.0069, -0.1843,
  58280. -0.0146, 0.1402, 0.0762,
  58281. 0.0100, -0.1924, -0.0344,
  58282. -0.3577, -0.5301, -0.4358,
  58283. -0.3169, 0.1063, 0.0158,
  58284. 0.0103, -0.5869, 0.0046,
  58285. -0.0897, -0.4940, 0.3287,
  58286. 0.7119, -0.0154, -0.0918,
  58287. -0.0533, 0.0596, -0.5411,
  58288. 0.0352, -0.0631, 0.5460,
  58289. -0.4776, 0.2847, -0.0271
  58290. ];
  58291. var samplesFactor = 1.0 / numSamples;
  58292. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  58293. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  58294. "area", "fallOff", "base", "range", "viewport"
  58295. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  58296. this._ssaoPostProcess.onApply = function (effect) {
  58297. if (_this._firstUpdate) {
  58298. effect.setArray3("sampleSphere", sampleSphere);
  58299. effect.setFloat("samplesFactor", samplesFactor);
  58300. effect.setFloat("randTextureTiles", 4.0);
  58301. }
  58302. effect.setFloat("totalStrength", _this.totalStrength);
  58303. effect.setFloat("radius", _this.radius);
  58304. effect.setFloat("area", _this.area);
  58305. effect.setFloat("fallOff", _this.fallOff);
  58306. effect.setFloat("base", _this.base);
  58307. effect.setTexture("textureSampler", _this._depthTexture);
  58308. effect.setTexture("randomSampler", _this._randomTexture);
  58309. };
  58310. };
  58311. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  58312. var _this = this;
  58313. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  58314. this._ssaoCombinePostProcess.onApply = function (effect) {
  58315. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  58316. };
  58317. };
  58318. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  58319. var size = 512;
  58320. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  58321. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58322. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58323. var context = this._randomTexture.getContext();
  58324. var rand = function (min, max) {
  58325. return Math.random() * (max - min) + min;
  58326. };
  58327. var randVector = BABYLON.Vector3.Zero();
  58328. for (var x = 0; x < size; x++) {
  58329. for (var y = 0; y < size; y++) {
  58330. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  58331. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  58332. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  58333. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  58334. context.fillRect(x, y, 1, 1);
  58335. }
  58336. }
  58337. this._randomTexture.update(false);
  58338. };
  58339. __decorate([
  58340. BABYLON.serialize()
  58341. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  58342. __decorate([
  58343. BABYLON.serialize()
  58344. ], SSAORenderingPipeline.prototype, "radius", void 0);
  58345. __decorate([
  58346. BABYLON.serialize()
  58347. ], SSAORenderingPipeline.prototype, "area", void 0);
  58348. __decorate([
  58349. BABYLON.serialize()
  58350. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  58351. __decorate([
  58352. BABYLON.serialize()
  58353. ], SSAORenderingPipeline.prototype, "base", void 0);
  58354. return SSAORenderingPipeline;
  58355. }(BABYLON.PostProcessRenderPipeline));
  58356. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  58357. })(BABYLON || (BABYLON = {}));
  58358. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  58359. var BABYLON;
  58360. (function (BABYLON) {
  58361. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  58362. __extends(SSAO2RenderingPipeline, _super);
  58363. /**
  58364. * @constructor
  58365. * @param {string} name - The rendering pipeline name
  58366. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58367. * @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 }
  58368. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58369. */
  58370. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  58371. var _this = _super.call(this, scene.getEngine(), name) || this;
  58372. // Members
  58373. /**
  58374. * The PassPostProcess id in the pipeline that contains the original scene color
  58375. * @type {string}
  58376. */
  58377. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  58378. /**
  58379. * The SSAO PostProcess id in the pipeline
  58380. * @type {string}
  58381. */
  58382. _this.SSAORenderEffect = "SSAORenderEffect";
  58383. /**
  58384. * The horizontal blur PostProcess id in the pipeline
  58385. * @type {string}
  58386. */
  58387. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  58388. /**
  58389. * The vertical blur PostProcess id in the pipeline
  58390. * @type {string}
  58391. */
  58392. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  58393. /**
  58394. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  58395. * @type {string}
  58396. */
  58397. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  58398. /**
  58399. * The output strength of the SSAO post-process. Default value is 1.0.
  58400. * @type {number}
  58401. */
  58402. _this.totalStrength = 1.0;
  58403. /**
  58404. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  58405. * @type {number}
  58406. */
  58407. _this.maxZ = 100.0;
  58408. /**
  58409. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  58410. * @type {number}
  58411. */
  58412. _this.minZAspect = 0.2;
  58413. /**
  58414. * Number of samples used for the SSAO calculations. Default value is 8
  58415. * @type {number}
  58416. */
  58417. _this._samples = 8;
  58418. /**
  58419. * Are we using bilateral blur ?
  58420. * @type {boolean}
  58421. */
  58422. _this._expensiveBlur = true;
  58423. /**
  58424. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  58425. * @type {number}
  58426. */
  58427. _this.radius = 2.0;
  58428. /**
  58429. * The base color of the SSAO post-process
  58430. * The final result is "base + ssao" between [0, 1]
  58431. * @type {number}
  58432. */
  58433. _this.base = 0.1;
  58434. _this._firstUpdate = true;
  58435. _this._scene = scene;
  58436. if (!_this.isSupported) {
  58437. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  58438. return _this;
  58439. }
  58440. var ssaoRatio = ratio.ssaoRatio || ratio;
  58441. var blurRatio = ratio.blurRatio || ratio;
  58442. // Set up assets
  58443. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  58444. _this._createRandomTexture();
  58445. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  58446. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  58447. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  58448. _this._createSSAOPostProcess(1.0);
  58449. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  58450. _this._createSSAOCombinePostProcess(blurRatio);
  58451. // Set up pipeline
  58452. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  58453. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  58454. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  58455. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  58456. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  58457. // Finish
  58458. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58459. if (cameras)
  58460. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  58461. return _this;
  58462. }
  58463. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  58464. get: function () {
  58465. return this._samples;
  58466. },
  58467. set: function (n) {
  58468. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  58469. this._samples = n;
  58470. this._sampleSphere = this._generateHemisphere();
  58471. this._firstUpdate = true;
  58472. },
  58473. enumerable: true,
  58474. configurable: true
  58475. });
  58476. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  58477. get: function () {
  58478. return this._expensiveBlur;
  58479. },
  58480. set: function (b) {
  58481. 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"]);
  58482. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  58483. this._expensiveBlur = b;
  58484. this._firstUpdate = true;
  58485. },
  58486. enumerable: true,
  58487. configurable: true
  58488. });
  58489. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  58490. /**
  58491. * Support test.
  58492. * @type {boolean}
  58493. */
  58494. get: function () {
  58495. var engine = BABYLON.Engine.LastCreatedEngine;
  58496. if (!engine) {
  58497. return false;
  58498. }
  58499. return engine.getCaps().drawBuffersExtension;
  58500. },
  58501. enumerable: true,
  58502. configurable: true
  58503. });
  58504. // Public Methods
  58505. /**
  58506. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  58507. */
  58508. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  58509. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  58510. for (var i = 0; i < this._scene.cameras.length; i++) {
  58511. var camera = this._scene.cameras[i];
  58512. this._originalColorPostProcess.dispose(camera);
  58513. this._ssaoPostProcess.dispose(camera);
  58514. this._blurHPostProcess.dispose(camera);
  58515. this._blurVPostProcess.dispose(camera);
  58516. this._ssaoCombinePostProcess.dispose(camera);
  58517. }
  58518. this._randomTexture.dispose();
  58519. if (disableGeometryBufferRenderer)
  58520. this._scene.disableGeometryBufferRenderer();
  58521. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  58522. _super.prototype.dispose.call(this);
  58523. };
  58524. // Private Methods
  58525. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  58526. var _this = this;
  58527. this._samplerOffsets = [];
  58528. var expensive = this.expensiveBlur;
  58529. for (var i = -8; i < 8; i++) {
  58530. this._samplerOffsets.push(i * 2 + 0.5);
  58531. }
  58532. 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");
  58533. this._blurHPostProcess.onApply = function (effect) {
  58534. if (!_this._scene.activeCamera) {
  58535. return;
  58536. }
  58537. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  58538. effect.setFloat("near", _this._scene.activeCamera.minZ);
  58539. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  58540. effect.setFloat("radius", _this.radius);
  58541. effect.setTexture("depthSampler", _this._depthTexture);
  58542. if (_this._firstUpdate) {
  58543. effect.setArray("samplerOffsets", _this._samplerOffsets);
  58544. }
  58545. };
  58546. 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");
  58547. this._blurVPostProcess.onApply = function (effect) {
  58548. if (!_this._scene.activeCamera) {
  58549. return;
  58550. }
  58551. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  58552. effect.setFloat("near", _this._scene.activeCamera.minZ);
  58553. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  58554. effect.setFloat("radius", _this.radius);
  58555. effect.setTexture("depthSampler", _this._depthTexture);
  58556. if (_this._firstUpdate) {
  58557. effect.setArray("samplerOffsets", _this._samplerOffsets);
  58558. _this._firstUpdate = false;
  58559. }
  58560. };
  58561. };
  58562. SSAO2RenderingPipeline.prototype._rebuild = function () {
  58563. this._firstUpdate = true;
  58564. _super.prototype._rebuild.call(this);
  58565. };
  58566. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  58567. var numSamples = this.samples;
  58568. var result = [];
  58569. var vector, scale;
  58570. var rand = function (min, max) {
  58571. return Math.random() * (max - min) + min;
  58572. };
  58573. var i = 0;
  58574. while (i < numSamples) {
  58575. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  58576. vector.normalize();
  58577. scale = i / numSamples;
  58578. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  58579. vector.scaleInPlace(scale);
  58580. result.push(vector.x, vector.y, vector.z);
  58581. i++;
  58582. }
  58583. return result;
  58584. };
  58585. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  58586. var _this = this;
  58587. var numSamples = this.samples;
  58588. this._sampleSphere = this._generateHemisphere();
  58589. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  58590. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  58591. "base", "range", "projection", "near", "far", "texelSize",
  58592. "xViewport", "yViewport", "maxZ", "minZAspect"
  58593. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  58594. this._ssaoPostProcess.onApply = function (effect) {
  58595. if (_this._firstUpdate) {
  58596. effect.setArray3("sampleSphere", _this._sampleSphere);
  58597. effect.setFloat("randTextureTiles", 4.0);
  58598. }
  58599. if (!_this._scene.activeCamera) {
  58600. return;
  58601. }
  58602. effect.setFloat("samplesFactor", 1 / _this.samples);
  58603. effect.setFloat("totalStrength", _this.totalStrength);
  58604. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  58605. effect.setFloat("radius", _this.radius);
  58606. effect.setFloat("maxZ", _this.maxZ);
  58607. effect.setFloat("minZAspect", _this.minZAspect);
  58608. effect.setFloat("base", _this.base);
  58609. effect.setFloat("near", _this._scene.activeCamera.minZ);
  58610. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  58611. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  58612. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  58613. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  58614. effect.setTexture("textureSampler", _this._depthTexture);
  58615. effect.setTexture("normalSampler", _this._normalTexture);
  58616. effect.setTexture("randomSampler", _this._randomTexture);
  58617. };
  58618. };
  58619. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  58620. var _this = this;
  58621. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  58622. this._ssaoCombinePostProcess.onApply = function (effect) {
  58623. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  58624. };
  58625. };
  58626. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  58627. var size = 512;
  58628. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  58629. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58630. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58631. var context = this._randomTexture.getContext();
  58632. var rand = function (min, max) {
  58633. return Math.random() * (max - min) + min;
  58634. };
  58635. var randVector = BABYLON.Vector3.Zero();
  58636. for (var x = 0; x < size; x++) {
  58637. for (var y = 0; y < size; y++) {
  58638. randVector.x = rand(0.0, 1.0);
  58639. randVector.y = rand(0.0, 1.0);
  58640. randVector.z = 0.0;
  58641. randVector.normalize();
  58642. randVector.scaleInPlace(255);
  58643. randVector.x = Math.floor(randVector.x);
  58644. randVector.y = Math.floor(randVector.y);
  58645. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  58646. context.fillRect(x, y, 1, 1);
  58647. }
  58648. }
  58649. this._randomTexture.update(false);
  58650. };
  58651. __decorate([
  58652. BABYLON.serialize()
  58653. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  58654. __decorate([
  58655. BABYLON.serialize()
  58656. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  58657. __decorate([
  58658. BABYLON.serialize()
  58659. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  58660. __decorate([
  58661. BABYLON.serialize("samples")
  58662. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  58663. __decorate([
  58664. BABYLON.serialize("expensiveBlur")
  58665. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  58666. __decorate([
  58667. BABYLON.serialize()
  58668. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  58669. __decorate([
  58670. BABYLON.serialize()
  58671. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  58672. return SSAO2RenderingPipeline;
  58673. }(BABYLON.PostProcessRenderPipeline));
  58674. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  58675. })(BABYLON || (BABYLON = {}));
  58676. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  58677. // BABYLON.JS Chromatic Aberration GLSL Shader
  58678. // Author: Olivier Guyot
  58679. // Separates very slightly R, G and B colors on the edges of the screen
  58680. // Inspired by Francois Tarlier & Martins Upitis
  58681. var BABYLON;
  58682. (function (BABYLON) {
  58683. var LensRenderingPipeline = /** @class */ (function (_super) {
  58684. __extends(LensRenderingPipeline, _super);
  58685. /**
  58686. * @constructor
  58687. *
  58688. * Effect parameters are as follow:
  58689. * {
  58690. * chromatic_aberration: number; // from 0 to x (1 for realism)
  58691. * edge_blur: number; // from 0 to x (1 for realism)
  58692. * distortion: number; // from 0 to x (1 for realism)
  58693. * grain_amount: number; // from 0 to 1
  58694. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  58695. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  58696. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  58697. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  58698. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  58699. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  58700. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  58701. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  58702. * }
  58703. * Note: if an effect parameter is unset, effect is disabled
  58704. *
  58705. * @param {string} name - The rendering pipeline name
  58706. * @param {object} parameters - An object containing all parameters (see above)
  58707. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58708. * @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)
  58709. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58710. */
  58711. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  58712. if (ratio === void 0) { ratio = 1.0; }
  58713. var _this = _super.call(this, scene.getEngine(), name) || this;
  58714. // Lens effects can be of the following:
  58715. // - chromatic aberration (slight shift of RGB colors)
  58716. // - blur on the edge of the lens
  58717. // - lens distortion
  58718. // - depth-of-field blur & highlights enhancing
  58719. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  58720. // - grain effect (noise or custom texture)
  58721. // Two additional texture samplers are needed:
  58722. // - depth map (for depth-of-field)
  58723. // - grain texture
  58724. /**
  58725. * The chromatic aberration PostProcess id in the pipeline
  58726. * @type {string}
  58727. */
  58728. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  58729. /**
  58730. * The highlights enhancing PostProcess id in the pipeline
  58731. * @type {string}
  58732. */
  58733. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  58734. /**
  58735. * The depth-of-field PostProcess id in the pipeline
  58736. * @type {string}
  58737. */
  58738. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  58739. _this._scene = scene;
  58740. // Fetch texture samplers
  58741. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  58742. if (parameters.grain_texture) {
  58743. _this._grainTexture = parameters.grain_texture;
  58744. }
  58745. else {
  58746. _this._createGrainTexture();
  58747. }
  58748. // save parameters
  58749. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  58750. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  58751. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  58752. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  58753. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  58754. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  58755. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  58756. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  58757. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  58758. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  58759. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  58760. // Create effects
  58761. _this._createChromaticAberrationPostProcess(ratio);
  58762. _this._createHighlightsPostProcess(ratio);
  58763. _this._createDepthOfFieldPostProcess(ratio / 4);
  58764. // Set up pipeline
  58765. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  58766. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  58767. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  58768. if (_this._highlightsGain === -1) {
  58769. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  58770. }
  58771. // Finish
  58772. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58773. if (cameras) {
  58774. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  58775. }
  58776. return _this;
  58777. }
  58778. // public methods (self explanatory)
  58779. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  58780. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  58781. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  58782. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  58783. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  58784. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  58785. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  58786. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  58787. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  58788. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  58789. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  58790. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  58791. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  58792. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  58793. };
  58794. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  58795. this._highlightsPostProcess.updateEffect();
  58796. };
  58797. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  58798. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  58799. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  58800. this._highlightsGain = amount;
  58801. };
  58802. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  58803. if (this._highlightsGain === -1) {
  58804. this._highlightsGain = 1.0;
  58805. }
  58806. this._highlightsThreshold = amount;
  58807. };
  58808. LensRenderingPipeline.prototype.disableHighlights = function () {
  58809. this._highlightsGain = -1;
  58810. };
  58811. /**
  58812. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  58813. */
  58814. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  58815. if (disableDepthRender === void 0) { disableDepthRender = false; }
  58816. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  58817. this._chromaticAberrationPostProcess = null;
  58818. this._highlightsPostProcess = null;
  58819. this._depthOfFieldPostProcess = null;
  58820. this._grainTexture.dispose();
  58821. if (disableDepthRender)
  58822. this._scene.disableDepthRenderer();
  58823. };
  58824. // colors shifting and distortion
  58825. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  58826. var _this = this;
  58827. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  58828. [], // samplers
  58829. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  58830. this._chromaticAberrationPostProcess.onApply = function (effect) {
  58831. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  58832. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  58833. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  58834. };
  58835. };
  58836. // highlights enhancing
  58837. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  58838. var _this = this;
  58839. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  58840. [], // samplers
  58841. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  58842. this._highlightsPostProcess.onApply = function (effect) {
  58843. effect.setFloat('gain', _this._highlightsGain);
  58844. effect.setFloat('threshold', _this._highlightsThreshold);
  58845. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  58846. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  58847. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  58848. };
  58849. };
  58850. // colors shifting and distortion
  58851. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  58852. var _this = this;
  58853. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  58854. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  58855. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  58856. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  58857. this._depthOfFieldPostProcess.onApply = function (effect) {
  58858. effect.setTexture("depthSampler", _this._depthTexture);
  58859. effect.setTexture("grainSampler", _this._grainTexture);
  58860. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  58861. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  58862. effect.setFloat('grain_amount', _this._grainAmount);
  58863. effect.setBool('blur_noise', _this._blurNoise);
  58864. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  58865. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  58866. effect.setFloat('distortion', _this._distortion);
  58867. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  58868. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  58869. effect.setFloat('aperture', _this._dofAperture);
  58870. effect.setFloat('darken', _this._dofDarken);
  58871. effect.setFloat('edge_blur', _this._edgeBlur);
  58872. effect.setBool('highlights', (_this._highlightsGain !== -1));
  58873. if (_this._scene.activeCamera) {
  58874. effect.setFloat('near', _this._scene.activeCamera.minZ);
  58875. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  58876. }
  58877. };
  58878. };
  58879. // creates a black and white random noise texture, 512x512
  58880. LensRenderingPipeline.prototype._createGrainTexture = function () {
  58881. var size = 512;
  58882. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58883. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58884. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58885. var context = this._grainTexture.getContext();
  58886. var rand = function (min, max) {
  58887. return Math.random() * (max - min) + min;
  58888. };
  58889. var value;
  58890. for (var x = 0; x < size; x++) {
  58891. for (var y = 0; y < size; y++) {
  58892. value = Math.floor(rand(0.42, 0.58) * 255);
  58893. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  58894. context.fillRect(x, y, 1, 1);
  58895. }
  58896. }
  58897. this._grainTexture.update(false);
  58898. };
  58899. return LensRenderingPipeline;
  58900. }(BABYLON.PostProcessRenderPipeline));
  58901. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  58902. })(BABYLON || (BABYLON = {}));
  58903. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  58904. var BABYLON;
  58905. (function (BABYLON) {
  58906. var StandardRenderingPipeline = /** @class */ (function (_super) {
  58907. __extends(StandardRenderingPipeline, _super);
  58908. /**
  58909. * @constructor
  58910. * @param {string} name - The rendering pipeline name
  58911. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58912. * @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)
  58913. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  58914. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58915. */
  58916. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  58917. if (originalPostProcess === void 0) { originalPostProcess = null; }
  58918. var _this = _super.call(this, scene.getEngine(), name) || this;
  58919. _this.downSampleX4PostProcess = null;
  58920. _this.brightPassPostProcess = null;
  58921. _this.blurHPostProcesses = [];
  58922. _this.blurVPostProcesses = [];
  58923. _this.textureAdderPostProcess = null;
  58924. _this.volumetricLightPostProcess = null;
  58925. _this.volumetricLightSmoothXPostProcess = null;
  58926. _this.volumetricLightSmoothYPostProcess = null;
  58927. _this.volumetricLightMergePostProces = null;
  58928. _this.volumetricLightFinalPostProcess = null;
  58929. _this.luminancePostProcess = null;
  58930. _this.luminanceDownSamplePostProcesses = [];
  58931. _this.hdrPostProcess = null;
  58932. _this.textureAdderFinalPostProcess = null;
  58933. _this.lensFlareFinalPostProcess = null;
  58934. _this.hdrFinalPostProcess = null;
  58935. _this.lensFlarePostProcess = null;
  58936. _this.lensFlareComposePostProcess = null;
  58937. _this.motionBlurPostProcess = null;
  58938. _this.depthOfFieldPostProcess = null;
  58939. // Values
  58940. _this.brightThreshold = 1.0;
  58941. _this.blurWidth = 512.0;
  58942. _this.horizontalBlur = false;
  58943. _this.exposure = 1.0;
  58944. _this.lensTexture = null;
  58945. _this.volumetricLightCoefficient = 0.2;
  58946. _this.volumetricLightPower = 4.0;
  58947. _this.volumetricLightBlurScale = 64.0;
  58948. _this.sourceLight = null;
  58949. _this.hdrMinimumLuminance = 1.0;
  58950. _this.hdrDecreaseRate = 0.5;
  58951. _this.hdrIncreaseRate = 0.5;
  58952. _this.lensColorTexture = null;
  58953. _this.lensFlareStrength = 20.0;
  58954. _this.lensFlareGhostDispersal = 1.4;
  58955. _this.lensFlareHaloWidth = 0.7;
  58956. _this.lensFlareDistortionStrength = 16.0;
  58957. _this.lensStarTexture = null;
  58958. _this.lensFlareDirtTexture = null;
  58959. _this.depthOfFieldDistance = 10.0;
  58960. _this.depthOfFieldBlurWidth = 64.0;
  58961. _this.motionStrength = 1.0;
  58962. // IAnimatable
  58963. _this.animations = [];
  58964. _this._currentDepthOfFieldSource = null;
  58965. _this._hdrCurrentLuminance = 1.0;
  58966. // Getters and setters
  58967. _this._bloomEnabled = true;
  58968. _this._depthOfFieldEnabled = false;
  58969. _this._vlsEnabled = false;
  58970. _this._lensFlareEnabled = false;
  58971. _this._hdrEnabled = false;
  58972. _this._motionBlurEnabled = false;
  58973. _this._motionBlurSamples = 64.0;
  58974. _this._volumetricLightStepsCount = 50.0;
  58975. _this._cameras = cameras || [];
  58976. // Initialize
  58977. _this._scene = scene;
  58978. _this._basePostProcess = originalPostProcess;
  58979. _this._ratio = ratio;
  58980. // Misc
  58981. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58982. // Finish
  58983. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58984. _this._buildPipeline();
  58985. return _this;
  58986. }
  58987. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  58988. get: function () {
  58989. return this._bloomEnabled;
  58990. },
  58991. set: function (enabled) {
  58992. if (this._bloomEnabled === enabled) {
  58993. return;
  58994. }
  58995. this._bloomEnabled = enabled;
  58996. this._buildPipeline();
  58997. },
  58998. enumerable: true,
  58999. configurable: true
  59000. });
  59001. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  59002. get: function () {
  59003. return this._depthOfFieldEnabled;
  59004. },
  59005. set: function (enabled) {
  59006. if (this._depthOfFieldEnabled === enabled) {
  59007. return;
  59008. }
  59009. this._depthOfFieldEnabled = enabled;
  59010. this._buildPipeline();
  59011. },
  59012. enumerable: true,
  59013. configurable: true
  59014. });
  59015. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  59016. get: function () {
  59017. return this._lensFlareEnabled;
  59018. },
  59019. set: function (enabled) {
  59020. if (this._lensFlareEnabled === enabled) {
  59021. return;
  59022. }
  59023. this._lensFlareEnabled = enabled;
  59024. this._buildPipeline();
  59025. },
  59026. enumerable: true,
  59027. configurable: true
  59028. });
  59029. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  59030. get: function () {
  59031. return this._hdrEnabled;
  59032. },
  59033. set: function (enabled) {
  59034. if (this._hdrEnabled === enabled) {
  59035. return;
  59036. }
  59037. this._hdrEnabled = enabled;
  59038. this._buildPipeline();
  59039. },
  59040. enumerable: true,
  59041. configurable: true
  59042. });
  59043. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  59044. get: function () {
  59045. return this._vlsEnabled;
  59046. },
  59047. set: function (enabled) {
  59048. if (this._vlsEnabled === enabled) {
  59049. return;
  59050. }
  59051. if (enabled) {
  59052. var geometry = this._scene.enableGeometryBufferRenderer();
  59053. if (!geometry) {
  59054. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  59055. return;
  59056. }
  59057. }
  59058. this._vlsEnabled = enabled;
  59059. this._buildPipeline();
  59060. },
  59061. enumerable: true,
  59062. configurable: true
  59063. });
  59064. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  59065. get: function () {
  59066. return this._motionBlurEnabled;
  59067. },
  59068. set: function (enabled) {
  59069. if (this._motionBlurEnabled === enabled) {
  59070. return;
  59071. }
  59072. this._motionBlurEnabled = enabled;
  59073. this._buildPipeline();
  59074. },
  59075. enumerable: true,
  59076. configurable: true
  59077. });
  59078. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  59079. get: function () {
  59080. return this._volumetricLightStepsCount;
  59081. },
  59082. set: function (count) {
  59083. if (this.volumetricLightPostProcess) {
  59084. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  59085. }
  59086. this._volumetricLightStepsCount = count;
  59087. },
  59088. enumerable: true,
  59089. configurable: true
  59090. });
  59091. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  59092. get: function () {
  59093. return this._motionBlurSamples;
  59094. },
  59095. set: function (samples) {
  59096. if (this.motionBlurPostProcess) {
  59097. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  59098. }
  59099. this._motionBlurSamples = samples;
  59100. },
  59101. enumerable: true,
  59102. configurable: true
  59103. });
  59104. StandardRenderingPipeline.prototype._buildPipeline = function () {
  59105. var _this = this;
  59106. var ratio = this._ratio;
  59107. var scene = this._scene;
  59108. this._disposePostProcesses();
  59109. this._reset();
  59110. // Create pass post-process
  59111. if (!this._basePostProcess) {
  59112. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  59113. this.originalPostProcess.onApply = function (effect) {
  59114. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  59115. };
  59116. }
  59117. else {
  59118. this.originalPostProcess = this._basePostProcess;
  59119. }
  59120. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  59121. this._currentDepthOfFieldSource = this.originalPostProcess;
  59122. if (this._vlsEnabled) {
  59123. // Create volumetric light
  59124. this._createVolumetricLightPostProcess(scene, ratio);
  59125. // Create volumetric light final post-process
  59126. 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);
  59127. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  59128. }
  59129. if (this._bloomEnabled) {
  59130. // Create down sample X4 post-process
  59131. this._createDownSampleX4PostProcess(scene, ratio / 2);
  59132. // Create bright pass post-process
  59133. this._createBrightPassPostProcess(scene, ratio / 2);
  59134. // Create gaussian blur post-processes (down sampling blurs)
  59135. this._createBlurPostProcesses(scene, ratio / 4, 1);
  59136. // Create texture adder post-process
  59137. this._createTextureAdderPostProcess(scene, ratio);
  59138. // Create depth-of-field source post-process
  59139. 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);
  59140. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  59141. }
  59142. if (this._lensFlareEnabled) {
  59143. // Create lens flare post-process
  59144. this._createLensFlarePostProcess(scene, ratio);
  59145. // Create depth-of-field source post-process post lens-flare and disable it now
  59146. 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);
  59147. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  59148. }
  59149. if (this._hdrEnabled) {
  59150. // Create luminance
  59151. this._createLuminancePostProcesses(scene, this._floatTextureType);
  59152. // Create HDR
  59153. this._createHdrPostProcess(scene, ratio);
  59154. // Create depth-of-field source post-process post hdr and disable it now
  59155. 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);
  59156. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  59157. }
  59158. if (this._depthOfFieldEnabled) {
  59159. // Create gaussian blur used by depth-of-field
  59160. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  59161. // Create depth-of-field post-process
  59162. this._createDepthOfFieldPostProcess(scene, ratio);
  59163. }
  59164. if (this._motionBlurEnabled) {
  59165. // Create motion blur post-process
  59166. this._createMotionBlurPostProcess(scene, ratio);
  59167. }
  59168. if (this._cameras !== null) {
  59169. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  59170. }
  59171. };
  59172. // Down Sample X4 Post-Processs
  59173. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  59174. var _this = this;
  59175. var downSampleX4Offsets = new Array(32);
  59176. 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);
  59177. this.downSampleX4PostProcess.onApply = function (effect) {
  59178. var id = 0;
  59179. var width = _this.downSampleX4PostProcess.width;
  59180. var height = _this.downSampleX4PostProcess.height;
  59181. for (var i = -2; i < 2; i++) {
  59182. for (var j = -2; j < 2; j++) {
  59183. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  59184. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  59185. id += 2;
  59186. }
  59187. }
  59188. effect.setArray2("dsOffsets", downSampleX4Offsets);
  59189. };
  59190. // Add to pipeline
  59191. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  59192. };
  59193. // Brightpass Post-Process
  59194. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  59195. var _this = this;
  59196. var brightOffsets = new Array(8);
  59197. 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);
  59198. this.brightPassPostProcess.onApply = function (effect) {
  59199. var sU = (1.0 / _this.brightPassPostProcess.width);
  59200. var sV = (1.0 / _this.brightPassPostProcess.height);
  59201. brightOffsets[0] = -0.5 * sU;
  59202. brightOffsets[1] = 0.5 * sV;
  59203. brightOffsets[2] = 0.5 * sU;
  59204. brightOffsets[3] = 0.5 * sV;
  59205. brightOffsets[4] = -0.5 * sU;
  59206. brightOffsets[5] = -0.5 * sV;
  59207. brightOffsets[6] = 0.5 * sU;
  59208. brightOffsets[7] = -0.5 * sV;
  59209. effect.setArray2("dsOffsets", brightOffsets);
  59210. effect.setFloat("brightThreshold", _this.brightThreshold);
  59211. };
  59212. // Add to pipeline
  59213. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  59214. };
  59215. // Create blur H&V post-processes
  59216. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  59217. var _this = this;
  59218. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  59219. var engine = scene.getEngine();
  59220. 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);
  59221. 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);
  59222. blurX.onActivateObservable.add(function () {
  59223. var dw = blurX.width / engine.getRenderWidth();
  59224. blurX.kernel = _this[blurWidthKey] * dw;
  59225. });
  59226. blurY.onActivateObservable.add(function () {
  59227. var dw = blurY.height / engine.getRenderHeight();
  59228. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  59229. });
  59230. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  59231. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  59232. this.blurHPostProcesses.push(blurX);
  59233. this.blurVPostProcesses.push(blurY);
  59234. };
  59235. // Create texture adder post-process
  59236. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  59237. var _this = this;
  59238. 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);
  59239. this.textureAdderPostProcess.onApply = function (effect) {
  59240. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  59241. effect.setTexture("lensSampler", _this.lensTexture);
  59242. effect.setFloat("exposure", _this.exposure);
  59243. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  59244. };
  59245. // Add to pipeline
  59246. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  59247. };
  59248. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  59249. var _this = this;
  59250. var geometryRenderer = scene.enableGeometryBufferRenderer();
  59251. geometryRenderer.enablePosition = true;
  59252. var geometry = geometryRenderer.getGBuffer();
  59253. // Base post-process
  59254. 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));
  59255. var depthValues = BABYLON.Vector2.Zero();
  59256. this.volumetricLightPostProcess.onApply = function (effect) {
  59257. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  59258. var generator = _this.sourceLight.getShadowGenerator();
  59259. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  59260. effect.setTexture("positionSampler", geometry.textures[2]);
  59261. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  59262. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  59263. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  59264. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  59265. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  59266. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  59267. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  59268. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  59269. effect.setVector2("depthValues", depthValues);
  59270. }
  59271. };
  59272. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  59273. // Smooth
  59274. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  59275. // Merge
  59276. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  59277. this.volumetricLightMergePostProces.onApply = function (effect) {
  59278. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  59279. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  59280. };
  59281. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  59282. };
  59283. // Create luminance
  59284. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  59285. var _this = this;
  59286. // Create luminance
  59287. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  59288. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  59289. var offsets = [];
  59290. this.luminancePostProcess.onApply = function (effect) {
  59291. var sU = (1.0 / _this.luminancePostProcess.width);
  59292. var sV = (1.0 / _this.luminancePostProcess.height);
  59293. offsets[0] = -0.5 * sU;
  59294. offsets[1] = 0.5 * sV;
  59295. offsets[2] = 0.5 * sU;
  59296. offsets[3] = 0.5 * sV;
  59297. offsets[4] = -0.5 * sU;
  59298. offsets[5] = -0.5 * sV;
  59299. offsets[6] = 0.5 * sU;
  59300. offsets[7] = -0.5 * sV;
  59301. effect.setArray2("lumOffsets", offsets);
  59302. };
  59303. // Add to pipeline
  59304. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  59305. // Create down sample luminance
  59306. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  59307. var size = Math.pow(3, i);
  59308. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  59309. if (i === 0) {
  59310. defines += "#define FINAL_DOWN_SAMPLER";
  59311. }
  59312. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  59313. this.luminanceDownSamplePostProcesses.push(postProcess);
  59314. }
  59315. // Create callbacks and add effects
  59316. var lastLuminance = this.luminancePostProcess;
  59317. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  59318. var downSampleOffsets = new Array(18);
  59319. pp.onApply = function (effect) {
  59320. if (!lastLuminance) {
  59321. return;
  59322. }
  59323. var id = 0;
  59324. for (var x = -1; x < 2; x++) {
  59325. for (var y = -1; y < 2; y++) {
  59326. downSampleOffsets[id] = x / lastLuminance.width;
  59327. downSampleOffsets[id + 1] = y / lastLuminance.height;
  59328. id += 2;
  59329. }
  59330. }
  59331. effect.setArray2("dsOffsets", downSampleOffsets);
  59332. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  59333. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  59334. lastLuminance = _this.luminancePostProcess;
  59335. }
  59336. else {
  59337. lastLuminance = pp;
  59338. }
  59339. };
  59340. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  59341. pp.onAfterRender = function (effect) {
  59342. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  59343. 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);
  59344. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  59345. };
  59346. }
  59347. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  59348. });
  59349. };
  59350. // Create HDR post-process
  59351. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  59352. var _this = this;
  59353. 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);
  59354. var outputLiminance = 1;
  59355. var time = 0;
  59356. var lastTime = 0;
  59357. this.hdrPostProcess.onApply = function (effect) {
  59358. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  59359. time += scene.getEngine().getDeltaTime();
  59360. if (outputLiminance < 0) {
  59361. outputLiminance = _this._hdrCurrentLuminance;
  59362. }
  59363. else {
  59364. var dt = (lastTime - time) / 1000.0;
  59365. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  59366. outputLiminance += _this.hdrDecreaseRate * dt;
  59367. }
  59368. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  59369. outputLiminance -= _this.hdrIncreaseRate * dt;
  59370. }
  59371. else {
  59372. outputLiminance = _this._hdrCurrentLuminance;
  59373. }
  59374. }
  59375. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  59376. effect.setFloat("averageLuminance", outputLiminance);
  59377. lastTime = time;
  59378. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  59379. };
  59380. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  59381. };
  59382. // Create lens flare post-process
  59383. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  59384. var _this = this;
  59385. 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);
  59386. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  59387. this._createBlurPostProcesses(scene, ratio / 4, 2);
  59388. 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);
  59389. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  59390. var resolution = new BABYLON.Vector2(0, 0);
  59391. // Lens flare
  59392. this.lensFlarePostProcess.onApply = function (effect) {
  59393. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  59394. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  59395. effect.setFloat("strength", _this.lensFlareStrength);
  59396. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  59397. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  59398. // Shift
  59399. resolution.x = _this.lensFlarePostProcess.width;
  59400. resolution.y = _this.lensFlarePostProcess.height;
  59401. effect.setVector2("resolution", resolution);
  59402. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  59403. };
  59404. // Compose
  59405. 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);
  59406. 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);
  59407. this.lensFlareComposePostProcess.onApply = function (effect) {
  59408. if (!_this._scene.activeCamera) {
  59409. return;
  59410. }
  59411. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  59412. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  59413. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  59414. // Lens start rotation matrix
  59415. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  59416. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  59417. 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));
  59418. camRot *= 4.0;
  59419. 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);
  59420. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  59421. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  59422. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  59423. };
  59424. };
  59425. // Create depth-of-field post-process
  59426. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  59427. var _this = this;
  59428. 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);
  59429. this.depthOfFieldPostProcess.onApply = function (effect) {
  59430. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  59431. effect.setTexture("depthSampler", _this._getDepthTexture());
  59432. effect.setFloat("distance", _this.depthOfFieldDistance);
  59433. };
  59434. // Add to pipeline
  59435. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  59436. };
  59437. // Create motion blur post-process
  59438. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  59439. var _this = this;
  59440. 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);
  59441. var motionScale = 0;
  59442. var prevViewProjection = BABYLON.Matrix.Identity();
  59443. var invViewProjection = BABYLON.Matrix.Identity();
  59444. var viewProjection = BABYLON.Matrix.Identity();
  59445. var screenSize = BABYLON.Vector2.Zero();
  59446. this.motionBlurPostProcess.onApply = function (effect) {
  59447. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  59448. viewProjection.invertToRef(invViewProjection);
  59449. effect.setMatrix("inverseViewProjection", invViewProjection);
  59450. effect.setMatrix("prevViewProjection", prevViewProjection);
  59451. prevViewProjection = viewProjection;
  59452. screenSize.x = _this.motionBlurPostProcess.width;
  59453. screenSize.y = _this.motionBlurPostProcess.height;
  59454. effect.setVector2("screenSize", screenSize);
  59455. motionScale = scene.getEngine().getFps() / 60.0;
  59456. effect.setFloat("motionScale", motionScale);
  59457. effect.setFloat("motionStrength", _this.motionStrength);
  59458. effect.setTexture("depthSampler", _this._getDepthTexture());
  59459. };
  59460. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  59461. };
  59462. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  59463. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  59464. var renderer = this._scene.enableGeometryBufferRenderer();
  59465. return renderer.getGBuffer().textures[0];
  59466. }
  59467. return this._scene.enableDepthRenderer().getDepthMap();
  59468. };
  59469. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  59470. for (var i = 0; i < this._cameras.length; i++) {
  59471. var camera = this._cameras[i];
  59472. if (this.originalPostProcess) {
  59473. this.originalPostProcess.dispose(camera);
  59474. }
  59475. if (this.downSampleX4PostProcess) {
  59476. this.downSampleX4PostProcess.dispose(camera);
  59477. }
  59478. if (this.brightPassPostProcess) {
  59479. this.brightPassPostProcess.dispose(camera);
  59480. }
  59481. if (this.textureAdderPostProcess) {
  59482. this.textureAdderPostProcess.dispose(camera);
  59483. }
  59484. if (this.textureAdderFinalPostProcess) {
  59485. this.textureAdderFinalPostProcess.dispose(camera);
  59486. }
  59487. if (this.volumetricLightPostProcess) {
  59488. this.volumetricLightPostProcess.dispose(camera);
  59489. }
  59490. if (this.volumetricLightSmoothXPostProcess) {
  59491. this.volumetricLightSmoothXPostProcess.dispose(camera);
  59492. }
  59493. if (this.volumetricLightSmoothYPostProcess) {
  59494. this.volumetricLightSmoothYPostProcess.dispose(camera);
  59495. }
  59496. if (this.volumetricLightMergePostProces) {
  59497. this.volumetricLightMergePostProces.dispose(camera);
  59498. }
  59499. if (this.volumetricLightFinalPostProcess) {
  59500. this.volumetricLightFinalPostProcess.dispose(camera);
  59501. }
  59502. if (this.lensFlarePostProcess) {
  59503. this.lensFlarePostProcess.dispose(camera);
  59504. }
  59505. if (this.lensFlareComposePostProcess) {
  59506. this.lensFlareComposePostProcess.dispose(camera);
  59507. }
  59508. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  59509. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  59510. }
  59511. if (this.luminancePostProcess) {
  59512. this.luminancePostProcess.dispose(camera);
  59513. }
  59514. if (this.hdrPostProcess) {
  59515. this.hdrPostProcess.dispose(camera);
  59516. }
  59517. if (this.hdrFinalPostProcess) {
  59518. this.hdrFinalPostProcess.dispose(camera);
  59519. }
  59520. if (this.depthOfFieldPostProcess) {
  59521. this.depthOfFieldPostProcess.dispose(camera);
  59522. }
  59523. if (this.motionBlurPostProcess) {
  59524. this.motionBlurPostProcess.dispose(camera);
  59525. }
  59526. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  59527. this.blurHPostProcesses[j].dispose(camera);
  59528. }
  59529. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  59530. this.blurVPostProcesses[j].dispose(camera);
  59531. }
  59532. }
  59533. this.originalPostProcess = null;
  59534. this.downSampleX4PostProcess = null;
  59535. this.brightPassPostProcess = null;
  59536. this.textureAdderPostProcess = null;
  59537. this.textureAdderFinalPostProcess = null;
  59538. this.volumetricLightPostProcess = null;
  59539. this.volumetricLightSmoothXPostProcess = null;
  59540. this.volumetricLightSmoothYPostProcess = null;
  59541. this.volumetricLightMergePostProces = null;
  59542. this.volumetricLightFinalPostProcess = null;
  59543. this.lensFlarePostProcess = null;
  59544. this.lensFlareComposePostProcess = null;
  59545. this.luminancePostProcess = null;
  59546. this.hdrPostProcess = null;
  59547. this.hdrFinalPostProcess = null;
  59548. this.depthOfFieldPostProcess = null;
  59549. this.motionBlurPostProcess = null;
  59550. this.luminanceDownSamplePostProcesses = [];
  59551. this.blurHPostProcesses = [];
  59552. this.blurVPostProcesses = [];
  59553. };
  59554. // Dispose
  59555. StandardRenderingPipeline.prototype.dispose = function () {
  59556. this._disposePostProcesses();
  59557. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  59558. _super.prototype.dispose.call(this);
  59559. };
  59560. // Serialize rendering pipeline
  59561. StandardRenderingPipeline.prototype.serialize = function () {
  59562. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59563. serializationObject.customType = "StandardRenderingPipeline";
  59564. return serializationObject;
  59565. };
  59566. /**
  59567. * Static members
  59568. */
  59569. // Parse serialized pipeline
  59570. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  59571. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  59572. };
  59573. // Luminance steps
  59574. StandardRenderingPipeline.LuminanceSteps = 6;
  59575. __decorate([
  59576. BABYLON.serialize()
  59577. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  59578. __decorate([
  59579. BABYLON.serialize()
  59580. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  59581. __decorate([
  59582. BABYLON.serialize()
  59583. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  59584. __decorate([
  59585. BABYLON.serialize()
  59586. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  59587. __decorate([
  59588. BABYLON.serializeAsTexture("lensTexture")
  59589. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  59590. __decorate([
  59591. BABYLON.serialize()
  59592. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  59593. __decorate([
  59594. BABYLON.serialize()
  59595. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  59596. __decorate([
  59597. BABYLON.serialize()
  59598. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  59599. __decorate([
  59600. BABYLON.serialize()
  59601. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  59602. __decorate([
  59603. BABYLON.serialize()
  59604. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  59605. __decorate([
  59606. BABYLON.serialize()
  59607. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  59608. __decorate([
  59609. BABYLON.serializeAsTexture("lensColorTexture")
  59610. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  59611. __decorate([
  59612. BABYLON.serialize()
  59613. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  59614. __decorate([
  59615. BABYLON.serialize()
  59616. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  59617. __decorate([
  59618. BABYLON.serialize()
  59619. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  59620. __decorate([
  59621. BABYLON.serialize()
  59622. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  59623. __decorate([
  59624. BABYLON.serializeAsTexture("lensStarTexture")
  59625. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  59626. __decorate([
  59627. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  59628. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  59629. __decorate([
  59630. BABYLON.serialize()
  59631. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  59632. __decorate([
  59633. BABYLON.serialize()
  59634. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  59635. __decorate([
  59636. BABYLON.serialize()
  59637. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  59638. __decorate([
  59639. BABYLON.serialize()
  59640. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  59641. __decorate([
  59642. BABYLON.serialize()
  59643. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  59644. __decorate([
  59645. BABYLON.serialize()
  59646. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  59647. __decorate([
  59648. BABYLON.serialize()
  59649. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  59650. __decorate([
  59651. BABYLON.serialize()
  59652. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  59653. __decorate([
  59654. BABYLON.serialize()
  59655. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  59656. __decorate([
  59657. BABYLON.serialize()
  59658. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  59659. __decorate([
  59660. BABYLON.serialize()
  59661. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  59662. return StandardRenderingPipeline;
  59663. }(BABYLON.PostProcessRenderPipeline));
  59664. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  59665. })(BABYLON || (BABYLON = {}));
  59666. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  59667. var BABYLON;
  59668. (function (BABYLON) {
  59669. var FxaaPostProcess = /** @class */ (function (_super) {
  59670. __extends(FxaaPostProcess, _super);
  59671. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  59672. if (camera === void 0) { camera = null; }
  59673. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59674. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  59675. _this.onApplyObservable.add(function (effect) {
  59676. var texelSize = _this.texelSize;
  59677. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  59678. });
  59679. return _this;
  59680. }
  59681. return FxaaPostProcess;
  59682. }(BABYLON.PostProcess));
  59683. BABYLON.FxaaPostProcess = FxaaPostProcess;
  59684. })(BABYLON || (BABYLON = {}));
  59685. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  59686. var BABYLON;
  59687. (function (BABYLON) {
  59688. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  59689. __extends(DefaultRenderingPipeline, _super);
  59690. /**
  59691. * @constructor
  59692. * @param {string} name - The rendering pipeline name
  59693. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  59694. * @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)
  59695. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  59696. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  59697. */
  59698. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  59699. if (automaticBuild === void 0) { automaticBuild = true; }
  59700. var _this = _super.call(this, scene.getEngine(), name) || this;
  59701. _this.PassPostProcessId = "PassPostProcessEffect";
  59702. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  59703. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  59704. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  59705. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  59706. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  59707. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  59708. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  59709. // IAnimatable
  59710. _this.animations = [];
  59711. // Values
  59712. _this._bloomEnabled = false;
  59713. _this._fxaaEnabled = false;
  59714. _this._imageProcessingEnabled = true;
  59715. _this._bloomScale = 0.6;
  59716. _this._buildAllowed = true;
  59717. /**
  59718. * Specifies the size of the bloom blur kernel, relative to the final output size
  59719. */
  59720. _this.bloomKernel = 64;
  59721. /**
  59722. * Specifies the weight of the bloom in the final rendering
  59723. */
  59724. _this._bloomWeight = 0.15;
  59725. _this._cameras = cameras || [];
  59726. _this._buildAllowed = automaticBuild;
  59727. // Initialize
  59728. _this._scene = scene;
  59729. var caps = _this._scene.getEngine().getCaps();
  59730. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  59731. // Misc
  59732. if (_this._hdr) {
  59733. if (caps.textureHalfFloatRender) {
  59734. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59735. }
  59736. else if (caps.textureFloatRender) {
  59737. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  59738. }
  59739. }
  59740. else {
  59741. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  59742. }
  59743. // Attach
  59744. scene.postProcessRenderPipelineManager.addPipeline(_this);
  59745. _this._buildPipeline();
  59746. return _this;
  59747. }
  59748. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  59749. get: function () {
  59750. return this._bloomWeight;
  59751. },
  59752. set: function (value) {
  59753. if (this._bloomWeight === value) {
  59754. return;
  59755. }
  59756. this._bloomWeight = value;
  59757. if (this._hdr && this.copyBack) {
  59758. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  59759. }
  59760. },
  59761. enumerable: true,
  59762. configurable: true
  59763. });
  59764. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  59765. get: function () {
  59766. return this._bloomScale;
  59767. },
  59768. set: function (value) {
  59769. if (this._bloomScale === value) {
  59770. return;
  59771. }
  59772. this._bloomScale = value;
  59773. this._buildPipeline();
  59774. },
  59775. enumerable: true,
  59776. configurable: true
  59777. });
  59778. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  59779. get: function () {
  59780. return this._bloomEnabled;
  59781. },
  59782. set: function (enabled) {
  59783. if (this._bloomEnabled === enabled) {
  59784. return;
  59785. }
  59786. this._bloomEnabled = enabled;
  59787. this._buildPipeline();
  59788. },
  59789. enumerable: true,
  59790. configurable: true
  59791. });
  59792. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  59793. get: function () {
  59794. return this._fxaaEnabled;
  59795. },
  59796. set: function (enabled) {
  59797. if (this._fxaaEnabled === enabled) {
  59798. return;
  59799. }
  59800. this._fxaaEnabled = enabled;
  59801. this._buildPipeline();
  59802. },
  59803. enumerable: true,
  59804. configurable: true
  59805. });
  59806. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  59807. get: function () {
  59808. return this._imageProcessingEnabled;
  59809. },
  59810. set: function (enabled) {
  59811. if (this._imageProcessingEnabled === enabled) {
  59812. return;
  59813. }
  59814. this._imageProcessingEnabled = enabled;
  59815. this._buildPipeline();
  59816. },
  59817. enumerable: true,
  59818. configurable: true
  59819. });
  59820. /**
  59821. * Force the compilation of the entire pipeline.
  59822. */
  59823. DefaultRenderingPipeline.prototype.prepare = function () {
  59824. var previousState = this._buildAllowed;
  59825. this._buildAllowed = true;
  59826. this._buildPipeline();
  59827. this._buildAllowed = previousState;
  59828. };
  59829. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  59830. var _this = this;
  59831. if (!this._buildAllowed) {
  59832. return;
  59833. }
  59834. var engine = this._scene.getEngine();
  59835. this._disposePostProcesses();
  59836. this._reset();
  59837. if (this.bloomEnabled) {
  59838. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59839. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  59840. if (!this._hdr) {
  59841. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59842. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  59843. this.highlights.autoClear = false;
  59844. this.highlights.alwaysForcePOT = true;
  59845. }
  59846. 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);
  59847. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  59848. this.blurX.alwaysForcePOT = true;
  59849. this.blurX.autoClear = false;
  59850. this.blurX.onActivateObservable.add(function () {
  59851. var dw = _this.blurX.width / engine.getRenderWidth(true);
  59852. _this.blurX.kernel = _this.bloomKernel * dw;
  59853. });
  59854. 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);
  59855. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  59856. this.blurY.alwaysForcePOT = true;
  59857. this.blurY.autoClear = false;
  59858. this.blurY.onActivateObservable.add(function () {
  59859. var dh = _this.blurY.height / engine.getRenderHeight(true);
  59860. _this.blurY.kernel = _this.bloomKernel * dh;
  59861. });
  59862. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59863. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  59864. this.copyBack.alwaysForcePOT = true;
  59865. if (this._hdr) {
  59866. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  59867. var w = this.bloomWeight;
  59868. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  59869. }
  59870. else {
  59871. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  59872. }
  59873. this.copyBack.autoClear = false;
  59874. }
  59875. if (this._imageProcessingEnabled) {
  59876. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59877. if (this._hdr) {
  59878. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  59879. }
  59880. else {
  59881. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  59882. }
  59883. }
  59884. if (this.fxaaEnabled) {
  59885. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59886. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  59887. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  59888. }
  59889. else if (this._hdr && this.imageProcessing) {
  59890. this.finalMerge = this.imageProcessing;
  59891. }
  59892. else {
  59893. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59894. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  59895. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  59896. }
  59897. if (this.bloomEnabled) {
  59898. if (this._hdr) {
  59899. this.copyBack.shareOutputWith(this.blurX);
  59900. if (this.imageProcessing) {
  59901. this.imageProcessing.shareOutputWith(this.pass);
  59902. this.imageProcessing.autoClear = false;
  59903. }
  59904. else if (this.fxaa) {
  59905. this.fxaa.shareOutputWith(this.pass);
  59906. }
  59907. else {
  59908. this.finalMerge.shareOutputWith(this.pass);
  59909. }
  59910. }
  59911. else {
  59912. if (this.fxaa) {
  59913. this.fxaa.shareOutputWith(this.pass);
  59914. }
  59915. else {
  59916. this.finalMerge.shareOutputWith(this.pass);
  59917. }
  59918. }
  59919. }
  59920. if (this._cameras !== null) {
  59921. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  59922. }
  59923. };
  59924. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  59925. for (var i = 0; i < this._cameras.length; i++) {
  59926. var camera = this._cameras[i];
  59927. if (this.pass) {
  59928. this.pass.dispose(camera);
  59929. }
  59930. if (this.highlights) {
  59931. this.highlights.dispose(camera);
  59932. }
  59933. if (this.blurX) {
  59934. this.blurX.dispose(camera);
  59935. }
  59936. if (this.blurY) {
  59937. this.blurY.dispose(camera);
  59938. }
  59939. if (this.copyBack) {
  59940. this.copyBack.dispose(camera);
  59941. }
  59942. if (this.imageProcessing) {
  59943. this.imageProcessing.dispose(camera);
  59944. }
  59945. if (this.fxaa) {
  59946. this.fxaa.dispose(camera);
  59947. }
  59948. if (this.finalMerge) {
  59949. this.finalMerge.dispose(camera);
  59950. }
  59951. }
  59952. this.pass = null;
  59953. this.highlights = null;
  59954. this.blurX = null;
  59955. this.blurY = null;
  59956. this.copyBack = null;
  59957. this.imageProcessing = null;
  59958. this.fxaa = null;
  59959. this.finalMerge = null;
  59960. };
  59961. // Dispose
  59962. DefaultRenderingPipeline.prototype.dispose = function () {
  59963. this._disposePostProcesses();
  59964. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  59965. _super.prototype.dispose.call(this);
  59966. };
  59967. // Serialize rendering pipeline
  59968. DefaultRenderingPipeline.prototype.serialize = function () {
  59969. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59970. serializationObject.customType = "DefaultRenderingPipeline";
  59971. return serializationObject;
  59972. };
  59973. // Parse serialized pipeline
  59974. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  59975. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  59976. };
  59977. __decorate([
  59978. BABYLON.serialize()
  59979. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  59980. __decorate([
  59981. BABYLON.serialize()
  59982. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  59983. __decorate([
  59984. BABYLON.serialize()
  59985. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  59986. __decorate([
  59987. BABYLON.serialize()
  59988. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  59989. __decorate([
  59990. BABYLON.serialize()
  59991. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  59992. __decorate([
  59993. BABYLON.serialize()
  59994. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  59995. __decorate([
  59996. BABYLON.serialize()
  59997. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  59998. __decorate([
  59999. BABYLON.serialize()
  60000. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  60001. return DefaultRenderingPipeline;
  60002. }(BABYLON.PostProcessRenderPipeline));
  60003. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  60004. })(BABYLON || (BABYLON = {}));
  60005. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  60006. var BABYLON;
  60007. (function (BABYLON) {
  60008. var GeometryBufferRenderer = /** @class */ (function () {
  60009. function GeometryBufferRenderer(scene, ratio) {
  60010. if (ratio === void 0) { ratio = 1; }
  60011. this._enablePosition = false;
  60012. this._scene = scene;
  60013. this._ratio = ratio;
  60014. // Render target
  60015. this._createRenderTargets();
  60016. }
  60017. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  60018. set: function (meshes) {
  60019. this._multiRenderTarget.renderList = meshes;
  60020. },
  60021. enumerable: true,
  60022. configurable: true
  60023. });
  60024. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  60025. get: function () {
  60026. return this._multiRenderTarget.isSupported;
  60027. },
  60028. enumerable: true,
  60029. configurable: true
  60030. });
  60031. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  60032. get: function () {
  60033. return this._enablePosition;
  60034. },
  60035. set: function (enable) {
  60036. this._enablePosition = enable;
  60037. this.dispose();
  60038. this._createRenderTargets();
  60039. },
  60040. enumerable: true,
  60041. configurable: true
  60042. });
  60043. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  60044. var material = subMesh.getMaterial();
  60045. if (material && material.disableDepthWrite) {
  60046. return false;
  60047. }
  60048. var defines = [];
  60049. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  60050. var mesh = subMesh.getMesh();
  60051. // Alpha test
  60052. if (material && material.needAlphaTesting()) {
  60053. defines.push("#define ALPHATEST");
  60054. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60055. attribs.push(BABYLON.VertexBuffer.UVKind);
  60056. defines.push("#define UV1");
  60057. }
  60058. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60059. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60060. defines.push("#define UV2");
  60061. }
  60062. }
  60063. // Buffers
  60064. if (this._enablePosition) {
  60065. defines.push("#define POSITION");
  60066. }
  60067. // Bones
  60068. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60069. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60070. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60071. if (mesh.numBoneInfluencers > 4) {
  60072. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60073. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60074. }
  60075. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60076. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  60077. }
  60078. else {
  60079. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60080. }
  60081. // Instances
  60082. if (useInstances) {
  60083. defines.push("#define INSTANCES");
  60084. attribs.push("world0");
  60085. attribs.push("world1");
  60086. attribs.push("world2");
  60087. attribs.push("world3");
  60088. }
  60089. // Get correct effect
  60090. var join = defines.join("\n");
  60091. if (this._cachedDefines !== join) {
  60092. this._cachedDefines = join;
  60093. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  60094. }
  60095. return this._effect.isReady();
  60096. };
  60097. GeometryBufferRenderer.prototype.getGBuffer = function () {
  60098. return this._multiRenderTarget;
  60099. };
  60100. // Methods
  60101. GeometryBufferRenderer.prototype.dispose = function () {
  60102. this.getGBuffer().dispose();
  60103. };
  60104. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  60105. var _this = this;
  60106. var engine = this._scene.getEngine();
  60107. var count = this._enablePosition ? 3 : 2;
  60108. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  60109. if (!this.isSupported) {
  60110. return;
  60111. }
  60112. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60113. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60114. this._multiRenderTarget.refreshRate = 1;
  60115. this._multiRenderTarget.renderParticles = false;
  60116. this._multiRenderTarget.renderList = null;
  60117. // set default depth value to 1.0 (far away)
  60118. this._multiRenderTarget.onClearObservable.add(function (engine) {
  60119. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  60120. });
  60121. // Custom render function
  60122. var renderSubMesh = function (subMesh) {
  60123. var mesh = subMesh.getRenderingMesh();
  60124. var scene = _this._scene;
  60125. var engine = scene.getEngine();
  60126. var material = subMesh.getMaterial();
  60127. if (!material) {
  60128. return;
  60129. }
  60130. // Culling
  60131. engine.setState(material.backFaceCulling);
  60132. // Managing instances
  60133. var batch = mesh._getInstancesRenderList(subMesh._id);
  60134. if (batch.mustReturn) {
  60135. return;
  60136. }
  60137. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  60138. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  60139. engine.enableEffect(_this._effect);
  60140. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  60141. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  60142. _this._effect.setMatrix("view", scene.getViewMatrix());
  60143. // Alpha test
  60144. if (material && material.needAlphaTesting()) {
  60145. var alphaTexture = material.getAlphaTestTexture();
  60146. if (alphaTexture) {
  60147. _this._effect.setTexture("diffuseSampler", alphaTexture);
  60148. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  60149. }
  60150. }
  60151. // Bones
  60152. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  60153. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  60154. }
  60155. // Draw
  60156. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  60157. }
  60158. };
  60159. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  60160. var index;
  60161. if (depthOnlySubMeshes.length) {
  60162. engine.setColorWrite(false);
  60163. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  60164. renderSubMesh(depthOnlySubMeshes.data[index]);
  60165. }
  60166. engine.setColorWrite(true);
  60167. }
  60168. for (index = 0; index < opaqueSubMeshes.length; index++) {
  60169. renderSubMesh(opaqueSubMeshes.data[index]);
  60170. }
  60171. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  60172. renderSubMesh(alphaTestSubMeshes.data[index]);
  60173. }
  60174. };
  60175. };
  60176. return GeometryBufferRenderer;
  60177. }());
  60178. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  60179. })(BABYLON || (BABYLON = {}));
  60180. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  60181. var BABYLON;
  60182. (function (BABYLON) {
  60183. var RefractionPostProcess = /** @class */ (function (_super) {
  60184. __extends(RefractionPostProcess, _super);
  60185. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  60186. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  60187. _this.color = color;
  60188. _this.depth = depth;
  60189. _this.colorLevel = colorLevel;
  60190. _this.onActivateObservable.add(function (cam) {
  60191. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  60192. });
  60193. _this.onApplyObservable.add(function (effect) {
  60194. effect.setColor3("baseColor", _this.color);
  60195. effect.setFloat("depth", _this.depth);
  60196. effect.setFloat("colorLevel", _this.colorLevel);
  60197. effect.setTexture("refractionSampler", _this._refRexture);
  60198. });
  60199. return _this;
  60200. }
  60201. // Methods
  60202. RefractionPostProcess.prototype.dispose = function (camera) {
  60203. if (this._refRexture) {
  60204. this._refRexture.dispose();
  60205. }
  60206. _super.prototype.dispose.call(this, camera);
  60207. };
  60208. return RefractionPostProcess;
  60209. }(BABYLON.PostProcess));
  60210. BABYLON.RefractionPostProcess = RefractionPostProcess;
  60211. })(BABYLON || (BABYLON = {}));
  60212. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  60213. var BABYLON;
  60214. (function (BABYLON) {
  60215. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  60216. __extends(BlackAndWhitePostProcess, _super);
  60217. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  60218. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  60219. _this.degree = 1;
  60220. _this.onApplyObservable.add(function (effect) {
  60221. effect.setFloat("degree", _this.degree);
  60222. });
  60223. return _this;
  60224. }
  60225. return BlackAndWhitePostProcess;
  60226. }(BABYLON.PostProcess));
  60227. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  60228. })(BABYLON || (BABYLON = {}));
  60229. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  60230. var BABYLON;
  60231. (function (BABYLON) {
  60232. var ConvolutionPostProcess = /** @class */ (function (_super) {
  60233. __extends(ConvolutionPostProcess, _super);
  60234. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  60235. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  60236. _this.kernel = kernel;
  60237. _this.onApply = function (effect) {
  60238. effect.setFloat2("screenSize", _this.width, _this.height);
  60239. effect.setArray("kernel", _this.kernel);
  60240. };
  60241. return _this;
  60242. }
  60243. // Statics
  60244. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  60245. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  60246. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  60247. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  60248. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  60249. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  60250. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  60251. return ConvolutionPostProcess;
  60252. }(BABYLON.PostProcess));
  60253. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  60254. })(BABYLON || (BABYLON = {}));
  60255. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  60256. var BABYLON;
  60257. (function (BABYLON) {
  60258. var FilterPostProcess = /** @class */ (function (_super) {
  60259. __extends(FilterPostProcess, _super);
  60260. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  60261. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  60262. _this.kernelMatrix = kernelMatrix;
  60263. _this.onApply = function (effect) {
  60264. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  60265. };
  60266. return _this;
  60267. }
  60268. return FilterPostProcess;
  60269. }(BABYLON.PostProcess));
  60270. BABYLON.FilterPostProcess = FilterPostProcess;
  60271. })(BABYLON || (BABYLON = {}));
  60272. //# sourceMappingURL=babylon.filterPostProcess.js.map
  60273. var BABYLON;
  60274. (function (BABYLON) {
  60275. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  60276. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  60277. __extends(VolumetricLightScatteringPostProcess, _super);
  60278. /**
  60279. * @constructor
  60280. * @param {string} name - The post-process name
  60281. * @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)
  60282. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  60283. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  60284. * @param {number} samples - The post-process quality, default 100
  60285. * @param {number} samplingMode - The post-process filtering mode
  60286. * @param {BABYLON.Engine} engine - The babylon engine
  60287. * @param {boolean} reusable - If the post-process is reusable
  60288. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  60289. */
  60290. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  60291. if (samples === void 0) { samples = 100; }
  60292. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  60293. 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;
  60294. _this._screenCoordinates = BABYLON.Vector2.Zero();
  60295. /**
  60296. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  60297. * @type {Vector3}
  60298. */
  60299. _this.customMeshPosition = BABYLON.Vector3.Zero();
  60300. /**
  60301. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  60302. * @type {boolean}
  60303. */
  60304. _this.useCustomMeshPosition = false;
  60305. /**
  60306. * If the post-process should inverse the light scattering direction
  60307. * @type {boolean}
  60308. */
  60309. _this.invert = true;
  60310. /**
  60311. * Array containing the excluded meshes not rendered in the internal pass
  60312. */
  60313. _this.excludedMeshes = new Array();
  60314. /**
  60315. * Controls the overall intensity of the post-process
  60316. * @type {number}
  60317. */
  60318. _this.exposure = 0.3;
  60319. /**
  60320. * Dissipates each sample's contribution in range [0, 1]
  60321. * @type {number}
  60322. */
  60323. _this.decay = 0.96815;
  60324. /**
  60325. * Controls the overall intensity of each sample
  60326. * @type {number}
  60327. */
  60328. _this.weight = 0.58767;
  60329. /**
  60330. * Controls the density of each sample
  60331. * @type {number}
  60332. */
  60333. _this.density = 0.926;
  60334. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  60335. engine = scene.getEngine();
  60336. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  60337. // Configure mesh
  60338. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  60339. // Configure
  60340. _this._createPass(scene, ratio.passRatio || ratio);
  60341. _this.onActivate = function (camera) {
  60342. if (!_this.isSupported) {
  60343. _this.dispose(camera);
  60344. }
  60345. _this.onActivate = null;
  60346. };
  60347. _this.onApplyObservable.add(function (effect) {
  60348. _this._updateMeshScreenCoordinates(scene);
  60349. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  60350. effect.setFloat("exposure", _this.exposure);
  60351. effect.setFloat("decay", _this.decay);
  60352. effect.setFloat("weight", _this.weight);
  60353. effect.setFloat("density", _this.density);
  60354. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  60355. });
  60356. return _this;
  60357. }
  60358. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  60359. get: function () {
  60360. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  60361. return false;
  60362. },
  60363. set: function (useDiffuseColor) {
  60364. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  60365. },
  60366. enumerable: true,
  60367. configurable: true
  60368. });
  60369. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  60370. return "VolumetricLightScatteringPostProcess";
  60371. };
  60372. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  60373. var mesh = subMesh.getMesh();
  60374. // Render this.mesh as default
  60375. if (mesh === this.mesh && mesh.material) {
  60376. return mesh.material.isReady(mesh);
  60377. }
  60378. var defines = [];
  60379. var attribs = [BABYLON.VertexBuffer.PositionKind];
  60380. var material = subMesh.getMaterial();
  60381. // Alpha test
  60382. if (material) {
  60383. if (material.needAlphaTesting()) {
  60384. defines.push("#define ALPHATEST");
  60385. }
  60386. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60387. attribs.push(BABYLON.VertexBuffer.UVKind);
  60388. defines.push("#define UV1");
  60389. }
  60390. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60391. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60392. defines.push("#define UV2");
  60393. }
  60394. }
  60395. // Bones
  60396. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60397. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60398. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60399. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60400. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  60401. }
  60402. else {
  60403. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60404. }
  60405. // Instances
  60406. if (useInstances) {
  60407. defines.push("#define INSTANCES");
  60408. attribs.push("world0");
  60409. attribs.push("world1");
  60410. attribs.push("world2");
  60411. attribs.push("world3");
  60412. }
  60413. // Get correct effect
  60414. var join = defines.join("\n");
  60415. if (this._cachedDefines !== join) {
  60416. this._cachedDefines = join;
  60417. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  60418. }
  60419. return this._volumetricLightScatteringPass.isReady();
  60420. };
  60421. /**
  60422. * Sets the new light position for light scattering effect
  60423. * @param {BABYLON.Vector3} The new custom light position
  60424. */
  60425. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  60426. this.customMeshPosition = position;
  60427. };
  60428. /**
  60429. * Returns the light position for light scattering effect
  60430. * @return {BABYLON.Vector3} The custom light position
  60431. */
  60432. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  60433. return this.customMeshPosition;
  60434. };
  60435. /**
  60436. * Disposes the internal assets and detaches the post-process from the camera
  60437. */
  60438. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  60439. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  60440. if (rttIndex !== -1) {
  60441. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  60442. }
  60443. this._volumetricLightScatteringRTT.dispose();
  60444. _super.prototype.dispose.call(this, camera);
  60445. };
  60446. /**
  60447. * Returns the render target texture used by the post-process
  60448. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  60449. */
  60450. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  60451. return this._volumetricLightScatteringRTT;
  60452. };
  60453. // Private methods
  60454. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  60455. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  60456. return true;
  60457. }
  60458. return false;
  60459. };
  60460. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  60461. var _this = this;
  60462. var engine = scene.getEngine();
  60463. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  60464. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60465. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60466. this._volumetricLightScatteringRTT.renderList = null;
  60467. this._volumetricLightScatteringRTT.renderParticles = false;
  60468. var camera = this.getCamera();
  60469. if (camera) {
  60470. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  60471. }
  60472. else {
  60473. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  60474. }
  60475. // Custom render function for submeshes
  60476. var renderSubMesh = function (subMesh) {
  60477. var mesh = subMesh.getRenderingMesh();
  60478. if (_this._meshExcluded(mesh)) {
  60479. return;
  60480. }
  60481. var material = subMesh.getMaterial();
  60482. if (!material) {
  60483. return;
  60484. }
  60485. var scene = mesh.getScene();
  60486. var engine = scene.getEngine();
  60487. // Culling
  60488. engine.setState(material.backFaceCulling);
  60489. // Managing instances
  60490. var batch = mesh._getInstancesRenderList(subMesh._id);
  60491. if (batch.mustReturn) {
  60492. return;
  60493. }
  60494. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  60495. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  60496. var effect = _this._volumetricLightScatteringPass;
  60497. if (mesh === _this.mesh) {
  60498. if (subMesh.effect) {
  60499. effect = subMesh.effect;
  60500. }
  60501. else {
  60502. effect = material.getEffect();
  60503. }
  60504. }
  60505. engine.enableEffect(effect);
  60506. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  60507. if (mesh === _this.mesh) {
  60508. material.bind(mesh.getWorldMatrix(), mesh);
  60509. }
  60510. else {
  60511. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  60512. // Alpha test
  60513. if (material && material.needAlphaTesting()) {
  60514. var alphaTexture = material.getAlphaTestTexture();
  60515. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  60516. if (alphaTexture) {
  60517. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  60518. }
  60519. }
  60520. // Bones
  60521. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  60522. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  60523. }
  60524. }
  60525. // Draw
  60526. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  60527. }
  60528. };
  60529. // Render target texture callbacks
  60530. var savedSceneClearColor;
  60531. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  60532. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  60533. savedSceneClearColor = scene.clearColor;
  60534. scene.clearColor = sceneClearColor;
  60535. });
  60536. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  60537. scene.clearColor = savedSceneClearColor;
  60538. });
  60539. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  60540. var engine = scene.getEngine();
  60541. var index;
  60542. if (depthOnlySubMeshes.length) {
  60543. engine.setColorWrite(false);
  60544. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  60545. renderSubMesh(depthOnlySubMeshes.data[index]);
  60546. }
  60547. engine.setColorWrite(true);
  60548. }
  60549. for (index = 0; index < opaqueSubMeshes.length; index++) {
  60550. renderSubMesh(opaqueSubMeshes.data[index]);
  60551. }
  60552. engine.setAlphaTesting(true);
  60553. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  60554. renderSubMesh(alphaTestSubMeshes.data[index]);
  60555. }
  60556. engine.setAlphaTesting(false);
  60557. if (transparentSubMeshes.length) {
  60558. // Sort sub meshes
  60559. for (index = 0; index < transparentSubMeshes.length; index++) {
  60560. var submesh = transparentSubMeshes.data[index];
  60561. var boundingInfo = submesh.getBoundingInfo();
  60562. if (boundingInfo && scene.activeCamera) {
  60563. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  60564. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  60565. }
  60566. }
  60567. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  60568. sortedArray.sort(function (a, b) {
  60569. // Alpha index first
  60570. if (a._alphaIndex > b._alphaIndex) {
  60571. return 1;
  60572. }
  60573. if (a._alphaIndex < b._alphaIndex) {
  60574. return -1;
  60575. }
  60576. // Then distance to camera
  60577. if (a._distanceToCamera < b._distanceToCamera) {
  60578. return 1;
  60579. }
  60580. if (a._distanceToCamera > b._distanceToCamera) {
  60581. return -1;
  60582. }
  60583. return 0;
  60584. });
  60585. // Render sub meshes
  60586. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  60587. for (index = 0; index < sortedArray.length; index++) {
  60588. renderSubMesh(sortedArray[index]);
  60589. }
  60590. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  60591. }
  60592. };
  60593. };
  60594. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  60595. var transform = scene.getTransformMatrix();
  60596. var meshPosition;
  60597. if (this.useCustomMeshPosition) {
  60598. meshPosition = this.customMeshPosition;
  60599. }
  60600. else if (this.attachedNode) {
  60601. meshPosition = this.attachedNode.position;
  60602. }
  60603. else {
  60604. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  60605. }
  60606. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  60607. this._screenCoordinates.x = pos.x / this._viewPort.width;
  60608. this._screenCoordinates.y = pos.y / this._viewPort.height;
  60609. if (this.invert)
  60610. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  60611. };
  60612. // Static methods
  60613. /**
  60614. * Creates a default mesh for the Volumeric Light Scattering post-process
  60615. * @param {string} The mesh name
  60616. * @param {BABYLON.Scene} The scene where to create the mesh
  60617. * @return {BABYLON.Mesh} the default mesh
  60618. */
  60619. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  60620. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  60621. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  60622. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  60623. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  60624. mesh.material = material;
  60625. return mesh;
  60626. };
  60627. __decorate([
  60628. BABYLON.serializeAsVector3()
  60629. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  60630. __decorate([
  60631. BABYLON.serialize()
  60632. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  60633. __decorate([
  60634. BABYLON.serialize()
  60635. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  60636. __decorate([
  60637. BABYLON.serializeAsMeshReference()
  60638. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  60639. __decorate([
  60640. BABYLON.serialize()
  60641. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  60642. __decorate([
  60643. BABYLON.serialize()
  60644. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  60645. __decorate([
  60646. BABYLON.serialize()
  60647. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  60648. __decorate([
  60649. BABYLON.serialize()
  60650. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  60651. __decorate([
  60652. BABYLON.serialize()
  60653. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  60654. return VolumetricLightScatteringPostProcess;
  60655. }(BABYLON.PostProcess));
  60656. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  60657. })(BABYLON || (BABYLON = {}));
  60658. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  60659. //
  60660. // This post-process allows the modification of rendered colors by using
  60661. // a 'look-up table' (LUT). This effect is also called Color Grading.
  60662. //
  60663. // The object needs to be provided an url to a texture containing the color
  60664. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  60665. // Use an image editing software to tweak the LUT to match your needs.
  60666. //
  60667. // For an example of a color LUT, see here:
  60668. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  60669. // For explanations on color grading, see here:
  60670. // http://udn.epicgames.com/Three/ColorGrading.html
  60671. //
  60672. var BABYLON;
  60673. (function (BABYLON) {
  60674. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  60675. __extends(ColorCorrectionPostProcess, _super);
  60676. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  60677. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  60678. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  60679. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  60680. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60681. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60682. _this.onApply = function (effect) {
  60683. effect.setTexture("colorTable", _this._colorTableTexture);
  60684. };
  60685. return _this;
  60686. }
  60687. return ColorCorrectionPostProcess;
  60688. }(BABYLON.PostProcess));
  60689. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  60690. })(BABYLON || (BABYLON = {}));
  60691. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  60692. var BABYLON;
  60693. (function (BABYLON) {
  60694. var TonemappingOperator;
  60695. (function (TonemappingOperator) {
  60696. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  60697. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  60698. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  60699. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  60700. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  60701. ;
  60702. var TonemapPostProcess = /** @class */ (function (_super) {
  60703. __extends(TonemapPostProcess, _super);
  60704. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  60705. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  60706. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60707. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  60708. _this._operator = _operator;
  60709. _this.exposureAdjustment = exposureAdjustment;
  60710. var defines = "#define ";
  60711. if (_this._operator === TonemappingOperator.Hable)
  60712. defines += "HABLE_TONEMAPPING";
  60713. else if (_this._operator === TonemappingOperator.Reinhard)
  60714. defines += "REINHARD_TONEMAPPING";
  60715. else if (_this._operator === TonemappingOperator.HejiDawson)
  60716. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  60717. else if (_this._operator === TonemappingOperator.Photographic)
  60718. defines += "PHOTOGRAPHIC_TONEMAPPING";
  60719. //sadly a second call to create the effect.
  60720. _this.updateEffect(defines);
  60721. _this.onApply = function (effect) {
  60722. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  60723. };
  60724. return _this;
  60725. }
  60726. return TonemapPostProcess;
  60727. }(BABYLON.PostProcess));
  60728. BABYLON.TonemapPostProcess = TonemapPostProcess;
  60729. })(BABYLON || (BABYLON = {}));
  60730. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  60731. var BABYLON;
  60732. (function (BABYLON) {
  60733. var DisplayPassPostProcess = /** @class */ (function (_super) {
  60734. __extends(DisplayPassPostProcess, _super);
  60735. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  60736. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  60737. }
  60738. return DisplayPassPostProcess;
  60739. }(BABYLON.PostProcess));
  60740. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  60741. })(BABYLON || (BABYLON = {}));
  60742. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  60743. var BABYLON;
  60744. (function (BABYLON) {
  60745. var HighlightsPostProcess = /** @class */ (function (_super) {
  60746. __extends(HighlightsPostProcess, _super);
  60747. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  60748. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60749. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  60750. }
  60751. return HighlightsPostProcess;
  60752. }(BABYLON.PostProcess));
  60753. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  60754. })(BABYLON || (BABYLON = {}));
  60755. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  60756. var BABYLON;
  60757. (function (BABYLON) {
  60758. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  60759. __extends(ImageProcessingPostProcess, _super);
  60760. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  60761. if (camera === void 0) { camera = null; }
  60762. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60763. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  60764. _this._fromLinearSpace = true;
  60765. /**
  60766. * Defines cache preventing GC.
  60767. */
  60768. _this._defines = {
  60769. IMAGEPROCESSING: false,
  60770. VIGNETTE: false,
  60771. VIGNETTEBLENDMODEMULTIPLY: false,
  60772. VIGNETTEBLENDMODEOPAQUE: false,
  60773. TONEMAPPING: false,
  60774. CONTRAST: false,
  60775. COLORCURVES: false,
  60776. COLORGRADING: false,
  60777. COLORGRADING3D: false,
  60778. FROMLINEARSPACE: false,
  60779. SAMPLER3DGREENDEPTH: false,
  60780. SAMPLER3DBGRMAP: false,
  60781. IMAGEPROCESSINGPOSTPROCESS: false,
  60782. EXPOSURE: false,
  60783. };
  60784. // Setup the configuration as forced by the constructor. This would then not force the
  60785. // scene materials output in linear space and let untouched the default forward pass.
  60786. if (imageProcessingConfiguration) {
  60787. imageProcessingConfiguration.applyByPostProcess = true;
  60788. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  60789. // This will cause the shader to be compiled
  60790. _this.fromLinearSpace = false;
  60791. }
  60792. else {
  60793. _this._attachImageProcessingConfiguration(null, true);
  60794. _this.imageProcessingConfiguration.applyByPostProcess = true;
  60795. }
  60796. _this.onApply = function (effect) {
  60797. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  60798. };
  60799. return _this;
  60800. }
  60801. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  60802. /**
  60803. * Gets the image processing configuration used either in this material.
  60804. */
  60805. get: function () {
  60806. return this._imageProcessingConfiguration;
  60807. },
  60808. /**
  60809. * Sets the Default image processing configuration used either in the this material.
  60810. *
  60811. * If sets to null, the scene one is in use.
  60812. */
  60813. set: function (value) {
  60814. this._attachImageProcessingConfiguration(value);
  60815. },
  60816. enumerable: true,
  60817. configurable: true
  60818. });
  60819. /**
  60820. * Attaches a new image processing configuration to the PBR Material.
  60821. * @param configuration
  60822. */
  60823. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  60824. var _this = this;
  60825. if (doNotBuild === void 0) { doNotBuild = false; }
  60826. if (configuration === this._imageProcessingConfiguration) {
  60827. return;
  60828. }
  60829. // Detaches observer.
  60830. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  60831. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  60832. }
  60833. // Pick the scene configuration if needed.
  60834. if (!configuration) {
  60835. var scene = null;
  60836. var engine = this.getEngine();
  60837. var camera = this.getCamera();
  60838. if (camera) {
  60839. scene = camera.getScene();
  60840. }
  60841. else if (engine && engine.scenes) {
  60842. var scenes = engine.scenes;
  60843. scene = scenes[scenes.length - 1];
  60844. }
  60845. else {
  60846. scene = BABYLON.Engine.LastCreatedScene;
  60847. }
  60848. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  60849. }
  60850. else {
  60851. this._imageProcessingConfiguration = configuration;
  60852. }
  60853. // Attaches observer.
  60854. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  60855. _this._updateParameters();
  60856. });
  60857. // Ensure the effect will be rebuilt.
  60858. if (!doNotBuild) {
  60859. this._updateParameters();
  60860. }
  60861. };
  60862. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  60863. /**
  60864. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  60865. */
  60866. get: function () {
  60867. return this.imageProcessingConfiguration.colorCurves;
  60868. },
  60869. /**
  60870. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  60871. */
  60872. set: function (value) {
  60873. this.imageProcessingConfiguration.colorCurves = value;
  60874. },
  60875. enumerable: true,
  60876. configurable: true
  60877. });
  60878. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  60879. /**
  60880. * Gets wether the color curves effect is enabled.
  60881. */
  60882. get: function () {
  60883. return this.imageProcessingConfiguration.colorCurvesEnabled;
  60884. },
  60885. /**
  60886. * Sets wether the color curves effect is enabled.
  60887. */
  60888. set: function (value) {
  60889. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  60890. },
  60891. enumerable: true,
  60892. configurable: true
  60893. });
  60894. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  60895. /**
  60896. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  60897. */
  60898. get: function () {
  60899. return this.imageProcessingConfiguration.colorGradingTexture;
  60900. },
  60901. /**
  60902. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  60903. */
  60904. set: function (value) {
  60905. this.imageProcessingConfiguration.colorGradingTexture = value;
  60906. },
  60907. enumerable: true,
  60908. configurable: true
  60909. });
  60910. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  60911. /**
  60912. * Gets wether the color grading effect is enabled.
  60913. */
  60914. get: function () {
  60915. return this.imageProcessingConfiguration.colorGradingEnabled;
  60916. },
  60917. /**
  60918. * Gets wether the color grading effect is enabled.
  60919. */
  60920. set: function (value) {
  60921. this.imageProcessingConfiguration.colorGradingEnabled = value;
  60922. },
  60923. enumerable: true,
  60924. configurable: true
  60925. });
  60926. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  60927. /**
  60928. * Gets exposure used in the effect.
  60929. */
  60930. get: function () {
  60931. return this.imageProcessingConfiguration.exposure;
  60932. },
  60933. /**
  60934. * Sets exposure used in the effect.
  60935. */
  60936. set: function (value) {
  60937. this.imageProcessingConfiguration.exposure = value;
  60938. },
  60939. enumerable: true,
  60940. configurable: true
  60941. });
  60942. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  60943. /**
  60944. * Gets wether tonemapping is enabled or not.
  60945. */
  60946. get: function () {
  60947. return this._imageProcessingConfiguration.toneMappingEnabled;
  60948. },
  60949. /**
  60950. * Sets wether tonemapping is enabled or not
  60951. */
  60952. set: function (value) {
  60953. this._imageProcessingConfiguration.toneMappingEnabled = value;
  60954. },
  60955. enumerable: true,
  60956. configurable: true
  60957. });
  60958. ;
  60959. ;
  60960. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  60961. /**
  60962. * Gets contrast used in the effect.
  60963. */
  60964. get: function () {
  60965. return this.imageProcessingConfiguration.contrast;
  60966. },
  60967. /**
  60968. * Sets contrast used in the effect.
  60969. */
  60970. set: function (value) {
  60971. this.imageProcessingConfiguration.contrast = value;
  60972. },
  60973. enumerable: true,
  60974. configurable: true
  60975. });
  60976. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  60977. /**
  60978. * Gets Vignette stretch size.
  60979. */
  60980. get: function () {
  60981. return this.imageProcessingConfiguration.vignetteStretch;
  60982. },
  60983. /**
  60984. * Sets Vignette stretch size.
  60985. */
  60986. set: function (value) {
  60987. this.imageProcessingConfiguration.vignetteStretch = value;
  60988. },
  60989. enumerable: true,
  60990. configurable: true
  60991. });
  60992. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  60993. /**
  60994. * Gets Vignette centre X Offset.
  60995. */
  60996. get: function () {
  60997. return this.imageProcessingConfiguration.vignetteCentreX;
  60998. },
  60999. /**
  61000. * Sets Vignette centre X Offset.
  61001. */
  61002. set: function (value) {
  61003. this.imageProcessingConfiguration.vignetteCentreX = value;
  61004. },
  61005. enumerable: true,
  61006. configurable: true
  61007. });
  61008. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  61009. /**
  61010. * Gets Vignette centre Y Offset.
  61011. */
  61012. get: function () {
  61013. return this.imageProcessingConfiguration.vignetteCentreY;
  61014. },
  61015. /**
  61016. * Sets Vignette centre Y Offset.
  61017. */
  61018. set: function (value) {
  61019. this.imageProcessingConfiguration.vignetteCentreY = value;
  61020. },
  61021. enumerable: true,
  61022. configurable: true
  61023. });
  61024. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  61025. /**
  61026. * Gets Vignette weight or intensity of the vignette effect.
  61027. */
  61028. get: function () {
  61029. return this.imageProcessingConfiguration.vignetteWeight;
  61030. },
  61031. /**
  61032. * Sets Vignette weight or intensity of the vignette effect.
  61033. */
  61034. set: function (value) {
  61035. this.imageProcessingConfiguration.vignetteWeight = value;
  61036. },
  61037. enumerable: true,
  61038. configurable: true
  61039. });
  61040. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  61041. /**
  61042. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  61043. * if vignetteEnabled is set to true.
  61044. */
  61045. get: function () {
  61046. return this.imageProcessingConfiguration.vignetteColor;
  61047. },
  61048. /**
  61049. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  61050. * if vignetteEnabled is set to true.
  61051. */
  61052. set: function (value) {
  61053. this.imageProcessingConfiguration.vignetteColor = value;
  61054. },
  61055. enumerable: true,
  61056. configurable: true
  61057. });
  61058. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  61059. /**
  61060. * Gets Camera field of view used by the Vignette effect.
  61061. */
  61062. get: function () {
  61063. return this.imageProcessingConfiguration.vignetteCameraFov;
  61064. },
  61065. /**
  61066. * Sets Camera field of view used by the Vignette effect.
  61067. */
  61068. set: function (value) {
  61069. this.imageProcessingConfiguration.vignetteCameraFov = value;
  61070. },
  61071. enumerable: true,
  61072. configurable: true
  61073. });
  61074. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  61075. /**
  61076. * Gets the vignette blend mode allowing different kind of effect.
  61077. */
  61078. get: function () {
  61079. return this.imageProcessingConfiguration.vignetteBlendMode;
  61080. },
  61081. /**
  61082. * Sets the vignette blend mode allowing different kind of effect.
  61083. */
  61084. set: function (value) {
  61085. this.imageProcessingConfiguration.vignetteBlendMode = value;
  61086. },
  61087. enumerable: true,
  61088. configurable: true
  61089. });
  61090. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  61091. /**
  61092. * Gets wether the vignette effect is enabled.
  61093. */
  61094. get: function () {
  61095. return this.imageProcessingConfiguration.vignetteEnabled;
  61096. },
  61097. /**
  61098. * Sets wether the vignette effect is enabled.
  61099. */
  61100. set: function (value) {
  61101. this.imageProcessingConfiguration.vignetteEnabled = value;
  61102. },
  61103. enumerable: true,
  61104. configurable: true
  61105. });
  61106. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  61107. /**
  61108. * Gets wether the input of the processing is in Gamma or Linear Space.
  61109. */
  61110. get: function () {
  61111. return this._fromLinearSpace;
  61112. },
  61113. /**
  61114. * Sets wether the input of the processing is in Gamma or Linear Space.
  61115. */
  61116. set: function (value) {
  61117. if (this._fromLinearSpace === value) {
  61118. return;
  61119. }
  61120. this._fromLinearSpace = value;
  61121. this._updateParameters();
  61122. },
  61123. enumerable: true,
  61124. configurable: true
  61125. });
  61126. ImageProcessingPostProcess.prototype.getClassName = function () {
  61127. return "ImageProcessingPostProcess";
  61128. };
  61129. ImageProcessingPostProcess.prototype._updateParameters = function () {
  61130. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  61131. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  61132. var defines = "";
  61133. for (var define in this._defines) {
  61134. if (this._defines[define]) {
  61135. defines += "#define " + define + ";\r\n";
  61136. }
  61137. }
  61138. var samplers = ["textureSampler"];
  61139. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  61140. var uniforms = ["scale"];
  61141. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  61142. this.updateEffect(defines, uniforms, samplers);
  61143. };
  61144. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  61145. _super.prototype.dispose.call(this, camera);
  61146. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  61147. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  61148. }
  61149. this.imageProcessingConfiguration.applyByPostProcess = false;
  61150. };
  61151. __decorate([
  61152. BABYLON.serialize()
  61153. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  61154. return ImageProcessingPostProcess;
  61155. }(BABYLON.PostProcess));
  61156. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  61157. })(BABYLON || (BABYLON = {}));
  61158. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  61159. var BABYLON;
  61160. (function (BABYLON) {
  61161. var BlurPostProcess = /** @class */ (function (_super) {
  61162. __extends(BlurPostProcess, _super);
  61163. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  61164. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  61165. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61166. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  61167. _this.direction = direction;
  61168. _this._packedFloat = false;
  61169. _this.onApplyObservable.add(function (effect) {
  61170. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  61171. });
  61172. _this.kernel = kernel;
  61173. return _this;
  61174. }
  61175. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  61176. /**
  61177. * Gets the length in pixels of the blur sample region
  61178. */
  61179. get: function () {
  61180. return this._idealKernel;
  61181. },
  61182. /**
  61183. * Sets the length in pixels of the blur sample region
  61184. */
  61185. set: function (v) {
  61186. if (this._idealKernel === v) {
  61187. return;
  61188. }
  61189. v = Math.max(v, 1);
  61190. this._idealKernel = v;
  61191. this._kernel = this._nearestBestKernel(v);
  61192. this._updateParameters();
  61193. },
  61194. enumerable: true,
  61195. configurable: true
  61196. });
  61197. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  61198. /**
  61199. * Gets wether or not the blur is unpacking/repacking floats
  61200. */
  61201. get: function () {
  61202. return this._packedFloat;
  61203. },
  61204. /**
  61205. * Sets wether or not the blur needs to unpack/repack floats
  61206. */
  61207. set: function (v) {
  61208. if (this._packedFloat === v) {
  61209. return;
  61210. }
  61211. this._packedFloat = v;
  61212. this._updateParameters();
  61213. },
  61214. enumerable: true,
  61215. configurable: true
  61216. });
  61217. BlurPostProcess.prototype._updateParameters = function () {
  61218. // Generate sampling offsets and weights
  61219. var N = this._kernel;
  61220. var centerIndex = (N - 1) / 2;
  61221. // Generate Gaussian sampling weights over kernel
  61222. var offsets = [];
  61223. var weights = [];
  61224. var totalWeight = 0;
  61225. for (var i = 0; i < N; i++) {
  61226. var u = i / (N - 1);
  61227. var w = this._gaussianWeight(u * 2.0 - 1);
  61228. offsets[i] = (i - centerIndex);
  61229. weights[i] = w;
  61230. totalWeight += w;
  61231. }
  61232. // Normalize weights
  61233. for (var i = 0; i < weights.length; i++) {
  61234. weights[i] /= totalWeight;
  61235. }
  61236. // Optimize: combine samples to take advantage of hardware linear sampling
  61237. // Walk from left to center, combining pairs (symmetrically)
  61238. var linearSamplingWeights = [];
  61239. var linearSamplingOffsets = [];
  61240. var linearSamplingMap = [];
  61241. for (var i = 0; i <= centerIndex; i += 2) {
  61242. var j = Math.min(i + 1, Math.floor(centerIndex));
  61243. var singleCenterSample = i === j;
  61244. if (singleCenterSample) {
  61245. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  61246. }
  61247. else {
  61248. var sharedCell = j === centerIndex;
  61249. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  61250. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  61251. if (offsetLinear === 0) {
  61252. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  61253. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  61254. }
  61255. else {
  61256. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  61257. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  61258. }
  61259. }
  61260. }
  61261. for (var i = 0; i < linearSamplingMap.length; i++) {
  61262. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  61263. linearSamplingWeights[i] = linearSamplingMap[i].w;
  61264. }
  61265. // Replace with optimized
  61266. offsets = linearSamplingOffsets;
  61267. weights = linearSamplingWeights;
  61268. // Generate shaders
  61269. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  61270. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  61271. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  61272. var defines = "";
  61273. for (var i = 0; i < varyingCount; i++) {
  61274. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  61275. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  61276. }
  61277. var depCount = 0;
  61278. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  61279. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  61280. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  61281. depCount++;
  61282. }
  61283. if (this.packedFloat) {
  61284. defines += "#define PACKEDFLOAT 1";
  61285. }
  61286. this.updateEffect(defines, null, null, {
  61287. varyingCount: varyingCount,
  61288. depCount: depCount
  61289. });
  61290. };
  61291. /**
  61292. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  61293. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  61294. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  61295. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  61296. * The gaps between physical kernels are compensated for in the weighting of the samples
  61297. * @param idealKernel Ideal blur kernel.
  61298. * @return Nearest best kernel.
  61299. */
  61300. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  61301. var v = Math.round(idealKernel);
  61302. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  61303. var k = _a[_i];
  61304. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  61305. return Math.max(k, 3);
  61306. }
  61307. }
  61308. return Math.max(v, 3);
  61309. };
  61310. /**
  61311. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  61312. * @param x The point on the Gaussian distribution to sample.
  61313. * @return the value of the Gaussian function at x.
  61314. */
  61315. BlurPostProcess.prototype._gaussianWeight = function (x) {
  61316. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  61317. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  61318. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  61319. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  61320. // truncated at around 1.3% of peak strength.
  61321. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  61322. var sigma = (1 / 3);
  61323. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  61324. var exponent = -((x * x) / (2.0 * sigma * sigma));
  61325. var weight = (1.0 / denominator) * Math.exp(exponent);
  61326. return weight;
  61327. };
  61328. /**
  61329. * Generates a string that can be used as a floating point number in GLSL.
  61330. * @param x Value to print.
  61331. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  61332. * @return GLSL float string.
  61333. */
  61334. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  61335. if (decimalFigures === void 0) { decimalFigures = 8; }
  61336. return x.toFixed(decimalFigures).replace(/0+$/, '');
  61337. };
  61338. return BlurPostProcess;
  61339. }(BABYLON.PostProcess));
  61340. BABYLON.BlurPostProcess = BlurPostProcess;
  61341. })(BABYLON || (BABYLON = {}));
  61342. //# sourceMappingURL=babylon.blurPostProcess.js.map
  61343. var BABYLON;
  61344. (function (BABYLON) {
  61345. var Bone = /** @class */ (function (_super) {
  61346. __extends(Bone, _super);
  61347. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  61348. if (parentBone === void 0) { parentBone = null; }
  61349. if (localMatrix === void 0) { localMatrix = null; }
  61350. if (restPose === void 0) { restPose = null; }
  61351. if (baseMatrix === void 0) { baseMatrix = null; }
  61352. if (index === void 0) { index = null; }
  61353. var _this = _super.call(this, name, skeleton.getScene()) || this;
  61354. _this.name = name;
  61355. _this.children = new Array();
  61356. _this.animations = new Array();
  61357. // Set this value to map this bone to a different index in the transform matrices.
  61358. // Set this value to -1 to exclude the bone from the transform matrices.
  61359. _this._index = null;
  61360. _this._worldTransform = new BABYLON.Matrix();
  61361. _this._absoluteTransform = new BABYLON.Matrix();
  61362. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  61363. _this._scaleMatrix = BABYLON.Matrix.Identity();
  61364. _this._scaleVector = BABYLON.Vector3.One();
  61365. _this._negateScaleChildren = BABYLON.Vector3.One();
  61366. _this._scalingDeterminant = 1;
  61367. _this._skeleton = skeleton;
  61368. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  61369. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  61370. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  61371. _this._index = index;
  61372. skeleton.bones.push(_this);
  61373. _this.setParent(parentBone, false);
  61374. _this._updateDifferenceMatrix();
  61375. return _this;
  61376. }
  61377. Object.defineProperty(Bone.prototype, "_matrix", {
  61378. get: function () {
  61379. return this._localMatrix;
  61380. },
  61381. set: function (val) {
  61382. if (this._localMatrix) {
  61383. this._localMatrix.copyFrom(val);
  61384. }
  61385. else {
  61386. this._localMatrix = val;
  61387. }
  61388. },
  61389. enumerable: true,
  61390. configurable: true
  61391. });
  61392. // Members
  61393. Bone.prototype.getSkeleton = function () {
  61394. return this._skeleton;
  61395. };
  61396. Bone.prototype.getParent = function () {
  61397. return this._parent;
  61398. };
  61399. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  61400. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  61401. if (this._parent === parent) {
  61402. return;
  61403. }
  61404. if (this._parent) {
  61405. var index = this._parent.children.indexOf(this);
  61406. if (index !== -1) {
  61407. this._parent.children.splice(index, 1);
  61408. }
  61409. }
  61410. this._parent = parent;
  61411. if (this._parent) {
  61412. this._parent.children.push(this);
  61413. }
  61414. if (updateDifferenceMatrix) {
  61415. this._updateDifferenceMatrix();
  61416. }
  61417. };
  61418. Bone.prototype.getLocalMatrix = function () {
  61419. return this._localMatrix;
  61420. };
  61421. Bone.prototype.getBaseMatrix = function () {
  61422. return this._baseMatrix;
  61423. };
  61424. Bone.prototype.getRestPose = function () {
  61425. return this._restPose;
  61426. };
  61427. Bone.prototype.returnToRest = function () {
  61428. this.updateMatrix(this._restPose.clone());
  61429. };
  61430. Bone.prototype.getWorldMatrix = function () {
  61431. return this._worldTransform;
  61432. };
  61433. Bone.prototype.getInvertedAbsoluteTransform = function () {
  61434. return this._invertedAbsoluteTransform;
  61435. };
  61436. Bone.prototype.getAbsoluteTransform = function () {
  61437. return this._absoluteTransform;
  61438. };
  61439. Object.defineProperty(Bone.prototype, "position", {
  61440. // Properties (matches AbstractMesh properties)
  61441. get: function () {
  61442. return this.getPosition();
  61443. },
  61444. set: function (newPosition) {
  61445. this.setPosition(newPosition);
  61446. },
  61447. enumerable: true,
  61448. configurable: true
  61449. });
  61450. Object.defineProperty(Bone.prototype, "rotation", {
  61451. get: function () {
  61452. return this.getRotation();
  61453. },
  61454. set: function (newRotation) {
  61455. this.setRotation(newRotation);
  61456. },
  61457. enumerable: true,
  61458. configurable: true
  61459. });
  61460. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  61461. get: function () {
  61462. return this.getRotationQuaternion();
  61463. },
  61464. set: function (newRotation) {
  61465. this.setRotationQuaternion(newRotation);
  61466. },
  61467. enumerable: true,
  61468. configurable: true
  61469. });
  61470. Object.defineProperty(Bone.prototype, "scaling", {
  61471. get: function () {
  61472. return this.getScale();
  61473. },
  61474. set: function (newScaling) {
  61475. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  61476. },
  61477. enumerable: true,
  61478. configurable: true
  61479. });
  61480. // Methods
  61481. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  61482. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  61483. this._baseMatrix = matrix.clone();
  61484. this._localMatrix = matrix.clone();
  61485. this._skeleton._markAsDirty();
  61486. if (updateDifferenceMatrix) {
  61487. this._updateDifferenceMatrix();
  61488. }
  61489. };
  61490. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  61491. if (!rootMatrix) {
  61492. rootMatrix = this._baseMatrix;
  61493. }
  61494. if (this._parent) {
  61495. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  61496. }
  61497. else {
  61498. this._absoluteTransform.copyFrom(rootMatrix);
  61499. }
  61500. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  61501. for (var index = 0; index < this.children.length; index++) {
  61502. this.children[index]._updateDifferenceMatrix();
  61503. }
  61504. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  61505. };
  61506. Bone.prototype.markAsDirty = function () {
  61507. this._currentRenderId++;
  61508. this._skeleton._markAsDirty();
  61509. };
  61510. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  61511. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  61512. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  61513. // all animation may be coming from a library skeleton, so may need to create animation
  61514. if (this.animations.length === 0) {
  61515. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  61516. this.animations[0].setKeys([]);
  61517. }
  61518. // get animation info / verify there is such a range from the source bone
  61519. var sourceRange = source.animations[0].getRange(rangeName);
  61520. if (!sourceRange) {
  61521. return false;
  61522. }
  61523. var from = sourceRange.from;
  61524. var to = sourceRange.to;
  61525. var sourceKeys = source.animations[0].getKeys();
  61526. // rescaling prep
  61527. var sourceBoneLength = source.length;
  61528. var sourceParent = source.getParent();
  61529. var parent = this.getParent();
  61530. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  61531. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  61532. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  61533. var destKeys = this.animations[0].getKeys();
  61534. // loop vars declaration
  61535. var orig;
  61536. var origTranslation;
  61537. var mat;
  61538. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  61539. orig = sourceKeys[key];
  61540. if (orig.frame >= from && orig.frame <= to) {
  61541. if (rescaleAsRequired) {
  61542. mat = orig.value.clone();
  61543. // scale based on parent ratio, when bone has parent
  61544. if (parentScalingReqd) {
  61545. origTranslation = mat.getTranslation();
  61546. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  61547. // scale based on skeleton dimension ratio when root bone, and value is passed
  61548. }
  61549. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  61550. origTranslation = mat.getTranslation();
  61551. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  61552. // use original when root bone, and no data for skelDimensionsRatio
  61553. }
  61554. else {
  61555. mat = orig.value;
  61556. }
  61557. }
  61558. else {
  61559. mat = orig.value;
  61560. }
  61561. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  61562. }
  61563. }
  61564. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  61565. return true;
  61566. };
  61567. /**
  61568. * Translate the bone in local or world space.
  61569. * @param vec The amount to translate the bone.
  61570. * @param space The space that the translation is in.
  61571. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61572. */
  61573. Bone.prototype.translate = function (vec, space, mesh) {
  61574. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61575. var lm = this.getLocalMatrix();
  61576. if (space == BABYLON.Space.LOCAL) {
  61577. lm.m[12] += vec.x;
  61578. lm.m[13] += vec.y;
  61579. lm.m[14] += vec.z;
  61580. }
  61581. else {
  61582. var wm = null;
  61583. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61584. if (mesh) {
  61585. wm = mesh.getWorldMatrix();
  61586. }
  61587. this._skeleton.computeAbsoluteTransforms();
  61588. var tmat = Bone._tmpMats[0];
  61589. var tvec = Bone._tmpVecs[0];
  61590. if (this._parent) {
  61591. if (mesh && wm) {
  61592. tmat.copyFrom(this._parent.getAbsoluteTransform());
  61593. tmat.multiplyToRef(wm, tmat);
  61594. }
  61595. else {
  61596. tmat.copyFrom(this._parent.getAbsoluteTransform());
  61597. }
  61598. }
  61599. tmat.m[12] = 0;
  61600. tmat.m[13] = 0;
  61601. tmat.m[14] = 0;
  61602. tmat.invert();
  61603. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  61604. lm.m[12] += tvec.x;
  61605. lm.m[13] += tvec.y;
  61606. lm.m[14] += tvec.z;
  61607. }
  61608. this.markAsDirty();
  61609. };
  61610. /**
  61611. * Set the postion of the bone in local or world space.
  61612. * @param position The position to set the bone.
  61613. * @param space The space that the position is in.
  61614. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61615. */
  61616. Bone.prototype.setPosition = function (position, space, mesh) {
  61617. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61618. var lm = this.getLocalMatrix();
  61619. if (space == BABYLON.Space.LOCAL) {
  61620. lm.m[12] = position.x;
  61621. lm.m[13] = position.y;
  61622. lm.m[14] = position.z;
  61623. }
  61624. else {
  61625. var wm = null;
  61626. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61627. if (mesh) {
  61628. wm = mesh.getWorldMatrix();
  61629. }
  61630. this._skeleton.computeAbsoluteTransforms();
  61631. var tmat = Bone._tmpMats[0];
  61632. var vec = Bone._tmpVecs[0];
  61633. if (this._parent) {
  61634. if (mesh && wm) {
  61635. tmat.copyFrom(this._parent.getAbsoluteTransform());
  61636. tmat.multiplyToRef(wm, tmat);
  61637. }
  61638. else {
  61639. tmat.copyFrom(this._parent.getAbsoluteTransform());
  61640. }
  61641. }
  61642. tmat.invert();
  61643. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  61644. lm.m[12] = vec.x;
  61645. lm.m[13] = vec.y;
  61646. lm.m[14] = vec.z;
  61647. }
  61648. this.markAsDirty();
  61649. };
  61650. /**
  61651. * Set the absolute postion of the bone (world space).
  61652. * @param position The position to set the bone.
  61653. * @param mesh The mesh that this bone is attached to.
  61654. */
  61655. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  61656. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  61657. };
  61658. /**
  61659. * Set the scale of the bone on the x, y and z axes.
  61660. * @param x The scale of the bone on the x axis.
  61661. * @param x The scale of the bone on the y axis.
  61662. * @param z The scale of the bone on the z axis.
  61663. * @param scaleChildren Set this to true if children of the bone should be scaled.
  61664. */
  61665. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  61666. if (scaleChildren === void 0) { scaleChildren = false; }
  61667. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  61668. if (!scaleChildren) {
  61669. this._negateScaleChildren.x = 1 / x;
  61670. this._negateScaleChildren.y = 1 / y;
  61671. this._negateScaleChildren.z = 1 / z;
  61672. }
  61673. this._syncScaleVector();
  61674. }
  61675. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  61676. };
  61677. /**
  61678. * Scale the bone on the x, y and z axes.
  61679. * @param x The amount to scale the bone on the x axis.
  61680. * @param x The amount to scale the bone on the y axis.
  61681. * @param z The amount to scale the bone on the z axis.
  61682. * @param scaleChildren Set this to true if children of the bone should be scaled.
  61683. */
  61684. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  61685. if (scaleChildren === void 0) { scaleChildren = false; }
  61686. var locMat = this.getLocalMatrix();
  61687. var origLocMat = Bone._tmpMats[0];
  61688. origLocMat.copyFrom(locMat);
  61689. var origLocMatInv = Bone._tmpMats[1];
  61690. origLocMatInv.copyFrom(origLocMat);
  61691. origLocMatInv.invert();
  61692. var scaleMat = Bone._tmpMats[2];
  61693. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  61694. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  61695. this._scaleVector.x *= x;
  61696. this._scaleVector.y *= y;
  61697. this._scaleVector.z *= z;
  61698. locMat.multiplyToRef(origLocMatInv, locMat);
  61699. locMat.multiplyToRef(scaleMat, locMat);
  61700. locMat.multiplyToRef(origLocMat, locMat);
  61701. var parent = this.getParent();
  61702. if (parent) {
  61703. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  61704. }
  61705. else {
  61706. this.getAbsoluteTransform().copyFrom(locMat);
  61707. }
  61708. var len = this.children.length;
  61709. scaleMat.invert();
  61710. for (var i = 0; i < len; i++) {
  61711. var child = this.children[i];
  61712. var cm = child.getLocalMatrix();
  61713. cm.multiplyToRef(scaleMat, cm);
  61714. var lm = child.getLocalMatrix();
  61715. lm.m[12] *= x;
  61716. lm.m[13] *= y;
  61717. lm.m[14] *= z;
  61718. }
  61719. this.computeAbsoluteTransforms();
  61720. if (scaleChildren) {
  61721. for (var i = 0; i < len; i++) {
  61722. this.children[i].scale(x, y, z, scaleChildren);
  61723. }
  61724. }
  61725. this.markAsDirty();
  61726. };
  61727. /**
  61728. * Set the yaw, pitch, and roll of the bone in local or world space.
  61729. * @param yaw The rotation of the bone on the y axis.
  61730. * @param pitch The rotation of the bone on the x axis.
  61731. * @param roll The rotation of the bone on the z axis.
  61732. * @param space The space that the axes of rotation are in.
  61733. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61734. */
  61735. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  61736. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61737. var rotMat = Bone._tmpMats[0];
  61738. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  61739. var rotMatInv = Bone._tmpMats[1];
  61740. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  61741. rotMatInv.multiplyToRef(rotMat, rotMat);
  61742. this._rotateWithMatrix(rotMat, space, mesh);
  61743. };
  61744. /**
  61745. * Rotate the bone on an axis in local or world space.
  61746. * @param axis The axis to rotate the bone on.
  61747. * @param amount The amount to rotate the bone.
  61748. * @param space The space that the axis is in.
  61749. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61750. */
  61751. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  61752. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61753. var rmat = Bone._tmpMats[0];
  61754. rmat.m[12] = 0;
  61755. rmat.m[13] = 0;
  61756. rmat.m[14] = 0;
  61757. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  61758. this._rotateWithMatrix(rmat, space, mesh);
  61759. };
  61760. /**
  61761. * Set the rotation of the bone to a particular axis angle in local or world space.
  61762. * @param axis The axis to rotate the bone on.
  61763. * @param angle The angle that the bone should be rotated to.
  61764. * @param space The space that the axis is in.
  61765. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61766. */
  61767. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  61768. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61769. var rotMat = Bone._tmpMats[0];
  61770. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  61771. var rotMatInv = Bone._tmpMats[1];
  61772. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  61773. rotMatInv.multiplyToRef(rotMat, rotMat);
  61774. this._rotateWithMatrix(rotMat, space, mesh);
  61775. };
  61776. /**
  61777. * Set the euler rotation of the bone in local of world space.
  61778. * @param rotation The euler rotation that the bone should be set to.
  61779. * @param space The space that the rotation is in.
  61780. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61781. */
  61782. Bone.prototype.setRotation = function (rotation, space, mesh) {
  61783. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61784. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  61785. };
  61786. /**
  61787. * Set the quaternion rotation of the bone in local of world space.
  61788. * @param quat The quaternion rotation that the bone should be set to.
  61789. * @param space The space that the rotation is in.
  61790. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61791. */
  61792. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  61793. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61794. var rotMatInv = Bone._tmpMats[0];
  61795. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  61796. var rotMat = Bone._tmpMats[1];
  61797. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  61798. rotMatInv.multiplyToRef(rotMat, rotMat);
  61799. this._rotateWithMatrix(rotMat, space, mesh);
  61800. };
  61801. /**
  61802. * Set the rotation matrix of the bone in local of world space.
  61803. * @param rotMat The rotation matrix that the bone should be set to.
  61804. * @param space The space that the rotation is in.
  61805. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61806. */
  61807. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  61808. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61809. var rotMatInv = Bone._tmpMats[0];
  61810. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  61811. var rotMat2 = Bone._tmpMats[1];
  61812. rotMat2.copyFrom(rotMat);
  61813. rotMatInv.multiplyToRef(rotMat, rotMat2);
  61814. this._rotateWithMatrix(rotMat2, space, mesh);
  61815. };
  61816. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  61817. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61818. var lmat = this.getLocalMatrix();
  61819. var lx = lmat.m[12];
  61820. var ly = lmat.m[13];
  61821. var lz = lmat.m[14];
  61822. var parent = this.getParent();
  61823. var parentScale = Bone._tmpMats[3];
  61824. var parentScaleInv = Bone._tmpMats[4];
  61825. if (parent) {
  61826. if (space == BABYLON.Space.WORLD) {
  61827. if (mesh) {
  61828. parentScale.copyFrom(mesh.getWorldMatrix());
  61829. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  61830. }
  61831. else {
  61832. parentScale.copyFrom(parent.getAbsoluteTransform());
  61833. }
  61834. }
  61835. else {
  61836. parentScale = parent._scaleMatrix;
  61837. }
  61838. parentScaleInv.copyFrom(parentScale);
  61839. parentScaleInv.invert();
  61840. lmat.multiplyToRef(parentScale, lmat);
  61841. lmat.multiplyToRef(rmat, lmat);
  61842. lmat.multiplyToRef(parentScaleInv, lmat);
  61843. }
  61844. else {
  61845. if (space == BABYLON.Space.WORLD && mesh) {
  61846. parentScale.copyFrom(mesh.getWorldMatrix());
  61847. parentScaleInv.copyFrom(parentScale);
  61848. parentScaleInv.invert();
  61849. lmat.multiplyToRef(parentScale, lmat);
  61850. lmat.multiplyToRef(rmat, lmat);
  61851. lmat.multiplyToRef(parentScaleInv, lmat);
  61852. }
  61853. else {
  61854. lmat.multiplyToRef(rmat, lmat);
  61855. }
  61856. }
  61857. lmat.m[12] = lx;
  61858. lmat.m[13] = ly;
  61859. lmat.m[14] = lz;
  61860. this.computeAbsoluteTransforms();
  61861. this.markAsDirty();
  61862. };
  61863. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  61864. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61865. if (space == BABYLON.Space.WORLD) {
  61866. var scaleMatrix = Bone._tmpMats[2];
  61867. scaleMatrix.copyFrom(this._scaleMatrix);
  61868. rotMatInv.copyFrom(this.getAbsoluteTransform());
  61869. if (mesh) {
  61870. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  61871. var meshScale = Bone._tmpMats[3];
  61872. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  61873. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  61874. }
  61875. rotMatInv.invert();
  61876. scaleMatrix.m[0] *= this._scalingDeterminant;
  61877. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  61878. }
  61879. else {
  61880. rotMatInv.copyFrom(this.getLocalMatrix());
  61881. rotMatInv.invert();
  61882. var scaleMatrix = Bone._tmpMats[2];
  61883. scaleMatrix.copyFrom(this._scaleMatrix);
  61884. if (this._parent) {
  61885. var pscaleMatrix = Bone._tmpMats[3];
  61886. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  61887. pscaleMatrix.invert();
  61888. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  61889. }
  61890. else {
  61891. scaleMatrix.m[0] *= this._scalingDeterminant;
  61892. }
  61893. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  61894. }
  61895. };
  61896. /**
  61897. * Get the scale of the bone
  61898. * @returns the scale of the bone
  61899. */
  61900. Bone.prototype.getScale = function () {
  61901. return this._scaleVector.clone();
  61902. };
  61903. /**
  61904. * Copy the scale of the bone to a vector3.
  61905. * @param result The vector3 to copy the scale to
  61906. */
  61907. Bone.prototype.getScaleToRef = function (result) {
  61908. result.copyFrom(this._scaleVector);
  61909. };
  61910. /**
  61911. * Get the position of the bone in local or world space.
  61912. * @param space The space that the returned position is in.
  61913. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61914. * @returns The position of the bone
  61915. */
  61916. Bone.prototype.getPosition = function (space, mesh) {
  61917. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61918. if (mesh === void 0) { mesh = null; }
  61919. var pos = BABYLON.Vector3.Zero();
  61920. this.getPositionToRef(space, mesh, pos);
  61921. return pos;
  61922. };
  61923. /**
  61924. * Copy the position of the bone to a vector3 in local or world space.
  61925. * @param space The space that the returned position is in.
  61926. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61927. * @param result The vector3 to copy the position to.
  61928. */
  61929. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  61930. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61931. if (space == BABYLON.Space.LOCAL) {
  61932. var lm = this.getLocalMatrix();
  61933. result.x = lm.m[12];
  61934. result.y = lm.m[13];
  61935. result.z = lm.m[14];
  61936. }
  61937. else {
  61938. var wm = null;
  61939. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61940. if (mesh) {
  61941. wm = mesh.getWorldMatrix();
  61942. }
  61943. this._skeleton.computeAbsoluteTransforms();
  61944. var tmat = Bone._tmpMats[0];
  61945. if (mesh && wm) {
  61946. tmat.copyFrom(this.getAbsoluteTransform());
  61947. tmat.multiplyToRef(wm, tmat);
  61948. }
  61949. else {
  61950. tmat = this.getAbsoluteTransform();
  61951. }
  61952. result.x = tmat.m[12];
  61953. result.y = tmat.m[13];
  61954. result.z = tmat.m[14];
  61955. }
  61956. };
  61957. /**
  61958. * Get the absolute position of the bone (world space).
  61959. * @param mesh The mesh that this bone is attached to.
  61960. * @returns The absolute position of the bone
  61961. */
  61962. Bone.prototype.getAbsolutePosition = function (mesh) {
  61963. if (mesh === void 0) { mesh = null; }
  61964. var pos = BABYLON.Vector3.Zero();
  61965. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  61966. return pos;
  61967. };
  61968. /**
  61969. * Copy the absolute position of the bone (world space) to the result param.
  61970. * @param mesh The mesh that this bone is attached to.
  61971. * @param result The vector3 to copy the absolute position to.
  61972. */
  61973. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  61974. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  61975. };
  61976. /**
  61977. * Compute the absolute transforms of this bone and its children.
  61978. */
  61979. Bone.prototype.computeAbsoluteTransforms = function () {
  61980. if (this._parent) {
  61981. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  61982. }
  61983. else {
  61984. this._absoluteTransform.copyFrom(this._localMatrix);
  61985. var poseMatrix = this._skeleton.getPoseMatrix();
  61986. if (poseMatrix) {
  61987. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  61988. }
  61989. }
  61990. var children = this.children;
  61991. var len = children.length;
  61992. for (var i = 0; i < len; i++) {
  61993. children[i].computeAbsoluteTransforms();
  61994. }
  61995. };
  61996. Bone.prototype._syncScaleVector = function () {
  61997. var lm = this.getLocalMatrix();
  61998. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  61999. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  62000. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  62001. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  62002. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  62003. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  62004. this._scaleVector.x = xs * Math.sqrt(xsq);
  62005. this._scaleVector.y = ys * Math.sqrt(ysq);
  62006. this._scaleVector.z = zs * Math.sqrt(zsq);
  62007. if (this._parent) {
  62008. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  62009. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  62010. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  62011. }
  62012. 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);
  62013. };
  62014. /**
  62015. * Get the world direction from an axis that is in the local space of the bone.
  62016. * @param localAxis The local direction that is used to compute the world direction.
  62017. * @param mesh The mesh that this bone is attached to.
  62018. * @returns The world direction
  62019. */
  62020. Bone.prototype.getDirection = function (localAxis, mesh) {
  62021. if (mesh === void 0) { mesh = null; }
  62022. var result = BABYLON.Vector3.Zero();
  62023. this.getDirectionToRef(localAxis, mesh, result);
  62024. return result;
  62025. };
  62026. /**
  62027. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  62028. * @param localAxis The local direction that is used to compute the world direction.
  62029. * @param mesh The mesh that this bone is attached to.
  62030. * @param result The vector3 that the world direction will be copied to.
  62031. */
  62032. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  62033. if (mesh === void 0) { mesh = null; }
  62034. var wm = null;
  62035. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  62036. if (mesh) {
  62037. wm = mesh.getWorldMatrix();
  62038. }
  62039. this._skeleton.computeAbsoluteTransforms();
  62040. var mat = Bone._tmpMats[0];
  62041. mat.copyFrom(this.getAbsoluteTransform());
  62042. if (mesh && wm) {
  62043. mat.multiplyToRef(wm, mat);
  62044. }
  62045. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  62046. result.normalize();
  62047. };
  62048. /**
  62049. * Get the euler rotation of the bone in local or world space.
  62050. * @param space The space that the rotation should be in.
  62051. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62052. * @returns The euler rotation
  62053. */
  62054. Bone.prototype.getRotation = function (space, mesh) {
  62055. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62056. if (mesh === void 0) { mesh = null; }
  62057. var result = BABYLON.Vector3.Zero();
  62058. this.getRotationToRef(space, mesh, result);
  62059. return result;
  62060. };
  62061. /**
  62062. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  62063. * @param space The space that the rotation should be in.
  62064. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62065. * @param result The vector3 that the rotation should be copied to.
  62066. */
  62067. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  62068. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62069. if (mesh === void 0) { mesh = null; }
  62070. var quat = Bone._tmpQuat;
  62071. this.getRotationQuaternionToRef(space, mesh, quat);
  62072. quat.toEulerAnglesToRef(result);
  62073. };
  62074. /**
  62075. * Get the quaternion rotation of the bone in either local or world space.
  62076. * @param space The space that the rotation should be in.
  62077. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62078. * @returns The quaternion rotation
  62079. */
  62080. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  62081. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62082. if (mesh === void 0) { mesh = null; }
  62083. var result = BABYLON.Quaternion.Identity();
  62084. this.getRotationQuaternionToRef(space, mesh, result);
  62085. return result;
  62086. };
  62087. /**
  62088. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  62089. * @param space The space that the rotation should be in.
  62090. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62091. * @param result The quaternion that the rotation should be copied to.
  62092. */
  62093. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  62094. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62095. if (mesh === void 0) { mesh = null; }
  62096. if (space == BABYLON.Space.LOCAL) {
  62097. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  62098. }
  62099. else {
  62100. var mat = Bone._tmpMats[0];
  62101. var amat = this.getAbsoluteTransform();
  62102. if (mesh) {
  62103. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  62104. }
  62105. else {
  62106. mat.copyFrom(amat);
  62107. }
  62108. mat.m[0] *= this._scalingDeterminant;
  62109. mat.m[1] *= this._scalingDeterminant;
  62110. mat.m[2] *= this._scalingDeterminant;
  62111. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  62112. }
  62113. };
  62114. /**
  62115. * Get the rotation matrix of the bone in local or world space.
  62116. * @param space The space that the rotation should be in.
  62117. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62118. * @returns The rotation matrix
  62119. */
  62120. Bone.prototype.getRotationMatrix = function (space, mesh) {
  62121. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62122. var result = BABYLON.Matrix.Identity();
  62123. this.getRotationMatrixToRef(space, mesh, result);
  62124. return result;
  62125. };
  62126. /**
  62127. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  62128. * @param space The space that the rotation should be in.
  62129. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62130. * @param result The quaternion that the rotation should be copied to.
  62131. */
  62132. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  62133. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62134. if (space == BABYLON.Space.LOCAL) {
  62135. this.getLocalMatrix().getRotationMatrixToRef(result);
  62136. }
  62137. else {
  62138. var mat = Bone._tmpMats[0];
  62139. var amat = this.getAbsoluteTransform();
  62140. if (mesh) {
  62141. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  62142. }
  62143. else {
  62144. mat.copyFrom(amat);
  62145. }
  62146. mat.m[0] *= this._scalingDeterminant;
  62147. mat.m[1] *= this._scalingDeterminant;
  62148. mat.m[2] *= this._scalingDeterminant;
  62149. mat.getRotationMatrixToRef(result);
  62150. }
  62151. };
  62152. /**
  62153. * Get the world position of a point that is in the local space of the bone.
  62154. * @param position The local position
  62155. * @param mesh The mesh that this bone is attached to.
  62156. * @returns The world position
  62157. */
  62158. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  62159. if (mesh === void 0) { mesh = null; }
  62160. var result = BABYLON.Vector3.Zero();
  62161. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  62162. return result;
  62163. };
  62164. /**
  62165. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  62166. * @param position The local position
  62167. * @param mesh The mesh that this bone is attached to.
  62168. * @param result The vector3 that the world position should be copied to.
  62169. */
  62170. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  62171. if (mesh === void 0) { mesh = null; }
  62172. var wm = null;
  62173. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  62174. if (mesh) {
  62175. wm = mesh.getWorldMatrix();
  62176. }
  62177. this._skeleton.computeAbsoluteTransforms();
  62178. var tmat = Bone._tmpMats[0];
  62179. if (mesh && wm) {
  62180. tmat.copyFrom(this.getAbsoluteTransform());
  62181. tmat.multiplyToRef(wm, tmat);
  62182. }
  62183. else {
  62184. tmat = this.getAbsoluteTransform();
  62185. }
  62186. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  62187. };
  62188. /**
  62189. * Get the local position of a point that is in world space.
  62190. * @param position The world position
  62191. * @param mesh The mesh that this bone is attached to.
  62192. * @returns The local position
  62193. */
  62194. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  62195. if (mesh === void 0) { mesh = null; }
  62196. var result = BABYLON.Vector3.Zero();
  62197. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  62198. return result;
  62199. };
  62200. /**
  62201. * Get the local position of a point that is in world space and copy it to the result param.
  62202. * @param position The world position
  62203. * @param mesh The mesh that this bone is attached to.
  62204. * @param result The vector3 that the local position should be copied to.
  62205. */
  62206. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  62207. if (mesh === void 0) { mesh = null; }
  62208. var wm = null;
  62209. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  62210. if (mesh) {
  62211. wm = mesh.getWorldMatrix();
  62212. }
  62213. this._skeleton.computeAbsoluteTransforms();
  62214. var tmat = Bone._tmpMats[0];
  62215. tmat.copyFrom(this.getAbsoluteTransform());
  62216. if (mesh && wm) {
  62217. tmat.multiplyToRef(wm, tmat);
  62218. }
  62219. tmat.invert();
  62220. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  62221. };
  62222. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62223. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  62224. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  62225. return Bone;
  62226. }(BABYLON.Node));
  62227. BABYLON.Bone = Bone;
  62228. })(BABYLON || (BABYLON = {}));
  62229. //# sourceMappingURL=babylon.bone.js.map
  62230. var BABYLON;
  62231. (function (BABYLON) {
  62232. var BoneIKController = /** @class */ (function () {
  62233. function BoneIKController(mesh, bone, options) {
  62234. this.targetPosition = BABYLON.Vector3.Zero();
  62235. this.poleTargetPosition = BABYLON.Vector3.Zero();
  62236. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  62237. this.poleAngle = 0;
  62238. this.slerpAmount = 1;
  62239. this._bone1Quat = BABYLON.Quaternion.Identity();
  62240. this._bone1Mat = BABYLON.Matrix.Identity();
  62241. this._bone2Ang = Math.PI;
  62242. this._maxAngle = Math.PI;
  62243. this._rightHandedSystem = false;
  62244. this._bendAxis = BABYLON.Vector3.Right();
  62245. this._slerping = false;
  62246. this._adjustRoll = 0;
  62247. this._bone2 = bone;
  62248. this._bone1 = bone.getParent();
  62249. if (!this._bone1) {
  62250. return;
  62251. }
  62252. this.mesh = mesh;
  62253. var bonePos = bone.getPosition();
  62254. if (bone.getAbsoluteTransform().determinant() > 0) {
  62255. this._rightHandedSystem = true;
  62256. this._bendAxis.x = 0;
  62257. this._bendAxis.y = 0;
  62258. this._bendAxis.z = -1;
  62259. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  62260. this._adjustRoll = Math.PI * .5;
  62261. this._bendAxis.z = 1;
  62262. }
  62263. }
  62264. if (this._bone1.length) {
  62265. var boneScale1 = this._bone1.getScale();
  62266. var boneScale2 = this._bone2.getScale();
  62267. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  62268. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  62269. }
  62270. else if (this._bone1.children[0]) {
  62271. mesh.computeWorldMatrix(true);
  62272. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  62273. var pos2 = this._bone2.getAbsolutePosition(mesh);
  62274. var pos3 = this._bone1.getAbsolutePosition(mesh);
  62275. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  62276. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  62277. }
  62278. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  62279. this.maxAngle = Math.PI;
  62280. if (options) {
  62281. if (options.targetMesh) {
  62282. this.targetMesh = options.targetMesh;
  62283. this.targetMesh.computeWorldMatrix(true);
  62284. }
  62285. if (options.poleTargetMesh) {
  62286. this.poleTargetMesh = options.poleTargetMesh;
  62287. this.poleTargetMesh.computeWorldMatrix(true);
  62288. }
  62289. else if (options.poleTargetBone) {
  62290. this.poleTargetBone = options.poleTargetBone;
  62291. }
  62292. else if (this._bone1.getParent()) {
  62293. this.poleTargetBone = this._bone1.getParent();
  62294. }
  62295. if (options.poleTargetLocalOffset) {
  62296. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  62297. }
  62298. if (options.poleAngle) {
  62299. this.poleAngle = options.poleAngle;
  62300. }
  62301. if (options.bendAxis) {
  62302. this._bendAxis.copyFrom(options.bendAxis);
  62303. }
  62304. if (options.maxAngle) {
  62305. this.maxAngle = options.maxAngle;
  62306. }
  62307. if (options.slerpAmount) {
  62308. this.slerpAmount = options.slerpAmount;
  62309. }
  62310. }
  62311. }
  62312. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  62313. get: function () {
  62314. return this._maxAngle;
  62315. },
  62316. set: function (value) {
  62317. this._setMaxAngle(value);
  62318. },
  62319. enumerable: true,
  62320. configurable: true
  62321. });
  62322. BoneIKController.prototype._setMaxAngle = function (ang) {
  62323. if (ang < 0) {
  62324. ang = 0;
  62325. }
  62326. if (ang > Math.PI || ang == undefined) {
  62327. ang = Math.PI;
  62328. }
  62329. this._maxAngle = ang;
  62330. var a = this._bone1Length;
  62331. var b = this._bone2Length;
  62332. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  62333. };
  62334. BoneIKController.prototype.update = function () {
  62335. var bone1 = this._bone1;
  62336. if (!bone1) {
  62337. return;
  62338. }
  62339. var target = this.targetPosition;
  62340. var poleTarget = this.poleTargetPosition;
  62341. var mat1 = BoneIKController._tmpMats[0];
  62342. var mat2 = BoneIKController._tmpMats[1];
  62343. if (this.targetMesh) {
  62344. target.copyFrom(this.targetMesh.getAbsolutePosition());
  62345. }
  62346. if (this.poleTargetBone) {
  62347. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  62348. }
  62349. else if (this.poleTargetMesh) {
  62350. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  62351. }
  62352. var bonePos = BoneIKController._tmpVecs[0];
  62353. var zaxis = BoneIKController._tmpVecs[1];
  62354. var xaxis = BoneIKController._tmpVecs[2];
  62355. var yaxis = BoneIKController._tmpVecs[3];
  62356. var upAxis = BoneIKController._tmpVecs[4];
  62357. var _tmpQuat = BoneIKController._tmpQuat;
  62358. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  62359. poleTarget.subtractToRef(bonePos, upAxis);
  62360. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  62361. upAxis.y = 1;
  62362. }
  62363. else {
  62364. upAxis.normalize();
  62365. }
  62366. target.subtractToRef(bonePos, yaxis);
  62367. yaxis.normalize();
  62368. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  62369. zaxis.normalize();
  62370. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  62371. xaxis.normalize();
  62372. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  62373. var a = this._bone1Length;
  62374. var b = this._bone2Length;
  62375. var c = BABYLON.Vector3.Distance(bonePos, target);
  62376. if (this._maxReach > 0) {
  62377. c = Math.min(this._maxReach, c);
  62378. }
  62379. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  62380. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  62381. if (acosa > 1) {
  62382. acosa = 1;
  62383. }
  62384. if (acosb > 1) {
  62385. acosb = 1;
  62386. }
  62387. if (acosa < -1) {
  62388. acosa = -1;
  62389. }
  62390. if (acosb < -1) {
  62391. acosb = -1;
  62392. }
  62393. var angA = Math.acos(acosa);
  62394. var angB = Math.acos(acosb);
  62395. var angC = -angA - angB;
  62396. if (this._rightHandedSystem) {
  62397. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  62398. mat2.multiplyToRef(mat1, mat1);
  62399. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  62400. mat2.multiplyToRef(mat1, mat1);
  62401. }
  62402. else {
  62403. var _tmpVec = BoneIKController._tmpVecs[5];
  62404. _tmpVec.copyFrom(this._bendAxis);
  62405. _tmpVec.x *= -1;
  62406. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  62407. mat2.multiplyToRef(mat1, mat1);
  62408. }
  62409. if (this.poleAngle) {
  62410. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  62411. mat1.multiplyToRef(mat2, mat1);
  62412. }
  62413. if (this._bone1) {
  62414. if (this.slerpAmount < 1) {
  62415. if (!this._slerping) {
  62416. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  62417. }
  62418. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  62419. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  62420. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  62421. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  62422. this._slerping = true;
  62423. }
  62424. else {
  62425. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  62426. this._bone1Mat.copyFrom(mat1);
  62427. this._slerping = false;
  62428. }
  62429. }
  62430. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  62431. this._bone2Ang = angC;
  62432. };
  62433. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62434. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  62435. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  62436. return BoneIKController;
  62437. }());
  62438. BABYLON.BoneIKController = BoneIKController;
  62439. })(BABYLON || (BABYLON = {}));
  62440. //# sourceMappingURL=babylon.boneIKController.js.map
  62441. var BABYLON;
  62442. (function (BABYLON) {
  62443. var BoneLookController = /** @class */ (function () {
  62444. /**
  62445. * Create a BoneLookController
  62446. * @param mesh the mesh that the bone belongs to
  62447. * @param bone the bone that will be looking to the target
  62448. * @param target the target Vector3 to look at
  62449. * @param settings optional settings:
  62450. * - maxYaw: the maximum angle the bone will yaw to
  62451. * - minYaw: the minimum angle the bone will yaw to
  62452. * - maxPitch: the maximum angle the bone will pitch to
  62453. * - minPitch: the minimum angle the bone will yaw to
  62454. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  62455. * - upAxis: the up axis of the coordinate system
  62456. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  62457. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  62458. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  62459. * - adjustYaw: used to make an adjustment to the yaw of the bone
  62460. * - adjustPitch: used to make an adjustment to the pitch of the bone
  62461. * - adjustRoll: used to make an adjustment to the roll of the bone
  62462. **/
  62463. function BoneLookController(mesh, bone, target, options) {
  62464. /**
  62465. * The up axis of the coordinate system that is used when the bone is rotated.
  62466. */
  62467. this.upAxis = BABYLON.Vector3.Up();
  62468. /**
  62469. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  62470. */
  62471. this.upAxisSpace = BABYLON.Space.LOCAL;
  62472. /**
  62473. * Used to make an adjustment to the yaw of the bone.
  62474. */
  62475. this.adjustYaw = 0;
  62476. /**
  62477. * Used to make an adjustment to the pitch of the bone.
  62478. */
  62479. this.adjustPitch = 0;
  62480. /**
  62481. * Used to make an adjustment to the roll of the bone.
  62482. */
  62483. this.adjustRoll = 0;
  62484. /**
  62485. * 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).
  62486. */
  62487. this.slerpAmount = 1;
  62488. this._boneQuat = BABYLON.Quaternion.Identity();
  62489. this._slerping = false;
  62490. this._firstFrameSkipped = false;
  62491. this._fowardAxis = BABYLON.Vector3.Forward();
  62492. this.mesh = mesh;
  62493. this.bone = bone;
  62494. this.target = target;
  62495. if (options) {
  62496. if (options.adjustYaw) {
  62497. this.adjustYaw = options.adjustYaw;
  62498. }
  62499. if (options.adjustPitch) {
  62500. this.adjustPitch = options.adjustPitch;
  62501. }
  62502. if (options.adjustRoll) {
  62503. this.adjustRoll = options.adjustRoll;
  62504. }
  62505. if (options.maxYaw != null) {
  62506. this.maxYaw = options.maxYaw;
  62507. }
  62508. else {
  62509. this.maxYaw = Math.PI;
  62510. }
  62511. if (options.minYaw != null) {
  62512. this.minYaw = options.minYaw;
  62513. }
  62514. else {
  62515. this.minYaw = -Math.PI;
  62516. }
  62517. if (options.maxPitch != null) {
  62518. this.maxPitch = options.maxPitch;
  62519. }
  62520. else {
  62521. this.maxPitch = Math.PI;
  62522. }
  62523. if (options.minPitch != null) {
  62524. this.minPitch = options.minPitch;
  62525. }
  62526. else {
  62527. this.minPitch = -Math.PI;
  62528. }
  62529. if (options.slerpAmount != null) {
  62530. this.slerpAmount = options.slerpAmount;
  62531. }
  62532. if (options.upAxis != null) {
  62533. this.upAxis = options.upAxis;
  62534. }
  62535. if (options.upAxisSpace != null) {
  62536. this.upAxisSpace = options.upAxisSpace;
  62537. }
  62538. if (options.yawAxis != null || options.pitchAxis != null) {
  62539. var newYawAxis = BABYLON.Axis.Y;
  62540. var newPitchAxis = BABYLON.Axis.X;
  62541. if (options.yawAxis != null) {
  62542. newYawAxis = options.yawAxis.clone();
  62543. newYawAxis.normalize();
  62544. }
  62545. if (options.pitchAxis != null) {
  62546. newPitchAxis = options.pitchAxis.clone();
  62547. newPitchAxis.normalize();
  62548. }
  62549. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  62550. this._transformYawPitch = BABYLON.Matrix.Identity();
  62551. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  62552. this._transformYawPitchInv = this._transformYawPitch.clone();
  62553. this._transformYawPitch.invert();
  62554. }
  62555. }
  62556. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  62557. this.upAxisSpace = BABYLON.Space.LOCAL;
  62558. }
  62559. }
  62560. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  62561. /**
  62562. * Get/set the minimum yaw angle that the bone can look to.
  62563. */
  62564. get: function () {
  62565. return this._minYaw;
  62566. },
  62567. set: function (value) {
  62568. this._minYaw = value;
  62569. this._minYawSin = Math.sin(value);
  62570. this._minYawCos = Math.cos(value);
  62571. if (this._maxYaw != null) {
  62572. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  62573. this._yawRange = this._maxYaw - this._minYaw;
  62574. }
  62575. },
  62576. enumerable: true,
  62577. configurable: true
  62578. });
  62579. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  62580. /**
  62581. * Get/set the maximum yaw angle that the bone can look to.
  62582. */
  62583. get: function () {
  62584. return this._maxYaw;
  62585. },
  62586. set: function (value) {
  62587. this._maxYaw = value;
  62588. this._maxYawSin = Math.sin(value);
  62589. this._maxYawCos = Math.cos(value);
  62590. if (this._minYaw != null) {
  62591. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  62592. this._yawRange = this._maxYaw - this._minYaw;
  62593. }
  62594. },
  62595. enumerable: true,
  62596. configurable: true
  62597. });
  62598. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  62599. /**
  62600. * Get/set the minimum pitch angle that the bone can look to.
  62601. */
  62602. get: function () {
  62603. return this._minPitch;
  62604. },
  62605. set: function (value) {
  62606. this._minPitch = value;
  62607. this._minPitchTan = Math.tan(value);
  62608. },
  62609. enumerable: true,
  62610. configurable: true
  62611. });
  62612. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  62613. /**
  62614. * Get/set the maximum pitch angle that the bone can look to.
  62615. */
  62616. get: function () {
  62617. return this._maxPitch;
  62618. },
  62619. set: function (value) {
  62620. this._maxPitch = value;
  62621. this._maxPitchTan = Math.tan(value);
  62622. },
  62623. enumerable: true,
  62624. configurable: true
  62625. });
  62626. /**
  62627. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  62628. */
  62629. BoneLookController.prototype.update = function () {
  62630. //skip the first frame when slerping so that the mesh rotation is correct
  62631. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  62632. this._firstFrameSkipped = true;
  62633. return;
  62634. }
  62635. var bone = this.bone;
  62636. var bonePos = BoneLookController._tmpVecs[0];
  62637. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  62638. var target = this.target;
  62639. var _tmpMat1 = BoneLookController._tmpMats[0];
  62640. var _tmpMat2 = BoneLookController._tmpMats[1];
  62641. var mesh = this.mesh;
  62642. var parentBone = bone.getParent();
  62643. var upAxis = BoneLookController._tmpVecs[1];
  62644. upAxis.copyFrom(this.upAxis);
  62645. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  62646. if (this._transformYawPitch) {
  62647. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  62648. }
  62649. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  62650. }
  62651. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  62652. mesh.getDirectionToRef(upAxis, upAxis);
  62653. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  62654. upAxis.normalize();
  62655. }
  62656. }
  62657. var checkYaw = false;
  62658. var checkPitch = false;
  62659. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  62660. checkYaw = true;
  62661. }
  62662. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  62663. checkPitch = true;
  62664. }
  62665. if (checkYaw || checkPitch) {
  62666. var spaceMat = BoneLookController._tmpMats[2];
  62667. var spaceMatInv = BoneLookController._tmpMats[3];
  62668. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  62669. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  62670. }
  62671. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  62672. spaceMat.copyFrom(mesh.getWorldMatrix());
  62673. }
  62674. else {
  62675. var forwardAxis = BoneLookController._tmpVecs[2];
  62676. forwardAxis.copyFrom(this._fowardAxis);
  62677. if (this._transformYawPitch) {
  62678. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  62679. }
  62680. if (parentBone) {
  62681. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  62682. }
  62683. else {
  62684. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  62685. }
  62686. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  62687. rightAxis.normalize();
  62688. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  62689. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  62690. }
  62691. spaceMat.invertToRef(spaceMatInv);
  62692. var xzlen = null;
  62693. if (checkPitch) {
  62694. var localTarget = BoneLookController._tmpVecs[3];
  62695. target.subtractToRef(bonePos, localTarget);
  62696. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  62697. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  62698. var pitch = Math.atan2(localTarget.y, xzlen);
  62699. var newPitch = pitch;
  62700. if (pitch > this._maxPitch) {
  62701. localTarget.y = this._maxPitchTan * xzlen;
  62702. newPitch = this._maxPitch;
  62703. }
  62704. else if (pitch < this._minPitch) {
  62705. localTarget.y = this._minPitchTan * xzlen;
  62706. newPitch = this._minPitch;
  62707. }
  62708. if (pitch != newPitch) {
  62709. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  62710. localTarget.addInPlace(bonePos);
  62711. target = localTarget;
  62712. }
  62713. }
  62714. if (checkYaw) {
  62715. var localTarget = BoneLookController._tmpVecs[4];
  62716. target.subtractToRef(bonePos, localTarget);
  62717. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  62718. var yaw = Math.atan2(localTarget.x, localTarget.z);
  62719. var newYaw = yaw;
  62720. if (yaw > this._maxYaw || yaw < this._minYaw) {
  62721. if (xzlen == null) {
  62722. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  62723. }
  62724. if (this._yawRange > Math.PI) {
  62725. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  62726. localTarget.z = this._maxYawCos * xzlen;
  62727. localTarget.x = this._maxYawSin * xzlen;
  62728. newYaw = this._maxYaw;
  62729. }
  62730. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  62731. localTarget.z = this._minYawCos * xzlen;
  62732. localTarget.x = this._minYawSin * xzlen;
  62733. newYaw = this._minYaw;
  62734. }
  62735. }
  62736. else {
  62737. if (yaw > this._maxYaw) {
  62738. localTarget.z = this._maxYawCos * xzlen;
  62739. localTarget.x = this._maxYawSin * xzlen;
  62740. newYaw = this._maxYaw;
  62741. }
  62742. else if (yaw < this._minYaw) {
  62743. localTarget.z = this._minYawCos * xzlen;
  62744. localTarget.x = this._minYawSin * xzlen;
  62745. newYaw = this._minYaw;
  62746. }
  62747. }
  62748. }
  62749. if (this._slerping && this._yawRange > Math.PI) {
  62750. //are we going to be crossing into the min/max region?
  62751. var boneFwd = BoneLookController._tmpVecs[8];
  62752. boneFwd.copyFrom(BABYLON.Axis.Z);
  62753. if (this._transformYawPitch) {
  62754. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  62755. }
  62756. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  62757. this._boneQuat.toRotationMatrix(boneRotMat);
  62758. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  62759. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  62760. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  62761. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  62762. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  62763. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  62764. if (angBtwTar > angBtwMidYaw) {
  62765. if (xzlen == null) {
  62766. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  62767. }
  62768. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  62769. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  62770. if (angBtwMin < angBtwMax) {
  62771. newYaw = boneYaw + Math.PI * .75;
  62772. localTarget.z = Math.cos(newYaw) * xzlen;
  62773. localTarget.x = Math.sin(newYaw) * xzlen;
  62774. }
  62775. else {
  62776. newYaw = boneYaw - Math.PI * .75;
  62777. localTarget.z = Math.cos(newYaw) * xzlen;
  62778. localTarget.x = Math.sin(newYaw) * xzlen;
  62779. }
  62780. }
  62781. }
  62782. if (yaw != newYaw) {
  62783. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  62784. localTarget.addInPlace(bonePos);
  62785. target = localTarget;
  62786. }
  62787. }
  62788. }
  62789. var zaxis = BoneLookController._tmpVecs[5];
  62790. var xaxis = BoneLookController._tmpVecs[6];
  62791. var yaxis = BoneLookController._tmpVecs[7];
  62792. var _tmpQuat = BoneLookController._tmpQuat;
  62793. target.subtractToRef(bonePos, zaxis);
  62794. zaxis.normalize();
  62795. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  62796. xaxis.normalize();
  62797. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  62798. yaxis.normalize();
  62799. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  62800. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  62801. return;
  62802. }
  62803. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  62804. return;
  62805. }
  62806. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  62807. return;
  62808. }
  62809. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  62810. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  62811. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  62812. }
  62813. if (this.slerpAmount < 1) {
  62814. if (!this._slerping) {
  62815. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  62816. }
  62817. if (this._transformYawPitch) {
  62818. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  62819. }
  62820. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  62821. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  62822. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  62823. this._slerping = true;
  62824. }
  62825. else {
  62826. if (this._transformYawPitch) {
  62827. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  62828. }
  62829. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  62830. this._slerping = false;
  62831. }
  62832. };
  62833. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  62834. var angDiff = ang2 - ang1;
  62835. angDiff %= Math.PI * 2;
  62836. if (angDiff > Math.PI) {
  62837. angDiff -= Math.PI * 2;
  62838. }
  62839. else if (angDiff < -Math.PI) {
  62840. angDiff += Math.PI * 2;
  62841. }
  62842. return angDiff;
  62843. };
  62844. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  62845. ang1 %= (2 * Math.PI);
  62846. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  62847. ang2 %= (2 * Math.PI);
  62848. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  62849. var ab = 0;
  62850. if (ang1 < ang2) {
  62851. ab = ang2 - ang1;
  62852. }
  62853. else {
  62854. ab = ang1 - ang2;
  62855. }
  62856. if (ab > Math.PI) {
  62857. ab = Math.PI * 2 - ab;
  62858. }
  62859. return ab;
  62860. };
  62861. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  62862. ang %= (2 * Math.PI);
  62863. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  62864. ang1 %= (2 * Math.PI);
  62865. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  62866. ang2 %= (2 * Math.PI);
  62867. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  62868. if (ang1 < ang2) {
  62869. if (ang > ang1 && ang < ang2) {
  62870. return true;
  62871. }
  62872. }
  62873. else {
  62874. if (ang > ang2 && ang < ang1) {
  62875. return true;
  62876. }
  62877. }
  62878. return false;
  62879. };
  62880. 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()];
  62881. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  62882. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  62883. return BoneLookController;
  62884. }());
  62885. BABYLON.BoneLookController = BoneLookController;
  62886. })(BABYLON || (BABYLON = {}));
  62887. //# sourceMappingURL=babylon.boneLookController.js.map
  62888. var BABYLON;
  62889. (function (BABYLON) {
  62890. var Skeleton = /** @class */ (function () {
  62891. function Skeleton(name, id, scene) {
  62892. this.name = name;
  62893. this.id = id;
  62894. this.bones = new Array();
  62895. this.needInitialSkinMatrix = false;
  62896. this._isDirty = true;
  62897. this._meshesWithPoseMatrix = new Array();
  62898. this._identity = BABYLON.Matrix.Identity();
  62899. this._ranges = {};
  62900. this._lastAbsoluteTransformsUpdateId = -1;
  62901. // Events
  62902. /**
  62903. * An event triggered before computing the skeleton's matrices
  62904. * @type {BABYLON.Observable}
  62905. */
  62906. this.onBeforeComputeObservable = new BABYLON.Observable();
  62907. this.bones = [];
  62908. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62909. scene.skeletons.push(this);
  62910. //make sure it will recalculate the matrix next time prepare is called.
  62911. this._isDirty = true;
  62912. }
  62913. // Members
  62914. Skeleton.prototype.getTransformMatrices = function (mesh) {
  62915. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  62916. return mesh._bonesTransformMatrices;
  62917. }
  62918. if (!this._transformMatrices) {
  62919. this.prepare();
  62920. }
  62921. return this._transformMatrices;
  62922. };
  62923. Skeleton.prototype.getScene = function () {
  62924. return this._scene;
  62925. };
  62926. // Methods
  62927. /**
  62928. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  62929. */
  62930. Skeleton.prototype.toString = function (fullDetails) {
  62931. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  62932. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  62933. if (fullDetails) {
  62934. ret += ", Ranges: {";
  62935. var first = true;
  62936. for (var name_1 in this._ranges) {
  62937. if (first) {
  62938. ret += ", ";
  62939. first = false;
  62940. }
  62941. ret += name_1;
  62942. }
  62943. ret += "}";
  62944. }
  62945. return ret;
  62946. };
  62947. /**
  62948. * Get bone's index searching by name
  62949. * @param {string} name is bone's name to search for
  62950. * @return {number} Indice of the bone. Returns -1 if not found
  62951. */
  62952. Skeleton.prototype.getBoneIndexByName = function (name) {
  62953. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  62954. if (this.bones[boneIndex].name === name) {
  62955. return boneIndex;
  62956. }
  62957. }
  62958. return -1;
  62959. };
  62960. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  62961. // check name not already in use
  62962. if (!this._ranges[name]) {
  62963. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  62964. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  62965. if (this.bones[i].animations[0]) {
  62966. this.bones[i].animations[0].createRange(name, from, to);
  62967. }
  62968. }
  62969. }
  62970. };
  62971. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  62972. if (deleteFrames === void 0) { deleteFrames = true; }
  62973. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  62974. if (this.bones[i].animations[0]) {
  62975. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  62976. }
  62977. }
  62978. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  62979. };
  62980. Skeleton.prototype.getAnimationRange = function (name) {
  62981. return this._ranges[name];
  62982. };
  62983. /**
  62984. * Returns as an Array, all AnimationRanges defined on this skeleton
  62985. */
  62986. Skeleton.prototype.getAnimationRanges = function () {
  62987. var animationRanges = [];
  62988. var name;
  62989. var i = 0;
  62990. for (name in this._ranges) {
  62991. animationRanges[i] = this._ranges[name];
  62992. i++;
  62993. }
  62994. return animationRanges;
  62995. };
  62996. /**
  62997. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  62998. */
  62999. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  63000. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  63001. if (this._ranges[name] || !source.getAnimationRange(name)) {
  63002. return false;
  63003. }
  63004. var ret = true;
  63005. var frameOffset = this._getHighestAnimationFrame() + 1;
  63006. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  63007. var boneDict = {};
  63008. var sourceBones = source.bones;
  63009. var nBones;
  63010. var i;
  63011. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  63012. boneDict[sourceBones[i].name] = sourceBones[i];
  63013. }
  63014. if (this.bones.length !== sourceBones.length) {
  63015. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  63016. ret = false;
  63017. }
  63018. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  63019. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  63020. var boneName = this.bones[i].name;
  63021. var sourceBone = boneDict[boneName];
  63022. if (sourceBone) {
  63023. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  63024. }
  63025. else {
  63026. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  63027. ret = false;
  63028. }
  63029. }
  63030. // do not call createAnimationRange(), since it also is done to bones, which was already done
  63031. var range = source.getAnimationRange(name);
  63032. if (range) {
  63033. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  63034. }
  63035. return ret;
  63036. };
  63037. Skeleton.prototype.returnToRest = function () {
  63038. for (var index = 0; index < this.bones.length; index++) {
  63039. this.bones[index].returnToRest();
  63040. }
  63041. };
  63042. Skeleton.prototype._getHighestAnimationFrame = function () {
  63043. var ret = 0;
  63044. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  63045. if (this.bones[i].animations[0]) {
  63046. var highest = this.bones[i].animations[0].getHighestFrame();
  63047. if (ret < highest) {
  63048. ret = highest;
  63049. }
  63050. }
  63051. }
  63052. return ret;
  63053. };
  63054. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  63055. var range = this.getAnimationRange(name);
  63056. if (!range) {
  63057. return null;
  63058. }
  63059. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  63060. };
  63061. Skeleton.prototype._markAsDirty = function () {
  63062. this._isDirty = true;
  63063. };
  63064. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  63065. this._meshesWithPoseMatrix.push(mesh);
  63066. };
  63067. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  63068. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  63069. if (index > -1) {
  63070. this._meshesWithPoseMatrix.splice(index, 1);
  63071. }
  63072. };
  63073. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  63074. this.onBeforeComputeObservable.notifyObservers(this);
  63075. for (var index = 0; index < this.bones.length; index++) {
  63076. var bone = this.bones[index];
  63077. var parentBone = bone.getParent();
  63078. if (parentBone) {
  63079. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  63080. }
  63081. else {
  63082. if (initialSkinMatrix) {
  63083. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  63084. }
  63085. else {
  63086. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  63087. }
  63088. }
  63089. if (bone._index !== -1) {
  63090. var mappedIndex = bone._index === null ? index : bone._index;
  63091. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  63092. }
  63093. }
  63094. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  63095. };
  63096. Skeleton.prototype.prepare = function () {
  63097. if (!this._isDirty) {
  63098. return;
  63099. }
  63100. if (this.needInitialSkinMatrix) {
  63101. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  63102. var mesh = this._meshesWithPoseMatrix[index];
  63103. var poseMatrix = mesh.getPoseMatrix();
  63104. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  63105. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  63106. }
  63107. if (this._synchronizedWithMesh !== mesh) {
  63108. this._synchronizedWithMesh = mesh;
  63109. // Prepare bones
  63110. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  63111. var bone = this.bones[boneIndex];
  63112. if (!bone.getParent()) {
  63113. var matrix = bone.getBaseMatrix();
  63114. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  63115. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  63116. }
  63117. }
  63118. }
  63119. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  63120. }
  63121. }
  63122. else {
  63123. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  63124. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  63125. }
  63126. this._computeTransformMatrices(this._transformMatrices, null);
  63127. }
  63128. this._isDirty = false;
  63129. this._scene._activeBones.addCount(this.bones.length, false);
  63130. };
  63131. Skeleton.prototype.getAnimatables = function () {
  63132. if (!this._animatables || this._animatables.length !== this.bones.length) {
  63133. this._animatables = [];
  63134. for (var index = 0; index < this.bones.length; index++) {
  63135. this._animatables.push(this.bones[index]);
  63136. }
  63137. }
  63138. return this._animatables;
  63139. };
  63140. Skeleton.prototype.clone = function (name, id) {
  63141. var result = new Skeleton(name, id || name, this._scene);
  63142. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  63143. for (var index = 0; index < this.bones.length; index++) {
  63144. var source = this.bones[index];
  63145. var parentBone = null;
  63146. var parent_1 = source.getParent();
  63147. if (parent_1) {
  63148. var parentIndex = this.bones.indexOf(parent_1);
  63149. parentBone = result.bones[parentIndex];
  63150. }
  63151. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  63152. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  63153. }
  63154. if (this._ranges) {
  63155. result._ranges = {};
  63156. for (var rangeName in this._ranges) {
  63157. var range = this._ranges[rangeName];
  63158. if (range) {
  63159. result._ranges[rangeName] = range.clone();
  63160. }
  63161. }
  63162. }
  63163. this._isDirty = true;
  63164. return result;
  63165. };
  63166. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  63167. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  63168. this.bones.forEach(function (bone) {
  63169. bone.animations.forEach(function (animation) {
  63170. animation.enableBlending = true;
  63171. animation.blendingSpeed = blendingSpeed;
  63172. });
  63173. });
  63174. };
  63175. Skeleton.prototype.dispose = function () {
  63176. this._meshesWithPoseMatrix = [];
  63177. // Animations
  63178. this.getScene().stopAnimation(this);
  63179. // Remove from scene
  63180. this.getScene().removeSkeleton(this);
  63181. };
  63182. Skeleton.prototype.serialize = function () {
  63183. var serializationObject = {};
  63184. serializationObject.name = this.name;
  63185. serializationObject.id = this.id;
  63186. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  63187. serializationObject.bones = [];
  63188. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  63189. for (var index = 0; index < this.bones.length; index++) {
  63190. var bone = this.bones[index];
  63191. var parent_2 = bone.getParent();
  63192. var serializedBone = {
  63193. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  63194. name: bone.name,
  63195. matrix: bone.getBaseMatrix().toArray(),
  63196. rest: bone.getRestPose().toArray()
  63197. };
  63198. serializationObject.bones.push(serializedBone);
  63199. if (bone.length) {
  63200. serializedBone.length = bone.length;
  63201. }
  63202. if (bone.animations && bone.animations.length > 0) {
  63203. serializedBone.animation = bone.animations[0].serialize();
  63204. }
  63205. serializationObject.ranges = [];
  63206. for (var name in this._ranges) {
  63207. var source = this._ranges[name];
  63208. if (!source) {
  63209. continue;
  63210. }
  63211. var range = {};
  63212. range.name = name;
  63213. range.from = source.from;
  63214. range.to = source.to;
  63215. serializationObject.ranges.push(range);
  63216. }
  63217. }
  63218. return serializationObject;
  63219. };
  63220. Skeleton.Parse = function (parsedSkeleton, scene) {
  63221. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  63222. if (parsedSkeleton.dimensionsAtRest) {
  63223. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  63224. }
  63225. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  63226. var index;
  63227. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  63228. var parsedBone = parsedSkeleton.bones[index];
  63229. var parentBone = null;
  63230. if (parsedBone.parentBoneIndex > -1) {
  63231. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  63232. }
  63233. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  63234. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  63235. if (parsedBone.length) {
  63236. bone.length = parsedBone.length;
  63237. }
  63238. if (parsedBone.animation) {
  63239. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  63240. }
  63241. }
  63242. // placed after bones, so createAnimationRange can cascade down
  63243. if (parsedSkeleton.ranges) {
  63244. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  63245. var data = parsedSkeleton.ranges[index];
  63246. skeleton.createAnimationRange(data.name, data.from, data.to);
  63247. }
  63248. }
  63249. return skeleton;
  63250. };
  63251. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  63252. if (forceUpdate === void 0) { forceUpdate = false; }
  63253. var renderId = this._scene.getRenderId();
  63254. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  63255. this.bones[0].computeAbsoluteTransforms();
  63256. this._lastAbsoluteTransformsUpdateId = renderId;
  63257. }
  63258. };
  63259. Skeleton.prototype.getPoseMatrix = function () {
  63260. var poseMatrix = null;
  63261. if (this._meshesWithPoseMatrix.length > 0) {
  63262. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  63263. }
  63264. return poseMatrix;
  63265. };
  63266. Skeleton.prototype.sortBones = function () {
  63267. var bones = new Array();
  63268. var visited = new Array(this.bones.length);
  63269. for (var index = 0; index < this.bones.length; index++) {
  63270. this._sortBones(index, bones, visited);
  63271. }
  63272. this.bones = bones;
  63273. };
  63274. Skeleton.prototype._sortBones = function (index, bones, visited) {
  63275. if (visited[index]) {
  63276. return;
  63277. }
  63278. visited[index] = true;
  63279. var bone = this.bones[index];
  63280. if (bone._index === undefined) {
  63281. bone._index = index;
  63282. }
  63283. var parentBone = bone.getParent();
  63284. if (parentBone) {
  63285. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  63286. }
  63287. bones.push(bone);
  63288. };
  63289. return Skeleton;
  63290. }());
  63291. BABYLON.Skeleton = Skeleton;
  63292. })(BABYLON || (BABYLON = {}));
  63293. //# sourceMappingURL=babylon.skeleton.js.map
  63294. var BABYLON;
  63295. (function (BABYLON) {
  63296. var SphericalPolynomial = /** @class */ (function () {
  63297. function SphericalPolynomial() {
  63298. this.x = BABYLON.Vector3.Zero();
  63299. this.y = BABYLON.Vector3.Zero();
  63300. this.z = BABYLON.Vector3.Zero();
  63301. this.xx = BABYLON.Vector3.Zero();
  63302. this.yy = BABYLON.Vector3.Zero();
  63303. this.zz = BABYLON.Vector3.Zero();
  63304. this.xy = BABYLON.Vector3.Zero();
  63305. this.yz = BABYLON.Vector3.Zero();
  63306. this.zx = BABYLON.Vector3.Zero();
  63307. }
  63308. SphericalPolynomial.prototype.addAmbient = function (color) {
  63309. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  63310. this.xx = this.xx.add(colorVector);
  63311. this.yy = this.yy.add(colorVector);
  63312. this.zz = this.zz.add(colorVector);
  63313. };
  63314. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  63315. var result = new SphericalPolynomial();
  63316. result.x = harmonics.L11.scale(1.02333);
  63317. result.y = harmonics.L1_1.scale(1.02333);
  63318. result.z = harmonics.L10.scale(1.02333);
  63319. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  63320. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  63321. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  63322. result.yz = harmonics.L2_1.scale(0.858086);
  63323. result.zx = harmonics.L21.scale(0.858086);
  63324. result.xy = harmonics.L2_2.scale(0.858086);
  63325. result.scale(1.0 / Math.PI);
  63326. return result;
  63327. };
  63328. SphericalPolynomial.prototype.scale = function (scale) {
  63329. this.x = this.x.scale(scale);
  63330. this.y = this.y.scale(scale);
  63331. this.z = this.z.scale(scale);
  63332. this.xx = this.xx.scale(scale);
  63333. this.yy = this.yy.scale(scale);
  63334. this.zz = this.zz.scale(scale);
  63335. this.yz = this.yz.scale(scale);
  63336. this.zx = this.zx.scale(scale);
  63337. this.xy = this.xy.scale(scale);
  63338. };
  63339. return SphericalPolynomial;
  63340. }());
  63341. BABYLON.SphericalPolynomial = SphericalPolynomial;
  63342. var SphericalHarmonics = /** @class */ (function () {
  63343. function SphericalHarmonics() {
  63344. this.L00 = BABYLON.Vector3.Zero();
  63345. this.L1_1 = BABYLON.Vector3.Zero();
  63346. this.L10 = BABYLON.Vector3.Zero();
  63347. this.L11 = BABYLON.Vector3.Zero();
  63348. this.L2_2 = BABYLON.Vector3.Zero();
  63349. this.L2_1 = BABYLON.Vector3.Zero();
  63350. this.L20 = BABYLON.Vector3.Zero();
  63351. this.L21 = BABYLON.Vector3.Zero();
  63352. this.L22 = BABYLON.Vector3.Zero();
  63353. }
  63354. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  63355. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  63356. var c = colorVector.scale(deltaSolidAngle);
  63357. this.L00 = this.L00.add(c.scale(0.282095));
  63358. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  63359. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  63360. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  63361. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  63362. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  63363. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  63364. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  63365. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  63366. };
  63367. SphericalHarmonics.prototype.scale = function (scale) {
  63368. this.L00 = this.L00.scale(scale);
  63369. this.L1_1 = this.L1_1.scale(scale);
  63370. this.L10 = this.L10.scale(scale);
  63371. this.L11 = this.L11.scale(scale);
  63372. this.L2_2 = this.L2_2.scale(scale);
  63373. this.L2_1 = this.L2_1.scale(scale);
  63374. this.L20 = this.L20.scale(scale);
  63375. this.L21 = this.L21.scale(scale);
  63376. this.L22 = this.L22.scale(scale);
  63377. };
  63378. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  63379. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  63380. //
  63381. // E_lm = A_l * L_lm
  63382. //
  63383. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  63384. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  63385. // the scaling factors are given in equation 9.
  63386. // Constant (Band 0)
  63387. this.L00 = this.L00.scale(3.141593);
  63388. // Linear (Band 1)
  63389. this.L1_1 = this.L1_1.scale(2.094395);
  63390. this.L10 = this.L10.scale(2.094395);
  63391. this.L11 = this.L11.scale(2.094395);
  63392. // Quadratic (Band 2)
  63393. this.L2_2 = this.L2_2.scale(0.785398);
  63394. this.L2_1 = this.L2_1.scale(0.785398);
  63395. this.L20 = this.L20.scale(0.785398);
  63396. this.L21 = this.L21.scale(0.785398);
  63397. this.L22 = this.L22.scale(0.785398);
  63398. };
  63399. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  63400. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  63401. // L = (1/pi) * E * rho
  63402. //
  63403. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  63404. this.scale(1.0 / Math.PI);
  63405. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  63406. // (The pixel shader must apply albedo after texture fetches, etc).
  63407. };
  63408. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  63409. var result = new SphericalHarmonics();
  63410. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  63411. result.L1_1 = polynomial.y.scale(0.977204);
  63412. result.L10 = polynomial.z.scale(0.977204);
  63413. result.L11 = polynomial.x.scale(0.977204);
  63414. result.L2_2 = polynomial.xy.scale(1.16538);
  63415. result.L2_1 = polynomial.yz.scale(1.16538);
  63416. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  63417. result.L21 = polynomial.zx.scale(1.16538);
  63418. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  63419. result.scale(Math.PI);
  63420. return result;
  63421. };
  63422. return SphericalHarmonics;
  63423. }());
  63424. BABYLON.SphericalHarmonics = SphericalHarmonics;
  63425. })(BABYLON || (BABYLON = {}));
  63426. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  63427. var BABYLON;
  63428. (function (BABYLON) {
  63429. var Internals;
  63430. (function (Internals) {
  63431. var FileFaceOrientation = /** @class */ (function () {
  63432. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  63433. this.name = name;
  63434. this.worldAxisForNormal = worldAxisForNormal;
  63435. this.worldAxisForFileX = worldAxisForFileX;
  63436. this.worldAxisForFileY = worldAxisForFileY;
  63437. }
  63438. return FileFaceOrientation;
  63439. }());
  63440. ;
  63441. /**
  63442. * Helper class dealing with the extraction of spherical polynomial dataArray
  63443. * from a cube map.
  63444. */
  63445. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  63446. function CubeMapToSphericalPolynomialTools() {
  63447. }
  63448. /**
  63449. * Converts a texture to the according Spherical Polynomial data.
  63450. * This extracts the first 3 orders only as they are the only one used in the lighting.
  63451. *
  63452. * @param texture The texture to extract the information from.
  63453. * @return The Spherical Polynomial data.
  63454. */
  63455. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  63456. if (!texture.isCube) {
  63457. // Only supports cube Textures currently.
  63458. return null;
  63459. }
  63460. var size = texture.getSize().width;
  63461. var right = texture.readPixels(0);
  63462. var left = texture.readPixels(1);
  63463. var up;
  63464. var down;
  63465. if (texture.isRenderTarget) {
  63466. up = texture.readPixels(3);
  63467. down = texture.readPixels(2);
  63468. }
  63469. else {
  63470. up = texture.readPixels(2);
  63471. down = texture.readPixels(3);
  63472. }
  63473. var front = texture.readPixels(4);
  63474. var back = texture.readPixels(5);
  63475. var gammaSpace = texture.gammaSpace;
  63476. // Always read as RGBA.
  63477. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  63478. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  63479. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  63480. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  63481. }
  63482. var cubeInfo = {
  63483. size: size,
  63484. right: right,
  63485. left: left,
  63486. up: up,
  63487. down: down,
  63488. front: front,
  63489. back: back,
  63490. format: format,
  63491. type: type,
  63492. gammaSpace: gammaSpace,
  63493. };
  63494. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  63495. };
  63496. /**
  63497. * Converts a cubemap to the according Spherical Polynomial data.
  63498. * This extracts the first 3 orders only as they are the only one used in the lighting.
  63499. *
  63500. * @param cubeInfo The Cube map to extract the information from.
  63501. * @return The Spherical Polynomial data.
  63502. */
  63503. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  63504. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  63505. var totalSolidAngle = 0.0;
  63506. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  63507. var du = 2.0 / cubeInfo.size;
  63508. var dv = du;
  63509. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  63510. var minUV = du * 0.5 - 1.0;
  63511. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  63512. var fileFace = this.FileFaces[faceIndex];
  63513. var dataArray = cubeInfo[fileFace.name];
  63514. var v = minUV;
  63515. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  63516. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  63517. // Because SP is still linear, so summation is fine in that basis.
  63518. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  63519. for (var y = 0; y < cubeInfo.size; y++) {
  63520. var u = minUV;
  63521. for (var x = 0; x < cubeInfo.size; x++) {
  63522. // World direction (not normalised)
  63523. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  63524. worldDirection.normalize();
  63525. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  63526. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  63527. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  63528. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  63529. // Handle Integer types.
  63530. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  63531. r /= 255;
  63532. g /= 255;
  63533. b /= 255;
  63534. }
  63535. // Handle Gamma space textures.
  63536. if (cubeInfo.gammaSpace) {
  63537. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  63538. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  63539. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  63540. }
  63541. var color = new BABYLON.Color3(r, g, b);
  63542. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  63543. totalSolidAngle += deltaSolidAngle;
  63544. u += du;
  63545. }
  63546. v += dv;
  63547. }
  63548. }
  63549. // Solid angle for entire sphere is 4*pi
  63550. var sphereSolidAngle = 4.0 * Math.PI;
  63551. // Adjust the solid angle to allow for how many faces we processed.
  63552. var facesProcessed = 6.0;
  63553. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  63554. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  63555. // This is needed because the numerical integration over the cube uses a
  63556. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  63557. // and also to compensate for accumulative error due to float precision in the summation.
  63558. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  63559. sphericalHarmonics.scale(correctionFactor);
  63560. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  63561. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  63562. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  63563. };
  63564. CubeMapToSphericalPolynomialTools.FileFaces = [
  63565. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  63566. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  63567. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  63568. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  63569. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  63570. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  63571. ];
  63572. return CubeMapToSphericalPolynomialTools;
  63573. }());
  63574. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  63575. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  63576. })(BABYLON || (BABYLON = {}));
  63577. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  63578. var BABYLON;
  63579. (function (BABYLON) {
  63580. var Internals;
  63581. (function (Internals) {
  63582. /**
  63583. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  63584. */
  63585. var PanoramaToCubeMapTools = /** @class */ (function () {
  63586. function PanoramaToCubeMapTools() {
  63587. }
  63588. /**
  63589. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  63590. *
  63591. * @param float32Array The source data.
  63592. * @param inputWidth The width of the input panorama.
  63593. * @param inputhHeight The height of the input panorama.
  63594. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  63595. * @return The cubemap data
  63596. */
  63597. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  63598. if (!float32Array) {
  63599. throw "ConvertPanoramaToCubemap: input cannot be null";
  63600. }
  63601. if (float32Array.length != inputWidth * inputHeight * 3) {
  63602. throw "ConvertPanoramaToCubemap: input size is wrong";
  63603. }
  63604. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  63605. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  63606. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  63607. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  63608. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  63609. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  63610. return {
  63611. front: textureFront,
  63612. back: textureBack,
  63613. left: textureLeft,
  63614. right: textureRight,
  63615. up: textureUp,
  63616. down: textureDown,
  63617. size: size,
  63618. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  63619. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  63620. gammaSpace: false,
  63621. };
  63622. };
  63623. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  63624. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  63625. var textureArray = new Float32Array(buffer);
  63626. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  63627. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  63628. var dy = 1 / texSize;
  63629. var fy = 0;
  63630. for (var y = 0; y < texSize; y++) {
  63631. var xv1 = faceData[0];
  63632. var xv2 = faceData[2];
  63633. for (var x = 0; x < texSize; x++) {
  63634. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  63635. v.normalize();
  63636. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  63637. // 3 channels per pixels
  63638. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  63639. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  63640. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  63641. xv1 = xv1.add(rotDX1);
  63642. xv2 = xv2.add(rotDX2);
  63643. }
  63644. fy += dy;
  63645. }
  63646. return textureArray;
  63647. };
  63648. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  63649. var theta = Math.atan2(vDir.z, vDir.x);
  63650. var phi = Math.acos(vDir.y);
  63651. while (theta < -Math.PI)
  63652. theta += 2 * Math.PI;
  63653. while (theta > Math.PI)
  63654. theta -= 2 * Math.PI;
  63655. var dx = theta / Math.PI;
  63656. var dy = phi / Math.PI;
  63657. // recenter.
  63658. dx = dx * 0.5 + 0.5;
  63659. var px = Math.round(dx * inputWidth);
  63660. if (px < 0)
  63661. px = 0;
  63662. else if (px >= inputWidth)
  63663. px = inputWidth - 1;
  63664. var py = Math.round(dy * inputHeight);
  63665. if (py < 0)
  63666. py = 0;
  63667. else if (py >= inputHeight)
  63668. py = inputHeight - 1;
  63669. var inputY = (inputHeight - py - 1);
  63670. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  63671. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  63672. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  63673. return {
  63674. r: r,
  63675. g: g,
  63676. b: b
  63677. };
  63678. };
  63679. PanoramaToCubeMapTools.FACE_FRONT = [
  63680. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  63681. new BABYLON.Vector3(1.0, -1.0, -1.0),
  63682. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  63683. new BABYLON.Vector3(1.0, 1.0, -1.0)
  63684. ];
  63685. PanoramaToCubeMapTools.FACE_BACK = [
  63686. new BABYLON.Vector3(1.0, -1.0, 1.0),
  63687. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  63688. new BABYLON.Vector3(1.0, 1.0, 1.0),
  63689. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  63690. ];
  63691. PanoramaToCubeMapTools.FACE_RIGHT = [
  63692. new BABYLON.Vector3(1.0, -1.0, -1.0),
  63693. new BABYLON.Vector3(1.0, -1.0, 1.0),
  63694. new BABYLON.Vector3(1.0, 1.0, -1.0),
  63695. new BABYLON.Vector3(1.0, 1.0, 1.0)
  63696. ];
  63697. PanoramaToCubeMapTools.FACE_LEFT = [
  63698. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  63699. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  63700. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  63701. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  63702. ];
  63703. PanoramaToCubeMapTools.FACE_DOWN = [
  63704. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  63705. new BABYLON.Vector3(1.0, 1.0, -1.0),
  63706. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  63707. new BABYLON.Vector3(1.0, 1.0, 1.0)
  63708. ];
  63709. PanoramaToCubeMapTools.FACE_UP = [
  63710. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  63711. new BABYLON.Vector3(1.0, -1.0, 1.0),
  63712. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  63713. new BABYLON.Vector3(1.0, -1.0, -1.0)
  63714. ];
  63715. return PanoramaToCubeMapTools;
  63716. }());
  63717. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  63718. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  63719. })(BABYLON || (BABYLON = {}));
  63720. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  63721. var BABYLON;
  63722. (function (BABYLON) {
  63723. var Internals;
  63724. (function (Internals) {
  63725. ;
  63726. /**
  63727. * This groups tools to convert HDR texture to native colors array.
  63728. */
  63729. var HDRTools = /** @class */ (function () {
  63730. function HDRTools() {
  63731. }
  63732. HDRTools.Ldexp = function (mantissa, exponent) {
  63733. if (exponent > 1023) {
  63734. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  63735. }
  63736. if (exponent < -1074) {
  63737. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  63738. }
  63739. return mantissa * Math.pow(2, exponent);
  63740. };
  63741. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  63742. if (exponent > 0) {
  63743. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  63744. float32array[index + 0] = red * exponent;
  63745. float32array[index + 1] = green * exponent;
  63746. float32array[index + 2] = blue * exponent;
  63747. }
  63748. else {
  63749. float32array[index + 0] = 0;
  63750. float32array[index + 1] = 0;
  63751. float32array[index + 2] = 0;
  63752. }
  63753. };
  63754. HDRTools.readStringLine = function (uint8array, startIndex) {
  63755. var line = "";
  63756. var character = "";
  63757. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  63758. character = String.fromCharCode(uint8array[i]);
  63759. if (character == "\n") {
  63760. break;
  63761. }
  63762. line += character;
  63763. }
  63764. return line;
  63765. };
  63766. /**
  63767. * Reads header information from an RGBE texture stored in a native array.
  63768. * More information on this format are available here:
  63769. * https://en.wikipedia.org/wiki/RGBE_image_format
  63770. *
  63771. * @param uint8array The binary file stored in native array.
  63772. * @return The header information.
  63773. */
  63774. HDRTools.RGBE_ReadHeader = function (uint8array) {
  63775. var height = 0;
  63776. var width = 0;
  63777. var line = this.readStringLine(uint8array, 0);
  63778. if (line[0] != '#' || line[1] != '?') {
  63779. throw "Bad HDR Format.";
  63780. }
  63781. var endOfHeader = false;
  63782. var findFormat = false;
  63783. var lineIndex = 0;
  63784. do {
  63785. lineIndex += (line.length + 1);
  63786. line = this.readStringLine(uint8array, lineIndex);
  63787. if (line == "FORMAT=32-bit_rle_rgbe") {
  63788. findFormat = true;
  63789. }
  63790. else if (line.length == 0) {
  63791. endOfHeader = true;
  63792. }
  63793. } while (!endOfHeader);
  63794. if (!findFormat) {
  63795. throw "HDR Bad header format, unsupported FORMAT";
  63796. }
  63797. lineIndex += (line.length + 1);
  63798. line = this.readStringLine(uint8array, lineIndex);
  63799. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  63800. var match = sizeRegexp.exec(line);
  63801. // TODO. Support +Y and -X if needed.
  63802. if (!match || match.length < 3) {
  63803. throw "HDR Bad header format, no size";
  63804. }
  63805. width = parseInt(match[2]);
  63806. height = parseInt(match[1]);
  63807. if (width < 8 || width > 0x7fff) {
  63808. throw "HDR Bad header format, unsupported size";
  63809. }
  63810. lineIndex += (line.length + 1);
  63811. return {
  63812. height: height,
  63813. width: width,
  63814. dataPosition: lineIndex
  63815. };
  63816. };
  63817. /**
  63818. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  63819. * This RGBE texture needs to store the information as a panorama.
  63820. *
  63821. * More information on this format are available here:
  63822. * https://en.wikipedia.org/wiki/RGBE_image_format
  63823. *
  63824. * @param buffer The binary file stored in an array buffer.
  63825. * @param size The expected size of the extracted cubemap.
  63826. * @return The Cube Map information.
  63827. */
  63828. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  63829. var uint8array = new Uint8Array(buffer);
  63830. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  63831. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  63832. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  63833. return cubeMapData;
  63834. };
  63835. /**
  63836. * Returns the pixels data extracted from an RGBE texture.
  63837. * This pixels will be stored left to right up to down in the R G B order in one array.
  63838. *
  63839. * More information on this format are available here:
  63840. * https://en.wikipedia.org/wiki/RGBE_image_format
  63841. *
  63842. * @param uint8array The binary file stored in an array buffer.
  63843. * @param hdrInfo The header information of the file.
  63844. * @return The pixels data in RGB right to left up to down order.
  63845. */
  63846. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  63847. // Keep for multi format supports.
  63848. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  63849. };
  63850. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  63851. var num_scanlines = hdrInfo.height;
  63852. var scanline_width = hdrInfo.width;
  63853. var a, b, c, d, count;
  63854. var dataIndex = hdrInfo.dataPosition;
  63855. var index = 0, endIndex = 0, i = 0;
  63856. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  63857. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  63858. // 3 channels of 4 bytes per pixel in float.
  63859. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  63860. var resultArray = new Float32Array(resultBuffer);
  63861. // read in each successive scanline
  63862. while (num_scanlines > 0) {
  63863. a = uint8array[dataIndex++];
  63864. b = uint8array[dataIndex++];
  63865. c = uint8array[dataIndex++];
  63866. d = uint8array[dataIndex++];
  63867. if (a != 2 || b != 2 || (c & 0x80)) {
  63868. // this file is not run length encoded
  63869. throw "HDR Bad header format, not RLE";
  63870. }
  63871. if (((c << 8) | d) != scanline_width) {
  63872. throw "HDR Bad header format, wrong scan line width";
  63873. }
  63874. index = 0;
  63875. // read each of the four channels for the scanline into the buffer
  63876. for (i = 0; i < 4; i++) {
  63877. endIndex = (i + 1) * scanline_width;
  63878. while (index < endIndex) {
  63879. a = uint8array[dataIndex++];
  63880. b = uint8array[dataIndex++];
  63881. if (a > 128) {
  63882. // a run of the same value
  63883. count = a - 128;
  63884. if ((count == 0) || (count > endIndex - index)) {
  63885. throw "HDR Bad Format, bad scanline data (run)";
  63886. }
  63887. while (count-- > 0) {
  63888. scanLineArray[index++] = b;
  63889. }
  63890. }
  63891. else {
  63892. // a non-run
  63893. count = a;
  63894. if ((count == 0) || (count > endIndex - index)) {
  63895. throw "HDR Bad Format, bad scanline data (non-run)";
  63896. }
  63897. scanLineArray[index++] = b;
  63898. if (--count > 0) {
  63899. for (var j = 0; j < count; j++) {
  63900. scanLineArray[index++] = uint8array[dataIndex++];
  63901. }
  63902. }
  63903. }
  63904. }
  63905. }
  63906. // now convert data from buffer into floats
  63907. for (i = 0; i < scanline_width; i++) {
  63908. a = scanLineArray[i];
  63909. b = scanLineArray[i + scanline_width];
  63910. c = scanLineArray[i + 2 * scanline_width];
  63911. d = scanLineArray[i + 3 * scanline_width];
  63912. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  63913. }
  63914. num_scanlines--;
  63915. }
  63916. return resultArray;
  63917. };
  63918. return HDRTools;
  63919. }());
  63920. Internals.HDRTools = HDRTools;
  63921. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  63922. })(BABYLON || (BABYLON = {}));
  63923. //# sourceMappingURL=babylon.hdr.js.map
  63924. var BABYLON;
  63925. (function (BABYLON) {
  63926. /**
  63927. * This represents a texture coming from an HDR input.
  63928. *
  63929. * The only supported format is currently panorama picture stored in RGBE format.
  63930. * Example of such files can be found on HDRLib: http://hdrlib.com/
  63931. */
  63932. var HDRCubeTexture = /** @class */ (function (_super) {
  63933. __extends(HDRCubeTexture, _super);
  63934. /**
  63935. * Instantiates an HDRTexture from the following parameters.
  63936. *
  63937. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  63938. * @param scene The scene the texture will be used in
  63939. * @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.
  63940. * @param noMipmap Forces to not generate the mipmap if true
  63941. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  63942. * @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)
  63943. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  63944. */
  63945. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  63946. if (noMipmap === void 0) { noMipmap = false; }
  63947. if (generateHarmonics === void 0) { generateHarmonics = true; }
  63948. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  63949. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  63950. if (onLoad === void 0) { onLoad = null; }
  63951. if (onError === void 0) { onError = null; }
  63952. var _this = _super.call(this, scene) || this;
  63953. _this._useInGammaSpace = false;
  63954. _this._generateHarmonics = true;
  63955. _this._isBABYLONPreprocessed = false;
  63956. _this._onLoad = null;
  63957. _this._onError = null;
  63958. /**
  63959. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  63960. */
  63961. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63962. /**
  63963. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  63964. * This is usefull at run time to apply the good shader.
  63965. */
  63966. _this.isPMREM = false;
  63967. _this._isBlocking = true;
  63968. if (!url) {
  63969. return _this;
  63970. }
  63971. _this.name = url;
  63972. _this.url = url;
  63973. _this.hasAlpha = false;
  63974. _this.isCube = true;
  63975. _this._textureMatrix = BABYLON.Matrix.Identity();
  63976. _this._onLoad = onLoad;
  63977. _this._onError = onError;
  63978. _this.gammaSpace = false;
  63979. var caps = scene.getEngine().getCaps();
  63980. if (size) {
  63981. _this._isBABYLONPreprocessed = false;
  63982. _this._noMipmap = noMipmap;
  63983. _this._size = size;
  63984. _this._useInGammaSpace = useInGammaSpace;
  63985. _this._usePMREMGenerator = usePMREMGenerator &&
  63986. caps.textureLOD &&
  63987. caps.textureFloat &&
  63988. !_this._useInGammaSpace;
  63989. }
  63990. else {
  63991. _this._isBABYLONPreprocessed = true;
  63992. _this._noMipmap = false;
  63993. _this._useInGammaSpace = false;
  63994. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  63995. !_this._useInGammaSpace;
  63996. }
  63997. _this.isPMREM = _this._usePMREMGenerator;
  63998. _this._texture = _this._getFromCache(url, _this._noMipmap);
  63999. if (!_this._texture) {
  64000. if (!scene.useDelayedTextureLoading) {
  64001. _this.loadTexture();
  64002. }
  64003. else {
  64004. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  64005. }
  64006. }
  64007. return _this;
  64008. }
  64009. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  64010. /**
  64011. * Gets wether or not the texture is blocking during loading.
  64012. */
  64013. get: function () {
  64014. return this._isBlocking;
  64015. },
  64016. /**
  64017. * Sets wether or not the texture is blocking during loading.
  64018. */
  64019. set: function (value) {
  64020. this._isBlocking = value;
  64021. },
  64022. enumerable: true,
  64023. configurable: true
  64024. });
  64025. /**
  64026. * Occurs when the file is a preprocessed .babylon.hdr file.
  64027. */
  64028. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  64029. var _this = this;
  64030. var mipLevels = 0;
  64031. var floatArrayView = null;
  64032. var scene = this.getScene();
  64033. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  64034. var mips = new Array();
  64035. if (!floatArrayView) {
  64036. return mips;
  64037. }
  64038. var startIndex = 30;
  64039. for (var level = 0; level < mipLevels; level++) {
  64040. mips.push([]);
  64041. // Fill each pixel of the mip level.
  64042. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  64043. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  64044. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  64045. mips[level].push(faceData);
  64046. startIndex += faceSize;
  64047. }
  64048. }
  64049. return mips;
  64050. } : null;
  64051. var callback = function (buffer) {
  64052. var scene = _this.getScene();
  64053. if (!scene) {
  64054. return null;
  64055. }
  64056. // Create Native Array Views
  64057. var intArrayView = new Int32Array(buffer);
  64058. floatArrayView = new Float32Array(buffer);
  64059. // Fill header.
  64060. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  64061. _this._size = intArrayView[1]; // CubeMap max mip face size.
  64062. // Update Texture Information.
  64063. if (!_this._texture) {
  64064. return null;
  64065. }
  64066. _this._texture.updateSize(_this._size, _this._size);
  64067. // Fill polynomial information.
  64068. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  64069. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  64070. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  64071. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  64072. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  64073. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  64074. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  64075. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  64076. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  64077. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  64078. _this.sphericalPolynomial = sphericalPolynomial;
  64079. // Fill pixel data.
  64080. mipLevels = intArrayView[29]; // Number of mip levels.
  64081. var startIndex = 30;
  64082. var data = [];
  64083. var faceSize = Math.pow(_this._size, 2) * 3;
  64084. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  64085. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  64086. startIndex += faceSize;
  64087. }
  64088. var results = [];
  64089. var byteArray = null;
  64090. // Push each faces.
  64091. for (var k = 0; k < 6; k++) {
  64092. var dataFace = null;
  64093. // To be deprecated.
  64094. if (version === 1) {
  64095. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  64096. dataFace = data[j];
  64097. }
  64098. // If special cases.
  64099. if (!mipmapGenerator && dataFace) {
  64100. if (!scene.getEngine().getCaps().textureFloat) {
  64101. // 3 channels of 1 bytes per pixel in bytes.
  64102. var byteBuffer = new ArrayBuffer(faceSize);
  64103. byteArray = new Uint8Array(byteBuffer);
  64104. }
  64105. for (var i = 0; i < _this._size * _this._size; i++) {
  64106. // Put in gamma space if requested.
  64107. if (_this._useInGammaSpace) {
  64108. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  64109. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  64110. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  64111. }
  64112. // Convert to int texture for fallback.
  64113. if (byteArray) {
  64114. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  64115. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  64116. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  64117. // May use luminance instead if the result is not accurate.
  64118. var max = Math.max(Math.max(r, g), b);
  64119. if (max > 255) {
  64120. var scale = 255 / max;
  64121. r *= scale;
  64122. g *= scale;
  64123. b *= scale;
  64124. }
  64125. byteArray[(i * 3) + 0] = r;
  64126. byteArray[(i * 3) + 1] = g;
  64127. byteArray[(i * 3) + 2] = b;
  64128. }
  64129. }
  64130. }
  64131. // Fill the array accordingly.
  64132. if (byteArray) {
  64133. results.push(byteArray);
  64134. }
  64135. else {
  64136. results.push(dataFace);
  64137. }
  64138. }
  64139. return results;
  64140. };
  64141. if (scene) {
  64142. 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);
  64143. }
  64144. };
  64145. /**
  64146. * Occurs when the file is raw .hdr file.
  64147. */
  64148. HDRCubeTexture.prototype.loadHDRTexture = function () {
  64149. var _this = this;
  64150. var callback = function (buffer) {
  64151. var scene = _this.getScene();
  64152. if (!scene) {
  64153. return null;
  64154. }
  64155. // Extract the raw linear data.
  64156. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  64157. // Generate harmonics if needed.
  64158. if (_this._generateHarmonics) {
  64159. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  64160. _this.sphericalPolynomial = sphericalPolynomial;
  64161. }
  64162. var results = [];
  64163. var byteArray = null;
  64164. // Push each faces.
  64165. for (var j = 0; j < 6; j++) {
  64166. // Create uintarray fallback.
  64167. if (!scene.getEngine().getCaps().textureFloat) {
  64168. // 3 channels of 1 bytes per pixel in bytes.
  64169. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  64170. byteArray = new Uint8Array(byteBuffer);
  64171. }
  64172. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  64173. // If special cases.
  64174. if (_this._useInGammaSpace || byteArray) {
  64175. for (var i = 0; i < _this._size * _this._size; i++) {
  64176. // Put in gamma space if requested.
  64177. if (_this._useInGammaSpace) {
  64178. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  64179. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  64180. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  64181. }
  64182. // Convert to int texture for fallback.
  64183. if (byteArray) {
  64184. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  64185. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  64186. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  64187. // May use luminance instead if the result is not accurate.
  64188. var max = Math.max(Math.max(r, g), b);
  64189. if (max > 255) {
  64190. var scale = 255 / max;
  64191. r *= scale;
  64192. g *= scale;
  64193. b *= scale;
  64194. }
  64195. byteArray[(i * 3) + 0] = r;
  64196. byteArray[(i * 3) + 1] = g;
  64197. byteArray[(i * 3) + 2] = b;
  64198. }
  64199. }
  64200. }
  64201. if (byteArray) {
  64202. results.push(byteArray);
  64203. }
  64204. else {
  64205. results.push(dataFace);
  64206. }
  64207. }
  64208. return results;
  64209. };
  64210. var mipmapGenerator = null;
  64211. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  64212. // if (!this._noMipmap &&
  64213. // this._usePMREMGenerator) {
  64214. // mipmapGenerator = (data: ArrayBufferView[]) => {
  64215. // // Custom setup of the generator matching with the PBR shader values.
  64216. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  64217. // this._size,
  64218. // this._size,
  64219. // 0,
  64220. // 3,
  64221. // this.getScene().getEngine().getCaps().textureFloat,
  64222. // 2048,
  64223. // 0.25,
  64224. // false,
  64225. // true);
  64226. // return generator.filterCubeMap();
  64227. // };
  64228. // }
  64229. var scene = this.getScene();
  64230. if (scene) {
  64231. 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);
  64232. }
  64233. };
  64234. /**
  64235. * Starts the loading process of the texture.
  64236. */
  64237. HDRCubeTexture.prototype.loadTexture = function () {
  64238. if (this._isBABYLONPreprocessed) {
  64239. this.loadBabylonTexture();
  64240. }
  64241. else {
  64242. this.loadHDRTexture();
  64243. }
  64244. };
  64245. HDRCubeTexture.prototype.clone = function () {
  64246. var scene = this.getScene();
  64247. if (!scene) {
  64248. return this;
  64249. }
  64250. var size = (this._isBABYLONPreprocessed ? null : this._size);
  64251. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  64252. // Base texture
  64253. newTexture.level = this.level;
  64254. newTexture.wrapU = this.wrapU;
  64255. newTexture.wrapV = this.wrapV;
  64256. newTexture.coordinatesIndex = this.coordinatesIndex;
  64257. newTexture.coordinatesMode = this.coordinatesMode;
  64258. return newTexture;
  64259. };
  64260. // Methods
  64261. HDRCubeTexture.prototype.delayLoad = function () {
  64262. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  64263. return;
  64264. }
  64265. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  64266. this._texture = this._getFromCache(this.url, this._noMipmap);
  64267. if (!this._texture) {
  64268. this.loadTexture();
  64269. }
  64270. };
  64271. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  64272. return this._textureMatrix;
  64273. };
  64274. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  64275. this._textureMatrix = value;
  64276. };
  64277. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  64278. var texture = null;
  64279. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  64280. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  64281. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  64282. texture.name = parsedTexture.name;
  64283. texture.hasAlpha = parsedTexture.hasAlpha;
  64284. texture.level = parsedTexture.level;
  64285. texture.coordinatesMode = parsedTexture.coordinatesMode;
  64286. texture.isBlocking = parsedTexture.isBlocking;
  64287. }
  64288. return texture;
  64289. };
  64290. HDRCubeTexture.prototype.serialize = function () {
  64291. if (!this.name) {
  64292. return null;
  64293. }
  64294. var serializationObject = {};
  64295. serializationObject.name = this.name;
  64296. serializationObject.hasAlpha = this.hasAlpha;
  64297. serializationObject.isCube = true;
  64298. serializationObject.level = this.level;
  64299. serializationObject.size = this._size;
  64300. serializationObject.coordinatesMode = this.coordinatesMode;
  64301. serializationObject.useInGammaSpace = this._useInGammaSpace;
  64302. serializationObject.generateHarmonics = this._generateHarmonics;
  64303. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  64304. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  64305. serializationObject.customType = "BABYLON.HDRCubeTexture";
  64306. serializationObject.noMipmap = this._noMipmap;
  64307. serializationObject.isBlocking = this._isBlocking;
  64308. return serializationObject;
  64309. };
  64310. /**
  64311. * Saves as a file the data contained in the texture in a binary format.
  64312. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  64313. * as the spherical used in the lighting.
  64314. * @param url The HDR file url.
  64315. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  64316. * @param onError Method called if any error happens during download.
  64317. * @return The packed binary data.
  64318. */
  64319. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  64320. if (onError === void 0) { onError = null; }
  64321. var callback = function (buffer) {
  64322. var data = new Blob([buffer], { type: 'application/octet-stream' });
  64323. // Returns a URL you can use as a href.
  64324. var objUrl = window.URL.createObjectURL(data);
  64325. // Simulates a link to it and click to dowload.
  64326. var a = document.createElement("a");
  64327. document.body.appendChild(a);
  64328. a.style.display = "none";
  64329. a.href = objUrl;
  64330. a.download = "envmap.babylon.hdr";
  64331. a.click();
  64332. };
  64333. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  64334. };
  64335. /**
  64336. * Serializes the data contained in the texture in a binary format.
  64337. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  64338. * as the spherical used in the lighting.
  64339. * @param url The HDR file url.
  64340. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  64341. * @param onError Method called if any error happens during download.
  64342. * @return The packed binary data.
  64343. */
  64344. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  64345. if (onError === void 0) { onError = null; }
  64346. // Needs the url tho create the texture.
  64347. if (!url) {
  64348. return;
  64349. }
  64350. // Check Power of two size.
  64351. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  64352. return;
  64353. }
  64354. // Coming Back in 3.x.
  64355. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  64356. };
  64357. HDRCubeTexture._facesMapping = [
  64358. "right",
  64359. "left",
  64360. "up",
  64361. "down",
  64362. "front",
  64363. "back"
  64364. ];
  64365. return HDRCubeTexture;
  64366. }(BABYLON.BaseTexture));
  64367. BABYLON.HDRCubeTexture = HDRCubeTexture;
  64368. })(BABYLON || (BABYLON = {}));
  64369. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  64370. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  64371. // Huge respect for a such great lib.
  64372. // Earcut license:
  64373. // Copyright (c) 2016, Mapbox
  64374. //
  64375. // Permission to use, copy, modify, and/or distribute this software for any purpose
  64376. // with or without fee is hereby granted, provided that the above copyright notice
  64377. // and this permission notice appear in all copies.
  64378. //
  64379. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  64380. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  64381. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  64382. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  64383. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  64384. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  64385. // THIS SOFTWARE.
  64386. var Earcut;
  64387. (function (Earcut) {
  64388. /**
  64389. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  64390. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  64391. * @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).
  64392. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  64393. */
  64394. function earcut(data, holeIndices, dim) {
  64395. dim = dim || 2;
  64396. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  64397. if (!outerNode)
  64398. return triangles;
  64399. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  64400. if (hasHoles)
  64401. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  64402. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  64403. if (data.length > 80 * dim) {
  64404. minX = maxX = data[0];
  64405. minY = maxY = data[1];
  64406. for (var i = dim; i < outerLen; i += dim) {
  64407. x = data[i];
  64408. y = data[i + 1];
  64409. if (x < minX)
  64410. minX = x;
  64411. if (y < minY)
  64412. minY = y;
  64413. if (x > maxX)
  64414. maxX = x;
  64415. if (y > maxY)
  64416. maxY = y;
  64417. }
  64418. // minX, minY and size are later used to transform coords into integers for z-order calculation
  64419. size = Math.max(maxX - minX, maxY - minY);
  64420. }
  64421. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  64422. return triangles;
  64423. }
  64424. Earcut.earcut = earcut;
  64425. var Node = /** @class */ (function () {
  64426. function Node(i, x, y) {
  64427. this.i = i;
  64428. this.x = x;
  64429. this.y = y;
  64430. this.prev = null;
  64431. this.next = null;
  64432. this.z = null;
  64433. this.prevZ = null;
  64434. this.nextZ = null;
  64435. this.steiner = false;
  64436. }
  64437. return Node;
  64438. }());
  64439. // create a circular doubly linked list from polygon points in the specified winding order
  64440. function linkedList(data, start, end, dim, clockwise) {
  64441. var i, last = null;
  64442. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  64443. for (i = start; i < end; i += dim)
  64444. last = insertNode(i, data[i], data[i + 1], last);
  64445. }
  64446. else {
  64447. for (i = end - dim; i >= start; i -= dim)
  64448. last = insertNode(i, data[i], data[i + 1], last);
  64449. }
  64450. if (last && equals(last, last.next)) {
  64451. removeNode(last);
  64452. last = last.next;
  64453. }
  64454. return last;
  64455. }
  64456. // eliminate colinear or duplicate points
  64457. function filterPoints(start, end) {
  64458. if (!start)
  64459. return start;
  64460. if (!end)
  64461. end = start;
  64462. var p = start, again;
  64463. do {
  64464. again = false;
  64465. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  64466. removeNode(p);
  64467. p = end = p.prev;
  64468. if (p === p.next)
  64469. return undefined;
  64470. again = true;
  64471. }
  64472. else {
  64473. p = p.next;
  64474. }
  64475. } while (again || p !== end);
  64476. return end;
  64477. }
  64478. // main ear slicing loop which triangulates a polygon (given as a linked list)
  64479. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  64480. if (!ear)
  64481. return;
  64482. // interlink polygon nodes in z-order
  64483. if (!pass && size)
  64484. indexCurve(ear, minX, minY, size);
  64485. var stop = ear, prev, next;
  64486. // iterate through ears, slicing them one by one
  64487. while (ear.prev !== ear.next) {
  64488. prev = ear.prev;
  64489. next = ear.next;
  64490. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  64491. // cut off the triangle
  64492. triangles.push(prev.i / dim);
  64493. triangles.push(ear.i / dim);
  64494. triangles.push(next.i / dim);
  64495. removeNode(ear);
  64496. // skipping the next vertice leads to less sliver triangles
  64497. ear = next.next;
  64498. stop = next.next;
  64499. continue;
  64500. }
  64501. ear = next;
  64502. // if we looped through the whole remaining polygon and can't find any more ears
  64503. if (ear === stop) {
  64504. // try filtering points and slicing again
  64505. if (!pass) {
  64506. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  64507. // if this didn't work, try curing all small self-intersections locally
  64508. }
  64509. else if (pass === 1) {
  64510. ear = cureLocalIntersections(ear, triangles, dim);
  64511. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  64512. // as a last resort, try splitting the remaining polygon into two
  64513. }
  64514. else if (pass === 2) {
  64515. splitEarcut(ear, triangles, dim, minX, minY, size);
  64516. }
  64517. break;
  64518. }
  64519. }
  64520. }
  64521. // check whether a polygon node forms a valid ear with adjacent nodes
  64522. function isEar(ear) {
  64523. var a = ear.prev, b = ear, c = ear.next;
  64524. if (area(a, b, c) >= 0)
  64525. return false; // reflex, can't be an ear
  64526. // now make sure we don't have other points inside the potential ear
  64527. var p = ear.next.next;
  64528. while (p !== ear.prev) {
  64529. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  64530. area(p.prev, p, p.next) >= 0)
  64531. return false;
  64532. p = p.next;
  64533. }
  64534. return true;
  64535. }
  64536. function isEarHashed(ear, minX, minY, size) {
  64537. var a = ear.prev, b = ear, c = ear.next;
  64538. if (area(a, b, c) >= 0)
  64539. return false; // reflex, can't be an ear
  64540. // triangle bbox; min & max are calculated like this for speed
  64541. 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);
  64542. // z-order range for the current triangle bbox;
  64543. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  64544. // first look for points inside the triangle in increasing z-order
  64545. var p = ear.nextZ;
  64546. while (p && p.z <= maxZ) {
  64547. if (p !== ear.prev &&
  64548. p !== ear.next &&
  64549. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  64550. area(p.prev, p, p.next) >= 0)
  64551. return false;
  64552. p = p.nextZ;
  64553. }
  64554. // then look for points in decreasing z-order
  64555. p = ear.prevZ;
  64556. while (p && p.z >= minZ) {
  64557. if (p !== ear.prev &&
  64558. p !== ear.next &&
  64559. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  64560. area(p.prev, p, p.next) >= 0)
  64561. return false;
  64562. p = p.prevZ;
  64563. }
  64564. return true;
  64565. }
  64566. // go through all polygon nodes and cure small local self-intersections
  64567. function cureLocalIntersections(start, triangles, dim) {
  64568. var p = start;
  64569. do {
  64570. var a = p.prev, b = p.next.next;
  64571. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  64572. triangles.push(a.i / dim);
  64573. triangles.push(p.i / dim);
  64574. triangles.push(b.i / dim);
  64575. // remove two nodes involved
  64576. removeNode(p);
  64577. removeNode(p.next);
  64578. p = start = b;
  64579. }
  64580. p = p.next;
  64581. } while (p !== start);
  64582. return p;
  64583. }
  64584. // try splitting polygon into two and triangulate them independently
  64585. function splitEarcut(start, triangles, dim, minX, minY, size) {
  64586. // look for a valid diagonal that divides the polygon into two
  64587. var a = start;
  64588. do {
  64589. var b = a.next.next;
  64590. while (b !== a.prev) {
  64591. if (a.i !== b.i && isValidDiagonal(a, b)) {
  64592. // split the polygon in two by the diagonal
  64593. var c = splitPolygon(a, b);
  64594. // filter colinear points around the cuts
  64595. a = filterPoints(a, a.next);
  64596. c = filterPoints(c, c.next);
  64597. // run earcut on each half
  64598. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  64599. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  64600. return;
  64601. }
  64602. b = b.next;
  64603. }
  64604. a = a.next;
  64605. } while (a !== start);
  64606. }
  64607. // link every hole into the outer loop, producing a single-ring polygon without holes
  64608. function eliminateHoles(data, holeIndices, outerNode, dim) {
  64609. var queue = [], i, len, start, end, list;
  64610. for (i = 0, len = holeIndices.length; i < len; i++) {
  64611. start = holeIndices[i] * dim;
  64612. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  64613. list = linkedList(data, start, end, dim, false);
  64614. if (list === list.next)
  64615. list.steiner = true;
  64616. queue.push(getLeftmost(list));
  64617. }
  64618. queue.sort(compareX);
  64619. // process holes from left to right
  64620. for (i = 0; i < queue.length; i++) {
  64621. eliminateHole(queue[i], outerNode);
  64622. outerNode = filterPoints(outerNode, outerNode.next);
  64623. }
  64624. return outerNode;
  64625. }
  64626. function compareX(a, b) {
  64627. return a.x - b.x;
  64628. }
  64629. // find a bridge between vertices that connects hole with an outer ring and and link it
  64630. function eliminateHole(hole, outerNode) {
  64631. outerNode = findHoleBridge(hole, outerNode);
  64632. if (outerNode) {
  64633. var b = splitPolygon(outerNode, hole);
  64634. filterPoints(b, b.next);
  64635. }
  64636. }
  64637. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  64638. function findHoleBridge(hole, outerNode) {
  64639. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  64640. // find a segment intersected by a ray from the hole's leftmost point to the left;
  64641. // segment's endpoint with lesser x will be potential connection point
  64642. do {
  64643. if (hy <= p.y && hy >= p.next.y) {
  64644. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  64645. if (x <= hx && x > qx) {
  64646. qx = x;
  64647. if (x === hx) {
  64648. if (hy === p.y)
  64649. return p;
  64650. if (hy === p.next.y)
  64651. return p.next;
  64652. }
  64653. m = p.x < p.next.x ? p : p.next;
  64654. }
  64655. }
  64656. p = p.next;
  64657. } while (p !== outerNode);
  64658. if (!m)
  64659. return null;
  64660. if (hx === qx)
  64661. return m.prev; // hole touches outer segment; pick lower endpoint
  64662. // look for points inside the triangle of hole point, segment intersection and endpoint;
  64663. // if there are no points found, we have a valid connection;
  64664. // otherwise choose the point of the minimum angle with the ray as connection point
  64665. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  64666. p = m.next;
  64667. while (p !== stop) {
  64668. if (hx >= p.x &&
  64669. p.x >= mx &&
  64670. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  64671. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  64672. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  64673. m = p;
  64674. tanMin = tan;
  64675. }
  64676. }
  64677. p = p.next;
  64678. }
  64679. return m;
  64680. }
  64681. // interlink polygon nodes in z-order
  64682. function indexCurve(start, minX, minY, size) {
  64683. var p = start;
  64684. do {
  64685. if (p.z === null)
  64686. p.z = zOrder(p.x, p.y, minX, minY, size);
  64687. p.prevZ = p.prev;
  64688. p.nextZ = p.next;
  64689. p = p.next;
  64690. } while (p !== start);
  64691. p.prevZ.nextZ = null;
  64692. p.prevZ = null;
  64693. sortLinked(p);
  64694. }
  64695. // Simon Tatham's linked list merge sort algorithm
  64696. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  64697. function sortLinked(list) {
  64698. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  64699. do {
  64700. p = list;
  64701. list = null;
  64702. tail = null;
  64703. numMerges = 0;
  64704. while (p) {
  64705. numMerges++;
  64706. q = p;
  64707. pSize = 0;
  64708. for (i = 0; i < inSize; i++) {
  64709. pSize++;
  64710. q = q.nextZ;
  64711. if (!q)
  64712. break;
  64713. }
  64714. qSize = inSize;
  64715. while (pSize > 0 || (qSize > 0 && q)) {
  64716. if (pSize === 0) {
  64717. e = q;
  64718. q = q.nextZ;
  64719. qSize--;
  64720. }
  64721. else if (qSize === 0 || !q) {
  64722. e = p;
  64723. p = p.nextZ;
  64724. pSize--;
  64725. }
  64726. else if (p.z <= q.z) {
  64727. e = p;
  64728. p = p.nextZ;
  64729. pSize--;
  64730. }
  64731. else {
  64732. e = q;
  64733. q = q.nextZ;
  64734. qSize--;
  64735. }
  64736. if (tail)
  64737. tail.nextZ = e;
  64738. else
  64739. list = e;
  64740. e.prevZ = tail;
  64741. tail = e;
  64742. }
  64743. p = q;
  64744. }
  64745. tail.nextZ = null;
  64746. inSize *= 2;
  64747. } while (numMerges > 1);
  64748. return list;
  64749. }
  64750. // z-order of a point given coords and size of the data bounding box
  64751. function zOrder(x, y, minX, minY, size) {
  64752. // coords are transformed into non-negative 15-bit integer range
  64753. x = 32767 * (x - minX) / size;
  64754. y = 32767 * (y - minY) / size;
  64755. x = (x | (x << 8)) & 0x00FF00FF;
  64756. x = (x | (x << 4)) & 0x0F0F0F0F;
  64757. x = (x | (x << 2)) & 0x33333333;
  64758. x = (x | (x << 1)) & 0x55555555;
  64759. y = (y | (y << 8)) & 0x00FF00FF;
  64760. y = (y | (y << 4)) & 0x0F0F0F0F;
  64761. y = (y | (y << 2)) & 0x33333333;
  64762. y = (y | (y << 1)) & 0x55555555;
  64763. return x | (y << 1);
  64764. }
  64765. // find the leftmost node of a polygon ring
  64766. function getLeftmost(start) {
  64767. var p = start, leftmost = start;
  64768. do {
  64769. if (p.x < leftmost.x)
  64770. leftmost = p;
  64771. p = p.next;
  64772. } while (p !== start);
  64773. return leftmost;
  64774. }
  64775. // check if a point lies within a convex triangle
  64776. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  64777. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  64778. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  64779. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  64780. }
  64781. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  64782. function isValidDiagonal(a, b) {
  64783. return a.next.i !== b.i &&
  64784. a.prev.i !== b.i &&
  64785. !intersectsPolygon(a, b) &&
  64786. locallyInside(a, b) &&
  64787. locallyInside(b, a) &&
  64788. middleInside(a, b);
  64789. }
  64790. // signed area of a triangle
  64791. function area(p, q, r) {
  64792. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  64793. }
  64794. // check if two points are equal
  64795. function equals(p1, p2) {
  64796. return p1.x === p2.x && p1.y === p2.y;
  64797. }
  64798. // check if two segments intersect
  64799. function intersects(p1, q1, p2, q2) {
  64800. if ((equals(p1, q1) && equals(p2, q2)) ||
  64801. (equals(p1, q2) && equals(p2, q1)))
  64802. return true;
  64803. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  64804. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  64805. }
  64806. // check if a polygon diagonal intersects any polygon segments
  64807. function intersectsPolygon(a, b) {
  64808. var p = a;
  64809. do {
  64810. if (p.i !== a.i &&
  64811. p.next.i !== a.i &&
  64812. p.i !== b.i &&
  64813. p.next.i !== b.i &&
  64814. intersects(p, p.next, a, b))
  64815. return true;
  64816. p = p.next;
  64817. } while (p !== a);
  64818. return false;
  64819. }
  64820. // check if a polygon diagonal is locally inside the polygon
  64821. function locallyInside(a, b) {
  64822. return area(a.prev, a, a.next) < 0
  64823. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  64824. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  64825. }
  64826. // check if the middle point of a polygon diagonal is inside the polygon
  64827. function middleInside(a, b) {
  64828. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  64829. do {
  64830. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  64831. inside = !inside;
  64832. p = p.next;
  64833. } while (p !== a);
  64834. return inside;
  64835. }
  64836. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  64837. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  64838. function splitPolygon(a, b) {
  64839. 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;
  64840. a.next = b;
  64841. b.prev = a;
  64842. a2.next = an;
  64843. an.prev = a2;
  64844. b2.next = a2;
  64845. a2.prev = b2;
  64846. bp.next = b2;
  64847. b2.prev = bp;
  64848. return b2;
  64849. }
  64850. // create a node and optionally link it with previous one (in a circular doubly linked list)
  64851. function insertNode(i, x, y, last) {
  64852. var p = new Node(i, x, y);
  64853. if (!last) {
  64854. p.prev = p;
  64855. p.next = p;
  64856. }
  64857. else {
  64858. p.next = last.next;
  64859. p.prev = last;
  64860. last.next.prev = p;
  64861. last.next = p;
  64862. }
  64863. return p;
  64864. }
  64865. function removeNode(p) {
  64866. p.next.prev = p.prev;
  64867. p.prev.next = p.next;
  64868. if (p.prevZ)
  64869. p.prevZ.nextZ = p.nextZ;
  64870. if (p.nextZ)
  64871. p.nextZ.prevZ = p.prevZ;
  64872. }
  64873. /**
  64874. * return a percentage difference between the polygon area and its triangulation area;
  64875. * used to verify correctness of triangulation
  64876. */
  64877. function deviation(data, holeIndices, dim, triangles) {
  64878. var hasHoles = holeIndices && holeIndices.length;
  64879. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  64880. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  64881. if (hasHoles) {
  64882. for (var i = 0, len = holeIndices.length; i < len; i++) {
  64883. var start = holeIndices[i] * dim;
  64884. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  64885. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  64886. }
  64887. }
  64888. var trianglesArea = 0;
  64889. for (i = 0; i < triangles.length; i += 3) {
  64890. var a = triangles[i] * dim;
  64891. var b = triangles[i + 1] * dim;
  64892. var c = triangles[i + 2] * dim;
  64893. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  64894. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  64895. }
  64896. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  64897. }
  64898. Earcut.deviation = deviation;
  64899. ;
  64900. function signedArea(data, start, end, dim) {
  64901. var sum = 0;
  64902. for (var i = start, j = end - dim; i < end; i += dim) {
  64903. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  64904. j = i;
  64905. }
  64906. return sum;
  64907. }
  64908. /**
  64909. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  64910. */
  64911. function flatten(data) {
  64912. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  64913. for (var i = 0; i < data.length; i++) {
  64914. for (var j = 0; j < data[i].length; j++) {
  64915. for (var d = 0; d < dim; d++)
  64916. result.vertices.push(data[i][j][d]);
  64917. }
  64918. if (i > 0) {
  64919. holeIndex += data[i - 1].length;
  64920. result.holes.push(holeIndex);
  64921. }
  64922. }
  64923. return result;
  64924. }
  64925. Earcut.flatten = flatten;
  64926. ;
  64927. })(Earcut || (Earcut = {}));
  64928. //# sourceMappingURL=babylon.earcut.js.map
  64929. var BABYLON;
  64930. (function (BABYLON) {
  64931. var IndexedVector2 = /** @class */ (function (_super) {
  64932. __extends(IndexedVector2, _super);
  64933. function IndexedVector2(original, index) {
  64934. var _this = _super.call(this, original.x, original.y) || this;
  64935. _this.index = index;
  64936. return _this;
  64937. }
  64938. return IndexedVector2;
  64939. }(BABYLON.Vector2));
  64940. var PolygonPoints = /** @class */ (function () {
  64941. function PolygonPoints() {
  64942. this.elements = new Array();
  64943. }
  64944. PolygonPoints.prototype.add = function (originalPoints) {
  64945. var _this = this;
  64946. var result = new Array();
  64947. originalPoints.forEach(function (point) {
  64948. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  64949. var newPoint = new IndexedVector2(point, _this.elements.length);
  64950. result.push(newPoint);
  64951. _this.elements.push(newPoint);
  64952. }
  64953. });
  64954. return result;
  64955. };
  64956. PolygonPoints.prototype.computeBounds = function () {
  64957. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  64958. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  64959. this.elements.forEach(function (point) {
  64960. // x
  64961. if (point.x < lmin.x) {
  64962. lmin.x = point.x;
  64963. }
  64964. else if (point.x > lmax.x) {
  64965. lmax.x = point.x;
  64966. }
  64967. // y
  64968. if (point.y < lmin.y) {
  64969. lmin.y = point.y;
  64970. }
  64971. else if (point.y > lmax.y) {
  64972. lmax.y = point.y;
  64973. }
  64974. });
  64975. return {
  64976. min: lmin,
  64977. max: lmax,
  64978. width: lmax.x - lmin.x,
  64979. height: lmax.y - lmin.y
  64980. };
  64981. };
  64982. return PolygonPoints;
  64983. }());
  64984. var Polygon = /** @class */ (function () {
  64985. function Polygon() {
  64986. }
  64987. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  64988. return [
  64989. new BABYLON.Vector2(xmin, ymin),
  64990. new BABYLON.Vector2(xmax, ymin),
  64991. new BABYLON.Vector2(xmax, ymax),
  64992. new BABYLON.Vector2(xmin, ymax)
  64993. ];
  64994. };
  64995. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  64996. if (cx === void 0) { cx = 0; }
  64997. if (cy === void 0) { cy = 0; }
  64998. if (numberOfSides === void 0) { numberOfSides = 32; }
  64999. var result = new Array();
  65000. var angle = 0;
  65001. var increment = (Math.PI * 2) / numberOfSides;
  65002. for (var i = 0; i < numberOfSides; i++) {
  65003. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  65004. angle -= increment;
  65005. }
  65006. return result;
  65007. };
  65008. Polygon.Parse = function (input) {
  65009. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  65010. var i, result = [];
  65011. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  65012. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  65013. }
  65014. return result;
  65015. };
  65016. Polygon.StartingAt = function (x, y) {
  65017. return BABYLON.Path2.StartingAt(x, y);
  65018. };
  65019. return Polygon;
  65020. }());
  65021. BABYLON.Polygon = Polygon;
  65022. var PolygonMeshBuilder = /** @class */ (function () {
  65023. function PolygonMeshBuilder(name, contours, scene) {
  65024. this._points = new PolygonPoints();
  65025. this._outlinepoints = new PolygonPoints();
  65026. this._holes = new Array();
  65027. this._epoints = new Array();
  65028. this._eholes = new Array();
  65029. this._name = name;
  65030. this._scene = scene;
  65031. var points;
  65032. if (contours instanceof BABYLON.Path2) {
  65033. points = contours.getPoints();
  65034. }
  65035. else {
  65036. points = contours;
  65037. }
  65038. this._addToepoint(points);
  65039. this._points.add(points);
  65040. this._outlinepoints.add(points);
  65041. }
  65042. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  65043. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  65044. var p = points_1[_i];
  65045. this._epoints.push(p.x, p.y);
  65046. }
  65047. };
  65048. PolygonMeshBuilder.prototype.addHole = function (hole) {
  65049. this._points.add(hole);
  65050. var holepoints = new PolygonPoints();
  65051. holepoints.add(hole);
  65052. this._holes.push(holepoints);
  65053. this._eholes.push(this._epoints.length / 2);
  65054. this._addToepoint(hole);
  65055. return this;
  65056. };
  65057. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  65058. var _this = this;
  65059. if (updatable === void 0) { updatable = false; }
  65060. if (depth === void 0) { depth = 0; }
  65061. var result = new BABYLON.Mesh(this._name, this._scene);
  65062. var normals = new Array();
  65063. var positions = new Array();
  65064. var uvs = new Array();
  65065. var bounds = this._points.computeBounds();
  65066. this._points.elements.forEach(function (p) {
  65067. normals.push(0, 1.0, 0);
  65068. positions.push(p.x, 0, p.y);
  65069. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  65070. });
  65071. var indices = new Array();
  65072. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  65073. for (var i = 0; i < res.length; i++) {
  65074. indices.push(res[i]);
  65075. }
  65076. if (depth > 0) {
  65077. var positionscount = (positions.length / 3); //get the current pointcount
  65078. this._points.elements.forEach(function (p) {
  65079. normals.push(0, -1.0, 0);
  65080. positions.push(p.x, -depth, p.y);
  65081. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  65082. });
  65083. var totalCount = indices.length;
  65084. for (var i = 0; i < totalCount; i += 3) {
  65085. var i0 = indices[i + 0];
  65086. var i1 = indices[i + 1];
  65087. var i2 = indices[i + 2];
  65088. indices.push(i2 + positionscount);
  65089. indices.push(i1 + positionscount);
  65090. indices.push(i0 + positionscount);
  65091. }
  65092. //Add the sides
  65093. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  65094. this._holes.forEach(function (hole) {
  65095. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  65096. });
  65097. }
  65098. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  65099. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  65100. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  65101. result.setIndices(indices);
  65102. return result;
  65103. };
  65104. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  65105. var StartIndex = positions.length / 3;
  65106. var ulength = 0;
  65107. for (var i = 0; i < points.elements.length; i++) {
  65108. var p = points.elements[i];
  65109. var p1;
  65110. if ((i + 1) > points.elements.length - 1) {
  65111. p1 = points.elements[0];
  65112. }
  65113. else {
  65114. p1 = points.elements[i + 1];
  65115. }
  65116. positions.push(p.x, 0, p.y);
  65117. positions.push(p.x, -depth, p.y);
  65118. positions.push(p1.x, 0, p1.y);
  65119. positions.push(p1.x, -depth, p1.y);
  65120. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  65121. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  65122. var v3 = v2.subtract(v1);
  65123. var v4 = new BABYLON.Vector3(0, 1, 0);
  65124. var vn = BABYLON.Vector3.Cross(v3, v4);
  65125. vn = vn.normalize();
  65126. uvs.push(ulength / bounds.width, 0);
  65127. uvs.push(ulength / bounds.width, 1);
  65128. ulength += v3.length();
  65129. uvs.push((ulength / bounds.width), 0);
  65130. uvs.push((ulength / bounds.width), 1);
  65131. if (!flip) {
  65132. normals.push(-vn.x, -vn.y, -vn.z);
  65133. normals.push(-vn.x, -vn.y, -vn.z);
  65134. normals.push(-vn.x, -vn.y, -vn.z);
  65135. normals.push(-vn.x, -vn.y, -vn.z);
  65136. indices.push(StartIndex);
  65137. indices.push(StartIndex + 1);
  65138. indices.push(StartIndex + 2);
  65139. indices.push(StartIndex + 1);
  65140. indices.push(StartIndex + 3);
  65141. indices.push(StartIndex + 2);
  65142. }
  65143. else {
  65144. normals.push(vn.x, vn.y, vn.z);
  65145. normals.push(vn.x, vn.y, vn.z);
  65146. normals.push(vn.x, vn.y, vn.z);
  65147. normals.push(vn.x, vn.y, vn.z);
  65148. indices.push(StartIndex);
  65149. indices.push(StartIndex + 2);
  65150. indices.push(StartIndex + 1);
  65151. indices.push(StartIndex + 1);
  65152. indices.push(StartIndex + 2);
  65153. indices.push(StartIndex + 3);
  65154. }
  65155. StartIndex += 4;
  65156. }
  65157. ;
  65158. };
  65159. return PolygonMeshBuilder;
  65160. }());
  65161. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  65162. })(BABYLON || (BABYLON = {}));
  65163. //# sourceMappingURL=babylon.polygonMesh.js.map
  65164. var BABYLON;
  65165. (function (BABYLON) {
  65166. // Unique ID when we import meshes from Babylon to CSG
  65167. var currentCSGMeshId = 0;
  65168. // # class Vertex
  65169. // Represents a vertex of a polygon. Use your own vertex class instead of this
  65170. // one to provide additional features like texture coordinates and vertex
  65171. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  65172. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  65173. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  65174. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  65175. // is not used anywhere else.
  65176. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  65177. var Vertex = /** @class */ (function () {
  65178. function Vertex(pos, normal, uv) {
  65179. this.pos = pos;
  65180. this.normal = normal;
  65181. this.uv = uv;
  65182. }
  65183. Vertex.prototype.clone = function () {
  65184. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  65185. };
  65186. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  65187. // orientation of a polygon is flipped.
  65188. Vertex.prototype.flip = function () {
  65189. this.normal = this.normal.scale(-1);
  65190. };
  65191. // Create a new vertex between this vertex and `other` by linearly
  65192. // interpolating all properties using a parameter of `t`. Subclasses should
  65193. // override this to interpolate additional properties.
  65194. Vertex.prototype.interpolate = function (other, t) {
  65195. 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));
  65196. };
  65197. return Vertex;
  65198. }());
  65199. // # class Plane
  65200. // Represents a plane in 3D space.
  65201. var Plane = /** @class */ (function () {
  65202. function Plane(normal, w) {
  65203. this.normal = normal;
  65204. this.w = w;
  65205. }
  65206. Plane.FromPoints = function (a, b, c) {
  65207. var v0 = c.subtract(a);
  65208. var v1 = b.subtract(a);
  65209. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  65210. return null;
  65211. }
  65212. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  65213. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  65214. };
  65215. Plane.prototype.clone = function () {
  65216. return new Plane(this.normal.clone(), this.w);
  65217. };
  65218. Plane.prototype.flip = function () {
  65219. this.normal.scaleInPlace(-1);
  65220. this.w = -this.w;
  65221. };
  65222. // Split `polygon` by this plane if needed, then put the polygon or polygon
  65223. // fragments in the appropriate lists. Coplanar polygons go into either
  65224. // `coplanarFront` or `coplanarBack` depending on their orientation with
  65225. // respect to this plane. Polygons in front or in back of this plane go into
  65226. // either `front` or `back`.
  65227. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  65228. var COPLANAR = 0;
  65229. var FRONT = 1;
  65230. var BACK = 2;
  65231. var SPANNING = 3;
  65232. // Classify each point as well as the entire polygon into one of the above
  65233. // four classes.
  65234. var polygonType = 0;
  65235. var types = [];
  65236. var i;
  65237. var t;
  65238. for (i = 0; i < polygon.vertices.length; i++) {
  65239. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  65240. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  65241. polygonType |= type;
  65242. types.push(type);
  65243. }
  65244. // Put the polygon in the correct list, splitting it when necessary.
  65245. switch (polygonType) {
  65246. case COPLANAR:
  65247. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  65248. break;
  65249. case FRONT:
  65250. front.push(polygon);
  65251. break;
  65252. case BACK:
  65253. back.push(polygon);
  65254. break;
  65255. case SPANNING:
  65256. var f = [], b = [];
  65257. for (i = 0; i < polygon.vertices.length; i++) {
  65258. var j = (i + 1) % polygon.vertices.length;
  65259. var ti = types[i], tj = types[j];
  65260. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  65261. if (ti !== BACK)
  65262. f.push(vi);
  65263. if (ti !== FRONT)
  65264. b.push(ti !== BACK ? vi.clone() : vi);
  65265. if ((ti | tj) === SPANNING) {
  65266. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  65267. var v = vi.interpolate(vj, t);
  65268. f.push(v);
  65269. b.push(v.clone());
  65270. }
  65271. }
  65272. var poly;
  65273. if (f.length >= 3) {
  65274. poly = new Polygon(f, polygon.shared);
  65275. if (poly.plane)
  65276. front.push(poly);
  65277. }
  65278. if (b.length >= 3) {
  65279. poly = new Polygon(b, polygon.shared);
  65280. if (poly.plane)
  65281. back.push(poly);
  65282. }
  65283. break;
  65284. }
  65285. };
  65286. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  65287. // point is on the plane.
  65288. Plane.EPSILON = 1e-5;
  65289. return Plane;
  65290. }());
  65291. // # class Polygon
  65292. // Represents a convex polygon. The vertices used to initialize a polygon must
  65293. // be coplanar and form a convex loop.
  65294. //
  65295. // Each convex polygon has a `shared` property, which is shared between all
  65296. // polygons that are clones of each other or were split from the same polygon.
  65297. // This can be used to define per-polygon properties (such as surface color).
  65298. var Polygon = /** @class */ (function () {
  65299. function Polygon(vertices, shared) {
  65300. this.vertices = vertices;
  65301. this.shared = shared;
  65302. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  65303. }
  65304. Polygon.prototype.clone = function () {
  65305. var vertices = this.vertices.map(function (v) { return v.clone(); });
  65306. return new Polygon(vertices, this.shared);
  65307. };
  65308. Polygon.prototype.flip = function () {
  65309. this.vertices.reverse().map(function (v) { v.flip(); });
  65310. this.plane.flip();
  65311. };
  65312. return Polygon;
  65313. }());
  65314. // # class Node
  65315. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  65316. // by picking a polygon to split along. That polygon (and all other coplanar
  65317. // polygons) are added directly to that node and the other polygons are added to
  65318. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  65319. // no distinction between internal and leaf nodes.
  65320. var Node = /** @class */ (function () {
  65321. function Node(polygons) {
  65322. this.plane = null;
  65323. this.front = null;
  65324. this.back = null;
  65325. this.polygons = new Array();
  65326. if (polygons) {
  65327. this.build(polygons);
  65328. }
  65329. }
  65330. Node.prototype.clone = function () {
  65331. var node = new Node();
  65332. node.plane = this.plane && this.plane.clone();
  65333. node.front = this.front && this.front.clone();
  65334. node.back = this.back && this.back.clone();
  65335. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  65336. return node;
  65337. };
  65338. // Convert solid space to empty space and empty space to solid space.
  65339. Node.prototype.invert = function () {
  65340. for (var i = 0; i < this.polygons.length; i++) {
  65341. this.polygons[i].flip();
  65342. }
  65343. if (this.plane) {
  65344. this.plane.flip();
  65345. }
  65346. if (this.front) {
  65347. this.front.invert();
  65348. }
  65349. if (this.back) {
  65350. this.back.invert();
  65351. }
  65352. var temp = this.front;
  65353. this.front = this.back;
  65354. this.back = temp;
  65355. };
  65356. // Recursively remove all polygons in `polygons` that are inside this BSP
  65357. // tree.
  65358. Node.prototype.clipPolygons = function (polygons) {
  65359. if (!this.plane)
  65360. return polygons.slice();
  65361. var front = new Array(), back = new Array();
  65362. for (var i = 0; i < polygons.length; i++) {
  65363. this.plane.splitPolygon(polygons[i], front, back, front, back);
  65364. }
  65365. if (this.front) {
  65366. front = this.front.clipPolygons(front);
  65367. }
  65368. if (this.back) {
  65369. back = this.back.clipPolygons(back);
  65370. }
  65371. else {
  65372. back = [];
  65373. }
  65374. return front.concat(back);
  65375. };
  65376. // Remove all polygons in this BSP tree that are inside the other BSP tree
  65377. // `bsp`.
  65378. Node.prototype.clipTo = function (bsp) {
  65379. this.polygons = bsp.clipPolygons(this.polygons);
  65380. if (this.front)
  65381. this.front.clipTo(bsp);
  65382. if (this.back)
  65383. this.back.clipTo(bsp);
  65384. };
  65385. // Return a list of all polygons in this BSP tree.
  65386. Node.prototype.allPolygons = function () {
  65387. var polygons = this.polygons.slice();
  65388. if (this.front)
  65389. polygons = polygons.concat(this.front.allPolygons());
  65390. if (this.back)
  65391. polygons = polygons.concat(this.back.allPolygons());
  65392. return polygons;
  65393. };
  65394. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  65395. // new polygons are filtered down to the bottom of the tree and become new
  65396. // nodes there. Each set of polygons is partitioned using the first polygon
  65397. // (no heuristic is used to pick a good split).
  65398. Node.prototype.build = function (polygons) {
  65399. if (!polygons.length)
  65400. return;
  65401. if (!this.plane)
  65402. this.plane = polygons[0].plane.clone();
  65403. var front = new Array(), back = new Array();
  65404. for (var i = 0; i < polygons.length; i++) {
  65405. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  65406. }
  65407. if (front.length) {
  65408. if (!this.front)
  65409. this.front = new Node();
  65410. this.front.build(front);
  65411. }
  65412. if (back.length) {
  65413. if (!this.back)
  65414. this.back = new Node();
  65415. this.back.build(back);
  65416. }
  65417. };
  65418. return Node;
  65419. }());
  65420. var CSG = /** @class */ (function () {
  65421. function CSG() {
  65422. this.polygons = new Array();
  65423. }
  65424. // Convert BABYLON.Mesh to BABYLON.CSG
  65425. CSG.FromMesh = function (mesh) {
  65426. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  65427. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  65428. if (mesh instanceof BABYLON.Mesh) {
  65429. mesh.computeWorldMatrix(true);
  65430. matrix = mesh.getWorldMatrix();
  65431. meshPosition = mesh.position.clone();
  65432. meshRotation = mesh.rotation.clone();
  65433. if (mesh.rotationQuaternion) {
  65434. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  65435. }
  65436. meshScaling = mesh.scaling.clone();
  65437. }
  65438. else {
  65439. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  65440. }
  65441. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  65442. var subMeshes = mesh.subMeshes;
  65443. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  65444. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  65445. vertices = [];
  65446. for (var j = 0; j < 3; j++) {
  65447. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  65448. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  65449. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  65450. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  65451. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  65452. vertex = new Vertex(position, normal, uv);
  65453. vertices.push(vertex);
  65454. }
  65455. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  65456. // To handle the case of degenerated triangle
  65457. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  65458. if (polygon.plane)
  65459. polygons.push(polygon);
  65460. }
  65461. }
  65462. var csg = CSG.FromPolygons(polygons);
  65463. csg.matrix = matrix;
  65464. csg.position = meshPosition;
  65465. csg.rotation = meshRotation;
  65466. csg.scaling = meshScaling;
  65467. csg.rotationQuaternion = meshRotationQuaternion;
  65468. currentCSGMeshId++;
  65469. return csg;
  65470. };
  65471. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  65472. CSG.FromPolygons = function (polygons) {
  65473. var csg = new CSG();
  65474. csg.polygons = polygons;
  65475. return csg;
  65476. };
  65477. CSG.prototype.clone = function () {
  65478. var csg = new CSG();
  65479. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  65480. csg.copyTransformAttributes(this);
  65481. return csg;
  65482. };
  65483. CSG.prototype.union = function (csg) {
  65484. var a = new Node(this.clone().polygons);
  65485. var b = new Node(csg.clone().polygons);
  65486. a.clipTo(b);
  65487. b.clipTo(a);
  65488. b.invert();
  65489. b.clipTo(a);
  65490. b.invert();
  65491. a.build(b.allPolygons());
  65492. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  65493. };
  65494. CSG.prototype.unionInPlace = function (csg) {
  65495. var a = new Node(this.polygons);
  65496. var b = new Node(csg.polygons);
  65497. a.clipTo(b);
  65498. b.clipTo(a);
  65499. b.invert();
  65500. b.clipTo(a);
  65501. b.invert();
  65502. a.build(b.allPolygons());
  65503. this.polygons = a.allPolygons();
  65504. };
  65505. CSG.prototype.subtract = function (csg) {
  65506. var a = new Node(this.clone().polygons);
  65507. var b = new Node(csg.clone().polygons);
  65508. a.invert();
  65509. a.clipTo(b);
  65510. b.clipTo(a);
  65511. b.invert();
  65512. b.clipTo(a);
  65513. b.invert();
  65514. a.build(b.allPolygons());
  65515. a.invert();
  65516. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  65517. };
  65518. CSG.prototype.subtractInPlace = function (csg) {
  65519. var a = new Node(this.polygons);
  65520. var b = new Node(csg.polygons);
  65521. a.invert();
  65522. a.clipTo(b);
  65523. b.clipTo(a);
  65524. b.invert();
  65525. b.clipTo(a);
  65526. b.invert();
  65527. a.build(b.allPolygons());
  65528. a.invert();
  65529. this.polygons = a.allPolygons();
  65530. };
  65531. CSG.prototype.intersect = function (csg) {
  65532. var a = new Node(this.clone().polygons);
  65533. var b = new Node(csg.clone().polygons);
  65534. a.invert();
  65535. b.clipTo(a);
  65536. b.invert();
  65537. a.clipTo(b);
  65538. b.clipTo(a);
  65539. a.build(b.allPolygons());
  65540. a.invert();
  65541. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  65542. };
  65543. CSG.prototype.intersectInPlace = function (csg) {
  65544. var a = new Node(this.polygons);
  65545. var b = new Node(csg.polygons);
  65546. a.invert();
  65547. b.clipTo(a);
  65548. b.invert();
  65549. a.clipTo(b);
  65550. b.clipTo(a);
  65551. a.build(b.allPolygons());
  65552. a.invert();
  65553. this.polygons = a.allPolygons();
  65554. };
  65555. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  65556. // not modified.
  65557. CSG.prototype.inverse = function () {
  65558. var csg = this.clone();
  65559. csg.inverseInPlace();
  65560. return csg;
  65561. };
  65562. CSG.prototype.inverseInPlace = function () {
  65563. this.polygons.map(function (p) { p.flip(); });
  65564. };
  65565. // This is used to keep meshes transformations so they can be restored
  65566. // when we build back a Babylon Mesh
  65567. // NB : All CSG operations are performed in world coordinates
  65568. CSG.prototype.copyTransformAttributes = function (csg) {
  65569. this.matrix = csg.matrix;
  65570. this.position = csg.position;
  65571. this.rotation = csg.rotation;
  65572. this.scaling = csg.scaling;
  65573. this.rotationQuaternion = csg.rotationQuaternion;
  65574. return this;
  65575. };
  65576. // Build Raw mesh from CSG
  65577. // Coordinates here are in world space
  65578. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  65579. var matrix = this.matrix.clone();
  65580. matrix.invert();
  65581. 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;
  65582. if (keepSubMeshes) {
  65583. // Sort Polygons, since subMeshes are indices range
  65584. polygons.sort(function (a, b) {
  65585. if (a.shared.meshId === b.shared.meshId) {
  65586. return a.shared.subMeshId - b.shared.subMeshId;
  65587. }
  65588. else {
  65589. return a.shared.meshId - b.shared.meshId;
  65590. }
  65591. });
  65592. }
  65593. for (var i = 0, il = polygons.length; i < il; i++) {
  65594. polygon = polygons[i];
  65595. // Building SubMeshes
  65596. if (!subMesh_dict[polygon.shared.meshId]) {
  65597. subMesh_dict[polygon.shared.meshId] = {};
  65598. }
  65599. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  65600. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  65601. indexStart: +Infinity,
  65602. indexEnd: -Infinity,
  65603. materialIndex: polygon.shared.materialIndex
  65604. };
  65605. }
  65606. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  65607. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  65608. polygonIndices[0] = 0;
  65609. polygonIndices[1] = j - 1;
  65610. polygonIndices[2] = j;
  65611. for (var k = 0; k < 3; k++) {
  65612. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  65613. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  65614. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  65615. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  65616. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  65617. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  65618. // Check if 2 points can be merged
  65619. if (!(typeof vertex_idx !== 'undefined' &&
  65620. normals[vertex_idx * 3] === localNormal.x &&
  65621. normals[vertex_idx * 3 + 1] === localNormal.y &&
  65622. normals[vertex_idx * 3 + 2] === localNormal.z &&
  65623. uvs[vertex_idx * 2] === uv.x &&
  65624. uvs[vertex_idx * 2 + 1] === uv.y)) {
  65625. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  65626. uvs.push(uv.x, uv.y);
  65627. normals.push(normal.x, normal.y, normal.z);
  65628. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  65629. }
  65630. indices.push(vertex_idx);
  65631. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  65632. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  65633. currentIndex++;
  65634. }
  65635. }
  65636. }
  65637. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  65638. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  65639. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  65640. mesh.setIndices(indices, null);
  65641. if (keepSubMeshes) {
  65642. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  65643. var materialIndexOffset = 0, materialMaxIndex;
  65644. mesh.subMeshes = new Array();
  65645. for (var m in subMesh_dict) {
  65646. materialMaxIndex = -1;
  65647. for (var sm in subMesh_dict[m]) {
  65648. subMesh_obj = subMesh_dict[m][sm];
  65649. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  65650. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  65651. }
  65652. materialIndexOffset += ++materialMaxIndex;
  65653. }
  65654. }
  65655. return mesh;
  65656. };
  65657. // Build Mesh from CSG taking material and transforms into account
  65658. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  65659. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  65660. mesh.material = material;
  65661. mesh.position.copyFrom(this.position);
  65662. mesh.rotation.copyFrom(this.rotation);
  65663. if (this.rotationQuaternion) {
  65664. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  65665. }
  65666. mesh.scaling.copyFrom(this.scaling);
  65667. mesh.computeWorldMatrix(true);
  65668. return mesh;
  65669. };
  65670. return CSG;
  65671. }());
  65672. BABYLON.CSG = CSG;
  65673. })(BABYLON || (BABYLON = {}));
  65674. //# sourceMappingURL=babylon.csg.js.map
  65675. var BABYLON;
  65676. (function (BABYLON) {
  65677. var LensFlare = /** @class */ (function () {
  65678. function LensFlare(size, position, color, imgUrl, system) {
  65679. this.size = size;
  65680. this.position = position;
  65681. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  65682. this.color = color || new BABYLON.Color3(1, 1, 1);
  65683. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  65684. this._system = system;
  65685. system.lensFlares.push(this);
  65686. }
  65687. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  65688. return new LensFlare(size, position, color, imgUrl, system);
  65689. };
  65690. LensFlare.prototype.dispose = function () {
  65691. if (this.texture) {
  65692. this.texture.dispose();
  65693. }
  65694. // Remove from scene
  65695. var index = this._system.lensFlares.indexOf(this);
  65696. this._system.lensFlares.splice(index, 1);
  65697. };
  65698. ;
  65699. return LensFlare;
  65700. }());
  65701. BABYLON.LensFlare = LensFlare;
  65702. })(BABYLON || (BABYLON = {}));
  65703. //# sourceMappingURL=babylon.lensFlare.js.map
  65704. var BABYLON;
  65705. (function (BABYLON) {
  65706. var LensFlareSystem = /** @class */ (function () {
  65707. function LensFlareSystem(name, emitter, scene) {
  65708. this.name = name;
  65709. this.lensFlares = new Array();
  65710. this.borderLimit = 300;
  65711. this.viewportBorder = 0;
  65712. this.layerMask = 0x0FFFFFFF;
  65713. this._vertexBuffers = {};
  65714. this._isEnabled = true;
  65715. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  65716. this._emitter = emitter;
  65717. this.id = name;
  65718. scene.lensFlareSystems.push(this);
  65719. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  65720. var engine = scene.getEngine();
  65721. // VBO
  65722. var vertices = [];
  65723. vertices.push(1, 1);
  65724. vertices.push(-1, 1);
  65725. vertices.push(-1, -1);
  65726. vertices.push(1, -1);
  65727. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  65728. // Indices
  65729. var indices = [];
  65730. indices.push(0);
  65731. indices.push(1);
  65732. indices.push(2);
  65733. indices.push(0);
  65734. indices.push(2);
  65735. indices.push(3);
  65736. this._indexBuffer = engine.createIndexBuffer(indices);
  65737. // Effects
  65738. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  65739. }
  65740. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  65741. get: function () {
  65742. return this._isEnabled;
  65743. },
  65744. set: function (value) {
  65745. this._isEnabled = value;
  65746. },
  65747. enumerable: true,
  65748. configurable: true
  65749. });
  65750. LensFlareSystem.prototype.getScene = function () {
  65751. return this._scene;
  65752. };
  65753. LensFlareSystem.prototype.getEmitter = function () {
  65754. return this._emitter;
  65755. };
  65756. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  65757. this._emitter = newEmitter;
  65758. };
  65759. LensFlareSystem.prototype.getEmitterPosition = function () {
  65760. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  65761. };
  65762. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  65763. var position = this.getEmitterPosition();
  65764. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  65765. this._positionX = position.x;
  65766. this._positionY = position.y;
  65767. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  65768. if (this.viewportBorder > 0) {
  65769. globalViewport.x -= this.viewportBorder;
  65770. globalViewport.y -= this.viewportBorder;
  65771. globalViewport.width += this.viewportBorder * 2;
  65772. globalViewport.height += this.viewportBorder * 2;
  65773. position.x += this.viewportBorder;
  65774. position.y += this.viewportBorder;
  65775. this._positionX += this.viewportBorder;
  65776. this._positionY += this.viewportBorder;
  65777. }
  65778. if (position.z > 0) {
  65779. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  65780. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  65781. return true;
  65782. }
  65783. return true;
  65784. }
  65785. return false;
  65786. };
  65787. LensFlareSystem.prototype._isVisible = function () {
  65788. if (!this._isEnabled || !this._scene.activeCamera) {
  65789. return false;
  65790. }
  65791. var emitterPosition = this.getEmitterPosition();
  65792. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  65793. var distance = direction.length();
  65794. direction.normalize();
  65795. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  65796. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  65797. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  65798. };
  65799. LensFlareSystem.prototype.render = function () {
  65800. if (!this._effect.isReady() || !this._scene.activeCamera)
  65801. return false;
  65802. var engine = this._scene.getEngine();
  65803. var viewport = this._scene.activeCamera.viewport;
  65804. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  65805. // Position
  65806. if (!this.computeEffectivePosition(globalViewport)) {
  65807. return false;
  65808. }
  65809. // Visibility
  65810. if (!this._isVisible()) {
  65811. return false;
  65812. }
  65813. // Intensity
  65814. var awayX;
  65815. var awayY;
  65816. if (this._positionX < this.borderLimit + globalViewport.x) {
  65817. awayX = this.borderLimit + globalViewport.x - this._positionX;
  65818. }
  65819. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  65820. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  65821. }
  65822. else {
  65823. awayX = 0;
  65824. }
  65825. if (this._positionY < this.borderLimit + globalViewport.y) {
  65826. awayY = this.borderLimit + globalViewport.y - this._positionY;
  65827. }
  65828. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  65829. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  65830. }
  65831. else {
  65832. awayY = 0;
  65833. }
  65834. var away = (awayX > awayY) ? awayX : awayY;
  65835. away -= this.viewportBorder;
  65836. if (away > this.borderLimit) {
  65837. away = this.borderLimit;
  65838. }
  65839. var intensity = 1.0 - (away / this.borderLimit);
  65840. if (intensity < 0) {
  65841. return false;
  65842. }
  65843. if (intensity > 1.0) {
  65844. intensity = 1.0;
  65845. }
  65846. if (this.viewportBorder > 0) {
  65847. globalViewport.x += this.viewportBorder;
  65848. globalViewport.y += this.viewportBorder;
  65849. globalViewport.width -= this.viewportBorder * 2;
  65850. globalViewport.height -= this.viewportBorder * 2;
  65851. this._positionX -= this.viewportBorder;
  65852. this._positionY -= this.viewportBorder;
  65853. }
  65854. // Position
  65855. var centerX = globalViewport.x + globalViewport.width / 2;
  65856. var centerY = globalViewport.y + globalViewport.height / 2;
  65857. var distX = centerX - this._positionX;
  65858. var distY = centerY - this._positionY;
  65859. // Effects
  65860. engine.enableEffect(this._effect);
  65861. engine.setState(false);
  65862. engine.setDepthBuffer(false);
  65863. // VBOs
  65864. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  65865. // Flares
  65866. for (var index = 0; index < this.lensFlares.length; index++) {
  65867. var flare = this.lensFlares[index];
  65868. engine.setAlphaMode(flare.alphaMode);
  65869. var x = centerX - (distX * flare.position);
  65870. var y = centerY - (distY * flare.position);
  65871. var cw = flare.size;
  65872. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  65873. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  65874. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  65875. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  65876. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  65877. // Texture
  65878. this._effect.setTexture("textureSampler", flare.texture);
  65879. // Color
  65880. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  65881. // Draw order
  65882. engine.draw(true, 0, 6);
  65883. }
  65884. engine.setDepthBuffer(true);
  65885. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  65886. return true;
  65887. };
  65888. LensFlareSystem.prototype.dispose = function () {
  65889. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65890. if (vertexBuffer) {
  65891. vertexBuffer.dispose();
  65892. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65893. }
  65894. if (this._indexBuffer) {
  65895. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  65896. this._indexBuffer = null;
  65897. }
  65898. while (this.lensFlares.length) {
  65899. this.lensFlares[0].dispose();
  65900. }
  65901. // Remove from scene
  65902. var index = this._scene.lensFlareSystems.indexOf(this);
  65903. this._scene.lensFlareSystems.splice(index, 1);
  65904. };
  65905. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  65906. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  65907. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  65908. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  65909. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  65910. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  65911. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  65912. var parsedFlare = parsedLensFlareSystem.flares[index];
  65913. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  65914. }
  65915. return lensFlareSystem;
  65916. };
  65917. LensFlareSystem.prototype.serialize = function () {
  65918. var serializationObject = {};
  65919. serializationObject.id = this.id;
  65920. serializationObject.name = this.name;
  65921. serializationObject.emitterId = this.getEmitter().id;
  65922. serializationObject.borderLimit = this.borderLimit;
  65923. serializationObject.flares = [];
  65924. for (var index = 0; index < this.lensFlares.length; index++) {
  65925. var flare = this.lensFlares[index];
  65926. serializationObject.flares.push({
  65927. size: flare.size,
  65928. position: flare.position,
  65929. color: flare.color.asArray(),
  65930. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  65931. });
  65932. }
  65933. return serializationObject;
  65934. };
  65935. return LensFlareSystem;
  65936. }());
  65937. BABYLON.LensFlareSystem = LensFlareSystem;
  65938. })(BABYLON || (BABYLON = {}));
  65939. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  65940. var BABYLON;
  65941. (function (BABYLON) {
  65942. /**
  65943. * This is a holder class for the physics joint created by the physics plugin.
  65944. * It holds a set of functions to control the underlying joint.
  65945. */
  65946. var PhysicsJoint = /** @class */ (function () {
  65947. function PhysicsJoint(type, jointData) {
  65948. this.type = type;
  65949. this.jointData = jointData;
  65950. jointData.nativeParams = jointData.nativeParams || {};
  65951. }
  65952. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  65953. get: function () {
  65954. return this._physicsJoint;
  65955. },
  65956. set: function (newJoint) {
  65957. if (this._physicsJoint) {
  65958. //remove from the wolrd
  65959. }
  65960. this._physicsJoint = newJoint;
  65961. },
  65962. enumerable: true,
  65963. configurable: true
  65964. });
  65965. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  65966. set: function (physicsPlugin) {
  65967. this._physicsPlugin = physicsPlugin;
  65968. },
  65969. enumerable: true,
  65970. configurable: true
  65971. });
  65972. /**
  65973. * Execute a function that is physics-plugin specific.
  65974. * @param {Function} func the function that will be executed.
  65975. * It accepts two parameters: the physics world and the physics joint.
  65976. */
  65977. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  65978. func(this._physicsPlugin.world, this._physicsJoint);
  65979. };
  65980. //TODO check if the native joints are the same
  65981. //Joint Types
  65982. PhysicsJoint.DistanceJoint = 0;
  65983. PhysicsJoint.HingeJoint = 1;
  65984. PhysicsJoint.BallAndSocketJoint = 2;
  65985. PhysicsJoint.WheelJoint = 3;
  65986. PhysicsJoint.SliderJoint = 4;
  65987. //OIMO
  65988. PhysicsJoint.PrismaticJoint = 5;
  65989. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  65990. PhysicsJoint.UniversalJoint = 6;
  65991. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  65992. //Cannon
  65993. //Similar to a Ball-Joint. Different in params
  65994. PhysicsJoint.PointToPointJoint = 8;
  65995. //Cannon only at the moment
  65996. PhysicsJoint.SpringJoint = 9;
  65997. PhysicsJoint.LockJoint = 10;
  65998. return PhysicsJoint;
  65999. }());
  66000. BABYLON.PhysicsJoint = PhysicsJoint;
  66001. /**
  66002. * A class representing a physics distance joint.
  66003. */
  66004. var DistanceJoint = /** @class */ (function (_super) {
  66005. __extends(DistanceJoint, _super);
  66006. function DistanceJoint(jointData) {
  66007. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  66008. }
  66009. /**
  66010. * Update the predefined distance.
  66011. */
  66012. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  66013. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  66014. };
  66015. return DistanceJoint;
  66016. }(PhysicsJoint));
  66017. BABYLON.DistanceJoint = DistanceJoint;
  66018. var MotorEnabledJoint = /** @class */ (function (_super) {
  66019. __extends(MotorEnabledJoint, _super);
  66020. function MotorEnabledJoint(type, jointData) {
  66021. return _super.call(this, type, jointData) || this;
  66022. }
  66023. /**
  66024. * Set the motor values.
  66025. * Attention, this function is plugin specific. Engines won't react 100% the same.
  66026. * @param {number} force the force to apply
  66027. * @param {number} maxForce max force for this motor.
  66028. */
  66029. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  66030. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  66031. };
  66032. /**
  66033. * Set the motor's limits.
  66034. * Attention, this function is plugin specific. Engines won't react 100% the same.
  66035. */
  66036. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  66037. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  66038. };
  66039. return MotorEnabledJoint;
  66040. }(PhysicsJoint));
  66041. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  66042. /**
  66043. * This class represents a single hinge physics joint
  66044. */
  66045. var HingeJoint = /** @class */ (function (_super) {
  66046. __extends(HingeJoint, _super);
  66047. function HingeJoint(jointData) {
  66048. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  66049. }
  66050. /**
  66051. * Set the motor values.
  66052. * Attention, this function is plugin specific. Engines won't react 100% the same.
  66053. * @param {number} force the force to apply
  66054. * @param {number} maxForce max force for this motor.
  66055. */
  66056. HingeJoint.prototype.setMotor = function (force, maxForce) {
  66057. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  66058. };
  66059. /**
  66060. * Set the motor's limits.
  66061. * Attention, this function is plugin specific. Engines won't react 100% the same.
  66062. */
  66063. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  66064. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  66065. };
  66066. return HingeJoint;
  66067. }(MotorEnabledJoint));
  66068. BABYLON.HingeJoint = HingeJoint;
  66069. /**
  66070. * This class represents a dual hinge physics joint (same as wheel joint)
  66071. */
  66072. var Hinge2Joint = /** @class */ (function (_super) {
  66073. __extends(Hinge2Joint, _super);
  66074. function Hinge2Joint(jointData) {
  66075. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  66076. }
  66077. /**
  66078. * Set the motor values.
  66079. * Attention, this function is plugin specific. Engines won't react 100% the same.
  66080. * @param {number} force the force to apply
  66081. * @param {number} maxForce max force for this motor.
  66082. * @param {motorIndex} the motor's index, 0 or 1.
  66083. */
  66084. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  66085. if (motorIndex === void 0) { motorIndex = 0; }
  66086. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  66087. };
  66088. /**
  66089. * Set the motor limits.
  66090. * Attention, this function is plugin specific. Engines won't react 100% the same.
  66091. * @param {number} upperLimit the upper limit
  66092. * @param {number} lowerLimit lower limit
  66093. * @param {motorIndex} the motor's index, 0 or 1.
  66094. */
  66095. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  66096. if (motorIndex === void 0) { motorIndex = 0; }
  66097. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  66098. };
  66099. return Hinge2Joint;
  66100. }(MotorEnabledJoint));
  66101. BABYLON.Hinge2Joint = Hinge2Joint;
  66102. })(BABYLON || (BABYLON = {}));
  66103. //# sourceMappingURL=babylon.physicsJoint.js.map
  66104. var BABYLON;
  66105. (function (BABYLON) {
  66106. var PhysicsImpostor = /** @class */ (function () {
  66107. function PhysicsImpostor(object, type, _options, _scene) {
  66108. if (_options === void 0) { _options = { mass: 0 }; }
  66109. var _this = this;
  66110. this.object = object;
  66111. this.type = type;
  66112. this._options = _options;
  66113. this._scene = _scene;
  66114. this._bodyUpdateRequired = false;
  66115. this._onBeforePhysicsStepCallbacks = new Array();
  66116. this._onAfterPhysicsStepCallbacks = new Array();
  66117. this._onPhysicsCollideCallbacks = [];
  66118. this._deltaPosition = BABYLON.Vector3.Zero();
  66119. this._isDisposed = false;
  66120. //temp variables for parent rotation calculations
  66121. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  66122. this._tmpQuat = new BABYLON.Quaternion();
  66123. this._tmpQuat2 = new BABYLON.Quaternion();
  66124. /**
  66125. * this function is executed by the physics engine.
  66126. */
  66127. this.beforeStep = function () {
  66128. if (!_this._physicsEngine) {
  66129. return;
  66130. }
  66131. _this.object.translate(_this._deltaPosition, -1);
  66132. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  66133. _this.object.computeWorldMatrix(false);
  66134. if (_this.object.parent && _this.object.rotationQuaternion) {
  66135. _this.getParentsRotation();
  66136. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  66137. }
  66138. else {
  66139. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  66140. }
  66141. if (!_this._options.disableBidirectionalTransformation) {
  66142. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  66143. }
  66144. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  66145. func(_this);
  66146. });
  66147. };
  66148. /**
  66149. * this function is executed by the physics engine.
  66150. */
  66151. this.afterStep = function () {
  66152. if (!_this._physicsEngine) {
  66153. return;
  66154. }
  66155. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  66156. func(_this);
  66157. });
  66158. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  66159. // object has now its world rotation. needs to be converted to local.
  66160. if (_this.object.parent && _this.object.rotationQuaternion) {
  66161. _this.getParentsRotation();
  66162. _this._tmpQuat.conjugateInPlace();
  66163. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  66164. }
  66165. // take the position set and make it the absolute position of this object.
  66166. _this.object.setAbsolutePosition(_this.object.position);
  66167. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  66168. _this.object.translate(_this._deltaPosition, 1);
  66169. };
  66170. /**
  66171. * Legacy collision detection event support
  66172. */
  66173. this.onCollideEvent = null;
  66174. //event and body object due to cannon's event-based architecture.
  66175. this.onCollide = function (e) {
  66176. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  66177. return;
  66178. }
  66179. if (!_this._physicsEngine) {
  66180. return;
  66181. }
  66182. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  66183. if (otherImpostor) {
  66184. // Legacy collision detection event support
  66185. if (_this.onCollideEvent) {
  66186. _this.onCollideEvent(_this, otherImpostor);
  66187. }
  66188. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  66189. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  66190. }).forEach(function (obj) {
  66191. obj.callback(_this, otherImpostor);
  66192. });
  66193. }
  66194. };
  66195. //sanity check!
  66196. if (!this.object) {
  66197. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  66198. return;
  66199. }
  66200. //legacy support for old syntax.
  66201. if (!this._scene && object.getScene) {
  66202. this._scene = object.getScene();
  66203. }
  66204. if (!this._scene) {
  66205. return;
  66206. }
  66207. this._physicsEngine = this._scene.getPhysicsEngine();
  66208. if (!this._physicsEngine) {
  66209. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  66210. }
  66211. else {
  66212. //set the object's quaternion, if not set
  66213. if (!this.object.rotationQuaternion) {
  66214. if (this.object.rotation) {
  66215. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  66216. }
  66217. else {
  66218. this.object.rotationQuaternion = new BABYLON.Quaternion();
  66219. }
  66220. }
  66221. //default options params
  66222. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  66223. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  66224. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  66225. this._joints = [];
  66226. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  66227. if (!this.object.parent || this._options.ignoreParent) {
  66228. this._init();
  66229. }
  66230. else if (this.object.parent.physicsImpostor) {
  66231. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  66232. }
  66233. }
  66234. }
  66235. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  66236. get: function () {
  66237. return this._isDisposed;
  66238. },
  66239. enumerable: true,
  66240. configurable: true
  66241. });
  66242. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  66243. get: function () {
  66244. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  66245. },
  66246. set: function (value) {
  66247. this.setMass(value);
  66248. },
  66249. enumerable: true,
  66250. configurable: true
  66251. });
  66252. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  66253. get: function () {
  66254. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  66255. },
  66256. set: function (value) {
  66257. if (!this._physicsEngine) {
  66258. return;
  66259. }
  66260. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  66261. },
  66262. enumerable: true,
  66263. configurable: true
  66264. });
  66265. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  66266. get: function () {
  66267. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  66268. },
  66269. set: function (value) {
  66270. if (!this._physicsEngine) {
  66271. return;
  66272. }
  66273. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  66274. },
  66275. enumerable: true,
  66276. configurable: true
  66277. });
  66278. /**
  66279. * This function will completly initialize this impostor.
  66280. * It will create a new body - but only if this mesh has no parent.
  66281. * If it has, this impostor will not be used other than to define the impostor
  66282. * of the child mesh.
  66283. */
  66284. PhysicsImpostor.prototype._init = function () {
  66285. if (!this._physicsEngine) {
  66286. return;
  66287. }
  66288. this._physicsEngine.removeImpostor(this);
  66289. this.physicsBody = null;
  66290. this._parent = this._parent || this._getPhysicsParent();
  66291. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  66292. this._physicsEngine.addImpostor(this);
  66293. }
  66294. };
  66295. PhysicsImpostor.prototype._getPhysicsParent = function () {
  66296. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  66297. var parentMesh = this.object.parent;
  66298. return parentMesh.physicsImpostor;
  66299. }
  66300. return null;
  66301. };
  66302. /**
  66303. * Should a new body be generated.
  66304. */
  66305. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  66306. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  66307. };
  66308. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  66309. this.forceUpdate();
  66310. };
  66311. /**
  66312. * Force a regeneration of this or the parent's impostor's body.
  66313. * Use under cautious - This will remove all joints already implemented.
  66314. */
  66315. PhysicsImpostor.prototype.forceUpdate = function () {
  66316. this._init();
  66317. if (this.parent && !this._options.ignoreParent) {
  66318. this.parent.forceUpdate();
  66319. }
  66320. };
  66321. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  66322. /*public get mesh(): AbstractMesh {
  66323. return this._mesh;
  66324. }*/
  66325. /**
  66326. * Gets the body that holds this impostor. Either its own, or its parent.
  66327. */
  66328. get: function () {
  66329. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  66330. },
  66331. /**
  66332. * Set the physics body. Used mainly by the physics engine/plugin
  66333. */
  66334. set: function (physicsBody) {
  66335. if (this._physicsBody && this._physicsEngine) {
  66336. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  66337. }
  66338. this._physicsBody = physicsBody;
  66339. this.resetUpdateFlags();
  66340. },
  66341. enumerable: true,
  66342. configurable: true
  66343. });
  66344. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  66345. get: function () {
  66346. return !this._options.ignoreParent && this._parent ? this._parent : null;
  66347. },
  66348. set: function (value) {
  66349. this._parent = value;
  66350. },
  66351. enumerable: true,
  66352. configurable: true
  66353. });
  66354. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  66355. this._bodyUpdateRequired = false;
  66356. };
  66357. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  66358. if (this.object.getBoundingInfo) {
  66359. var q = this.object.rotationQuaternion;
  66360. //reset rotation
  66361. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  66362. //calculate the world matrix with no rotation
  66363. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  66364. var boundingInfo = this.object.getBoundingInfo();
  66365. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  66366. //bring back the rotation
  66367. this.object.rotationQuaternion = q;
  66368. //calculate the world matrix with the new rotation
  66369. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  66370. return size;
  66371. }
  66372. else {
  66373. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  66374. }
  66375. };
  66376. PhysicsImpostor.prototype.getObjectCenter = function () {
  66377. if (this.object.getBoundingInfo) {
  66378. var boundingInfo = this.object.getBoundingInfo();
  66379. return boundingInfo.boundingBox.centerWorld;
  66380. }
  66381. else {
  66382. return this.object.position;
  66383. }
  66384. };
  66385. /**
  66386. * Get a specific parametes from the options parameter.
  66387. */
  66388. PhysicsImpostor.prototype.getParam = function (paramName) {
  66389. return this._options[paramName];
  66390. };
  66391. /**
  66392. * Sets a specific parameter in the options given to the physics plugin
  66393. */
  66394. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  66395. this._options[paramName] = value;
  66396. this._bodyUpdateRequired = true;
  66397. };
  66398. /**
  66399. * Specifically change the body's mass option. Won't recreate the physics body object
  66400. */
  66401. PhysicsImpostor.prototype.setMass = function (mass) {
  66402. if (this.getParam("mass") !== mass) {
  66403. this.setParam("mass", mass);
  66404. }
  66405. if (this._physicsEngine) {
  66406. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  66407. }
  66408. };
  66409. PhysicsImpostor.prototype.getLinearVelocity = function () {
  66410. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  66411. };
  66412. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  66413. if (this._physicsEngine) {
  66414. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  66415. }
  66416. };
  66417. PhysicsImpostor.prototype.getAngularVelocity = function () {
  66418. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  66419. };
  66420. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  66421. if (this._physicsEngine) {
  66422. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  66423. }
  66424. };
  66425. /**
  66426. * Execute a function with the physics plugin native code.
  66427. * Provide a function the will have two variables - the world object and the physics body object.
  66428. */
  66429. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  66430. if (this._physicsEngine) {
  66431. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  66432. }
  66433. };
  66434. /**
  66435. * Register a function that will be executed before the physics world is stepping forward.
  66436. */
  66437. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  66438. this._onBeforePhysicsStepCallbacks.push(func);
  66439. };
  66440. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  66441. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  66442. if (index > -1) {
  66443. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  66444. }
  66445. else {
  66446. BABYLON.Tools.Warn("Function to remove was not found");
  66447. }
  66448. };
  66449. /**
  66450. * Register a function that will be executed after the physics step
  66451. */
  66452. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  66453. this._onAfterPhysicsStepCallbacks.push(func);
  66454. };
  66455. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  66456. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  66457. if (index > -1) {
  66458. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  66459. }
  66460. else {
  66461. BABYLON.Tools.Warn("Function to remove was not found");
  66462. }
  66463. };
  66464. /**
  66465. * register a function that will be executed when this impostor collides against a different body.
  66466. */
  66467. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  66468. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  66469. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  66470. };
  66471. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  66472. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  66473. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  66474. if (index > -1) {
  66475. this._onPhysicsCollideCallbacks.splice(index, 1);
  66476. }
  66477. else {
  66478. BABYLON.Tools.Warn("Function to remove was not found");
  66479. }
  66480. };
  66481. PhysicsImpostor.prototype.getParentsRotation = function () {
  66482. var parent = this.object.parent;
  66483. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  66484. while (parent) {
  66485. if (parent.rotationQuaternion) {
  66486. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  66487. }
  66488. else {
  66489. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  66490. }
  66491. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  66492. parent = parent.parent;
  66493. }
  66494. return this._tmpQuat;
  66495. };
  66496. /**
  66497. * Apply a force
  66498. */
  66499. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  66500. if (this._physicsEngine) {
  66501. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  66502. }
  66503. return this;
  66504. };
  66505. /**
  66506. * Apply an impulse
  66507. */
  66508. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  66509. if (this._physicsEngine) {
  66510. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  66511. }
  66512. return this;
  66513. };
  66514. /**
  66515. * A help function to create a joint.
  66516. */
  66517. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  66518. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  66519. this.addJoint(otherImpostor, joint);
  66520. return this;
  66521. };
  66522. /**
  66523. * Add a joint to this impostor with a different impostor.
  66524. */
  66525. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  66526. this._joints.push({
  66527. otherImpostor: otherImpostor,
  66528. joint: joint
  66529. });
  66530. if (this._physicsEngine) {
  66531. this._physicsEngine.addJoint(this, otherImpostor, joint);
  66532. }
  66533. return this;
  66534. };
  66535. /**
  66536. * Will keep this body still, in a sleep mode.
  66537. */
  66538. PhysicsImpostor.prototype.sleep = function () {
  66539. if (this._physicsEngine) {
  66540. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  66541. }
  66542. return this;
  66543. };
  66544. /**
  66545. * Wake the body up.
  66546. */
  66547. PhysicsImpostor.prototype.wakeUp = function () {
  66548. if (this._physicsEngine) {
  66549. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  66550. }
  66551. return this;
  66552. };
  66553. PhysicsImpostor.prototype.clone = function (newObject) {
  66554. if (!newObject)
  66555. return null;
  66556. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  66557. };
  66558. PhysicsImpostor.prototype.dispose = function () {
  66559. var _this = this;
  66560. //no dispose if no physics engine is available.
  66561. if (!this._physicsEngine) {
  66562. return;
  66563. }
  66564. this._joints.forEach(function (j) {
  66565. if (_this._physicsEngine) {
  66566. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  66567. }
  66568. });
  66569. //dispose the physics body
  66570. this._physicsEngine.removeImpostor(this);
  66571. if (this.parent) {
  66572. this.parent.forceUpdate();
  66573. }
  66574. else {
  66575. /*this._object.getChildMeshes().forEach(function(mesh) {
  66576. if (mesh.physicsImpostor) {
  66577. if (disposeChildren) {
  66578. mesh.physicsImpostor.dispose();
  66579. mesh.physicsImpostor = null;
  66580. }
  66581. }
  66582. })*/
  66583. }
  66584. this._isDisposed = true;
  66585. };
  66586. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  66587. this._deltaPosition.copyFrom(position);
  66588. };
  66589. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  66590. if (!this._deltaRotation) {
  66591. this._deltaRotation = new BABYLON.Quaternion();
  66592. }
  66593. this._deltaRotation.copyFrom(rotation);
  66594. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  66595. };
  66596. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  66597. if (this._physicsEngine) {
  66598. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  66599. }
  66600. return this;
  66601. };
  66602. PhysicsImpostor.prototype.getRadius = function () {
  66603. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  66604. };
  66605. /**
  66606. * Sync a bone with this impostor
  66607. * @param bone The bone to sync to the impostor.
  66608. * @param boneMesh The mesh that the bone is influencing.
  66609. * @param jointPivot The pivot of the joint / bone in local space.
  66610. * @param distToJoint Optional distance from the impostor to the joint.
  66611. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  66612. */
  66613. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  66614. var tempVec = PhysicsImpostor._tmpVecs[0];
  66615. var mesh = this.object;
  66616. if (mesh.rotationQuaternion) {
  66617. if (adjustRotation) {
  66618. var tempQuat = PhysicsImpostor._tmpQuat;
  66619. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  66620. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  66621. }
  66622. else {
  66623. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  66624. }
  66625. }
  66626. tempVec.x = 0;
  66627. tempVec.y = 0;
  66628. tempVec.z = 0;
  66629. if (jointPivot) {
  66630. tempVec.x = jointPivot.x;
  66631. tempVec.y = jointPivot.y;
  66632. tempVec.z = jointPivot.z;
  66633. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  66634. if (distToJoint === undefined || distToJoint === null) {
  66635. distToJoint = jointPivot.length();
  66636. }
  66637. tempVec.x *= distToJoint;
  66638. tempVec.y *= distToJoint;
  66639. tempVec.z *= distToJoint;
  66640. }
  66641. if (bone.getParent()) {
  66642. tempVec.addInPlace(mesh.getAbsolutePosition());
  66643. bone.setAbsolutePosition(tempVec, boneMesh);
  66644. }
  66645. else {
  66646. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  66647. boneMesh.position.x -= tempVec.x;
  66648. boneMesh.position.y -= tempVec.y;
  66649. boneMesh.position.z -= tempVec.z;
  66650. }
  66651. };
  66652. /**
  66653. * Sync impostor to a bone
  66654. * @param bone The bone that the impostor will be synced to.
  66655. * @param boneMesh The mesh that the bone is influencing.
  66656. * @param jointPivot The pivot of the joint / bone in local space.
  66657. * @param distToJoint Optional distance from the impostor to the joint.
  66658. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  66659. * @param boneAxis Optional vector3 axis the bone is aligned with
  66660. */
  66661. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  66662. var mesh = this.object;
  66663. if (mesh.rotationQuaternion) {
  66664. if (adjustRotation) {
  66665. var tempQuat = PhysicsImpostor._tmpQuat;
  66666. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  66667. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  66668. }
  66669. else {
  66670. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  66671. }
  66672. }
  66673. var pos = PhysicsImpostor._tmpVecs[0];
  66674. var boneDir = PhysicsImpostor._tmpVecs[1];
  66675. if (!boneAxis) {
  66676. boneAxis = PhysicsImpostor._tmpVecs[2];
  66677. boneAxis.x = 0;
  66678. boneAxis.y = 1;
  66679. boneAxis.z = 0;
  66680. }
  66681. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  66682. bone.getAbsolutePositionToRef(boneMesh, pos);
  66683. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  66684. distToJoint = jointPivot.length();
  66685. }
  66686. if (distToJoint !== undefined && distToJoint !== null) {
  66687. pos.x += boneDir.x * distToJoint;
  66688. pos.y += boneDir.y * distToJoint;
  66689. pos.z += boneDir.z * distToJoint;
  66690. }
  66691. mesh.setAbsolutePosition(pos);
  66692. };
  66693. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  66694. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  66695. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  66696. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  66697. //Impostor types
  66698. PhysicsImpostor.NoImpostor = 0;
  66699. PhysicsImpostor.SphereImpostor = 1;
  66700. PhysicsImpostor.BoxImpostor = 2;
  66701. PhysicsImpostor.PlaneImpostor = 3;
  66702. PhysicsImpostor.MeshImpostor = 4;
  66703. PhysicsImpostor.CylinderImpostor = 7;
  66704. PhysicsImpostor.ParticleImpostor = 8;
  66705. PhysicsImpostor.HeightmapImpostor = 9;
  66706. return PhysicsImpostor;
  66707. }());
  66708. BABYLON.PhysicsImpostor = PhysicsImpostor;
  66709. })(BABYLON || (BABYLON = {}));
  66710. //# sourceMappingURL=babylon.physicsImpostor.js.map
  66711. var BABYLON;
  66712. (function (BABYLON) {
  66713. var PhysicsEngine = /** @class */ (function () {
  66714. function PhysicsEngine(gravity, _physicsPlugin) {
  66715. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  66716. this._physicsPlugin = _physicsPlugin;
  66717. //new methods and parameters
  66718. this._impostors = [];
  66719. this._joints = [];
  66720. if (!this._physicsPlugin.isSupported()) {
  66721. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  66722. + "Please make sure it is included.");
  66723. }
  66724. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  66725. this.setGravity(gravity);
  66726. this.setTimeStep();
  66727. }
  66728. PhysicsEngine.prototype.setGravity = function (gravity) {
  66729. this.gravity = gravity;
  66730. this._physicsPlugin.setGravity(this.gravity);
  66731. };
  66732. /**
  66733. * Set the time step of the physics engine.
  66734. * default is 1/60.
  66735. * To slow it down, enter 1/600 for example.
  66736. * To speed it up, 1/30
  66737. * @param {number} newTimeStep the new timestep to apply to this world.
  66738. */
  66739. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  66740. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  66741. this._physicsPlugin.setTimeStep(newTimeStep);
  66742. };
  66743. /**
  66744. * Get the time step of the physics engine.
  66745. */
  66746. PhysicsEngine.prototype.getTimeStep = function () {
  66747. return this._physicsPlugin.getTimeStep();
  66748. };
  66749. PhysicsEngine.prototype.dispose = function () {
  66750. this._impostors.forEach(function (impostor) {
  66751. impostor.dispose();
  66752. });
  66753. this._physicsPlugin.dispose();
  66754. };
  66755. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  66756. return this._physicsPlugin.name;
  66757. };
  66758. /**
  66759. * Adding a new impostor for the impostor tracking.
  66760. * This will be done by the impostor itself.
  66761. * @param {PhysicsImpostor} impostor the impostor to add
  66762. */
  66763. PhysicsEngine.prototype.addImpostor = function (impostor) {
  66764. impostor.uniqueId = this._impostors.push(impostor);
  66765. //if no parent, generate the body
  66766. if (!impostor.parent) {
  66767. this._physicsPlugin.generatePhysicsBody(impostor);
  66768. }
  66769. };
  66770. /**
  66771. * Remove an impostor from the engine.
  66772. * This impostor and its mesh will not longer be updated by the physics engine.
  66773. * @param {PhysicsImpostor} impostor the impostor to remove
  66774. */
  66775. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  66776. var index = this._impostors.indexOf(impostor);
  66777. if (index > -1) {
  66778. var removed = this._impostors.splice(index, 1);
  66779. //Is it needed?
  66780. if (removed.length) {
  66781. //this will also remove it from the world.
  66782. removed[0].physicsBody = null;
  66783. }
  66784. }
  66785. };
  66786. /**
  66787. * Add a joint to the physics engine
  66788. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  66789. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  66790. * @param {PhysicsJoint} the joint that will connect both impostors.
  66791. */
  66792. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  66793. var impostorJoint = {
  66794. mainImpostor: mainImpostor,
  66795. connectedImpostor: connectedImpostor,
  66796. joint: joint
  66797. };
  66798. joint.physicsPlugin = this._physicsPlugin;
  66799. this._joints.push(impostorJoint);
  66800. this._physicsPlugin.generateJoint(impostorJoint);
  66801. };
  66802. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  66803. var matchingJoints = this._joints.filter(function (impostorJoint) {
  66804. return (impostorJoint.connectedImpostor === connectedImpostor
  66805. && impostorJoint.joint === joint
  66806. && impostorJoint.mainImpostor === mainImpostor);
  66807. });
  66808. if (matchingJoints.length) {
  66809. this._physicsPlugin.removeJoint(matchingJoints[0]);
  66810. //TODO remove it from the list as well
  66811. }
  66812. };
  66813. /**
  66814. * Called by the scene. no need to call it.
  66815. */
  66816. PhysicsEngine.prototype._step = function (delta) {
  66817. var _this = this;
  66818. //check if any mesh has no body / requires an update
  66819. this._impostors.forEach(function (impostor) {
  66820. if (impostor.isBodyInitRequired()) {
  66821. _this._physicsPlugin.generatePhysicsBody(impostor);
  66822. }
  66823. });
  66824. if (delta > 0.1) {
  66825. delta = 0.1;
  66826. }
  66827. else if (delta <= 0) {
  66828. delta = 1.0 / 60.0;
  66829. }
  66830. this._physicsPlugin.executeStep(delta, this._impostors);
  66831. };
  66832. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  66833. return this._physicsPlugin;
  66834. };
  66835. PhysicsEngine.prototype.getImpostors = function () {
  66836. return this._impostors;
  66837. };
  66838. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  66839. for (var i = 0; i < this._impostors.length; ++i) {
  66840. if (this._impostors[i].object === object) {
  66841. return this._impostors[i];
  66842. }
  66843. }
  66844. return null;
  66845. };
  66846. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  66847. for (var i = 0; i < this._impostors.length; ++i) {
  66848. if (this._impostors[i].physicsBody === body) {
  66849. return this._impostors[i];
  66850. }
  66851. }
  66852. return null;
  66853. };
  66854. // Statics
  66855. PhysicsEngine.Epsilon = 0.001;
  66856. return PhysicsEngine;
  66857. }());
  66858. BABYLON.PhysicsEngine = PhysicsEngine;
  66859. })(BABYLON || (BABYLON = {}));
  66860. //# sourceMappingURL=babylon.physicsEngine.js.map
  66861. var BABYLON;
  66862. (function (BABYLON) {
  66863. /**
  66864. * The strenght of the force in correspondence to the distance of the affected object
  66865. */
  66866. var PhysicsRadialImpulseFalloff;
  66867. (function (PhysicsRadialImpulseFalloff) {
  66868. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  66869. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  66870. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  66871. /**
  66872. * The strenght of the force in correspondence to the distance of the affected object
  66873. */
  66874. var PhysicsUpdraftMode;
  66875. (function (PhysicsUpdraftMode) {
  66876. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  66877. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  66878. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  66879. var PhysicsHelper = /** @class */ (function () {
  66880. function PhysicsHelper(scene) {
  66881. this._scene = scene;
  66882. this._physicsEngine = this._scene.getPhysicsEngine();
  66883. if (!this._physicsEngine) {
  66884. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  66885. }
  66886. }
  66887. /**
  66888. * @param {Vector3} origin the origin of the explosion
  66889. * @param {number} radius the explosion radius
  66890. * @param {number} strength the explosion strength
  66891. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  66892. */
  66893. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  66894. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  66895. if (!this._physicsEngine) {
  66896. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  66897. return null;
  66898. }
  66899. var impostors = this._physicsEngine.getImpostors();
  66900. if (impostors.length === 0) {
  66901. return null;
  66902. }
  66903. var event = new PhysicsRadialExplosionEvent(this._scene);
  66904. impostors.forEach(function (impostor) {
  66905. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  66906. if (!impostorForceAndContactPoint) {
  66907. return;
  66908. }
  66909. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  66910. });
  66911. event.dispose(false);
  66912. return event;
  66913. };
  66914. /**
  66915. * @param {Vector3} origin the origin of the explosion
  66916. * @param {number} radius the explosion radius
  66917. * @param {number} strength the explosion strength
  66918. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  66919. */
  66920. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  66921. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  66922. if (!this._physicsEngine) {
  66923. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  66924. return null;
  66925. }
  66926. var impostors = this._physicsEngine.getImpostors();
  66927. if (impostors.length === 0) {
  66928. return null;
  66929. }
  66930. var event = new PhysicsRadialExplosionEvent(this._scene);
  66931. impostors.forEach(function (impostor) {
  66932. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  66933. if (!impostorForceAndContactPoint) {
  66934. return;
  66935. }
  66936. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  66937. });
  66938. event.dispose(false);
  66939. return event;
  66940. };
  66941. /**
  66942. * @param {Vector3} origin the origin of the explosion
  66943. * @param {number} radius the explosion radius
  66944. * @param {number} strength the explosion strength
  66945. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  66946. */
  66947. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  66948. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  66949. if (!this._physicsEngine) {
  66950. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  66951. return null;
  66952. }
  66953. var impostors = this._physicsEngine.getImpostors();
  66954. if (impostors.length === 0) {
  66955. return null;
  66956. }
  66957. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  66958. event.dispose(false);
  66959. return event;
  66960. };
  66961. /**
  66962. * @param {Vector3} origin the origin of the updraft
  66963. * @param {number} radius the radius of the updraft
  66964. * @param {number} strength the strength of the updraft
  66965. * @param {number} height the height of the updraft
  66966. */
  66967. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  66968. if (!this._physicsEngine) {
  66969. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  66970. return null;
  66971. }
  66972. if (this._physicsEngine.getImpostors().length === 0) {
  66973. return null;
  66974. }
  66975. var event = new PhysicsUpdraftEvent(this._physicsEngine, this._scene, origin, radius, strength, height, updraftMode);
  66976. event.dispose(false);
  66977. return event;
  66978. };
  66979. return PhysicsHelper;
  66980. }());
  66981. BABYLON.PhysicsHelper = PhysicsHelper;
  66982. /***** Radial explosion *****/
  66983. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  66984. function PhysicsRadialExplosionEvent(scene) {
  66985. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  66986. this._rays = [];
  66987. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  66988. this._scene = scene;
  66989. }
  66990. /**
  66991. * Returns the data related to the radial explosion event (sphere & rays).
  66992. * @returns {PhysicsRadialExplosionEventData}
  66993. */
  66994. PhysicsRadialExplosionEvent.prototype.getData = function () {
  66995. this._dataFetched = true;
  66996. return {
  66997. sphere: this._sphere,
  66998. rays: this._rays,
  66999. };
  67000. };
  67001. /**
  67002. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  67003. * @param impostor
  67004. * @param {Vector3} origin the origin of the explosion
  67005. * @param {number} radius the explosion radius
  67006. * @param {number} strength the explosion strength
  67007. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  67008. * @returns {Nullable<PhysicsForceAndContactPoint>}
  67009. */
  67010. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  67011. if (impostor.mass === 0) {
  67012. return null;
  67013. }
  67014. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  67015. return null;
  67016. }
  67017. var impostorObject = impostor.object;
  67018. var impostorObjectCenter = impostor.getObjectCenter();
  67019. var direction = impostorObjectCenter.subtract(origin);
  67020. var ray = new BABYLON.Ray(origin, direction, radius);
  67021. this._rays.push(ray);
  67022. var hit = ray.intersectsMesh(impostorObject);
  67023. var contactPoint = hit.pickedPoint;
  67024. if (!contactPoint) {
  67025. return null;
  67026. }
  67027. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  67028. if (distanceFromOrigin > radius) {
  67029. return null;
  67030. }
  67031. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  67032. ? strength
  67033. : strength * (1 - (distanceFromOrigin / radius));
  67034. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  67035. return { force: force, contactPoint: contactPoint };
  67036. };
  67037. /**
  67038. * Disposes the sphere.
  67039. * @param {bolean} force
  67040. */
  67041. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  67042. var _this = this;
  67043. if (force === void 0) { force = true; }
  67044. if (force) {
  67045. this._sphere.dispose();
  67046. }
  67047. else {
  67048. setTimeout(function () {
  67049. if (!_this._dataFetched) {
  67050. _this._sphere.dispose();
  67051. }
  67052. }, 0);
  67053. }
  67054. };
  67055. /*** Helpers ***/
  67056. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  67057. if (!this._sphere) {
  67058. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  67059. this._sphere.isVisible = false;
  67060. }
  67061. };
  67062. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  67063. var impostorObject = impostor.object;
  67064. this._prepareSphere();
  67065. this._sphere.position = origin;
  67066. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  67067. this._sphere._updateBoundingInfo();
  67068. this._sphere.computeWorldMatrix(true);
  67069. return this._sphere.intersectsMesh(impostorObject, true);
  67070. };
  67071. return PhysicsRadialExplosionEvent;
  67072. }());
  67073. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  67074. /***** Gravitational Field *****/
  67075. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  67076. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  67077. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  67078. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  67079. this._physicsHelper = physicsHelper;
  67080. this._scene = scene;
  67081. this._origin = origin;
  67082. this._radius = radius;
  67083. this._strength = strength;
  67084. this._falloff = falloff;
  67085. this._tickCallback = this._tick.bind(this);
  67086. }
  67087. /**
  67088. * Returns the data related to the gravitational field event (sphere).
  67089. * @returns {PhysicsGravitationalFieldEventData}
  67090. */
  67091. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  67092. this._dataFetched = true;
  67093. return {
  67094. sphere: this._sphere,
  67095. };
  67096. };
  67097. /**
  67098. * Enables the gravitational field.
  67099. */
  67100. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  67101. this._tickCallback.call(this);
  67102. this._scene.registerBeforeRender(this._tickCallback);
  67103. };
  67104. /**
  67105. * Disables the gravitational field.
  67106. */
  67107. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  67108. this._scene.unregisterBeforeRender(this._tickCallback);
  67109. };
  67110. /**
  67111. * Disposes the sphere.
  67112. * @param {bolean} force
  67113. */
  67114. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  67115. var _this = this;
  67116. if (force === void 0) { force = true; }
  67117. if (force) {
  67118. this._sphere.dispose();
  67119. }
  67120. else {
  67121. setTimeout(function () {
  67122. if (!_this._dataFetched) {
  67123. _this._sphere.dispose();
  67124. }
  67125. }, 0);
  67126. }
  67127. };
  67128. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  67129. // Since the params won't change, we fetch the event only once
  67130. if (this._sphere) {
  67131. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  67132. }
  67133. else {
  67134. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  67135. if (radialExplosionEvent) {
  67136. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  67137. }
  67138. }
  67139. };
  67140. return PhysicsGravitationalFieldEvent;
  67141. }());
  67142. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  67143. /***** Updraft *****/
  67144. var PhysicsUpdraftEvent = /** @class */ (function () {
  67145. function PhysicsUpdraftEvent(physicsEngine, scene, origin, radius, strength, height, updraftMode) {
  67146. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  67147. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  67148. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  67149. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  67150. this._physicsEngine = physicsEngine;
  67151. this._scene = scene;
  67152. this._origin = origin;
  67153. this._radius = radius;
  67154. this._strength = strength;
  67155. this._height = height;
  67156. this._updraftMode = updraftMode;
  67157. // TODO: for this._cylinderPosition & this._originTop, take rotation into account
  67158. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  67159. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  67160. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  67161. this._originDirection = this._origin.subtract(this._originTop).normalize();
  67162. }
  67163. this._tickCallback = this._tick.bind(this);
  67164. }
  67165. /**
  67166. * Returns the data related to the updraft event (cylinder).
  67167. * @returns {PhysicsGravitationalFieldEventData}
  67168. */
  67169. PhysicsUpdraftEvent.prototype.getData = function () {
  67170. this._dataFetched = true;
  67171. return {
  67172. cylinder: this._cylinder,
  67173. };
  67174. };
  67175. /**
  67176. * Enables the updraft.
  67177. */
  67178. PhysicsUpdraftEvent.prototype.enable = function () {
  67179. this._tickCallback.call(this);
  67180. this._scene.registerBeforeRender(this._tickCallback);
  67181. };
  67182. /**
  67183. * Disables the cortex.
  67184. */
  67185. PhysicsUpdraftEvent.prototype.disable = function () {
  67186. this._scene.unregisterBeforeRender(this._tickCallback);
  67187. };
  67188. /**
  67189. * Disposes the sphere.
  67190. * @param {bolean} force
  67191. */
  67192. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  67193. var _this = this;
  67194. if (force === void 0) { force = true; }
  67195. if (force) {
  67196. this._cylinder.dispose();
  67197. }
  67198. else {
  67199. setTimeout(function () {
  67200. if (!_this._dataFetched) {
  67201. _this._cylinder.dispose();
  67202. }
  67203. }, 0);
  67204. }
  67205. };
  67206. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  67207. if (impostor.mass === 0) {
  67208. return null;
  67209. }
  67210. if (!this._intersectsWithCylinder(impostor)) {
  67211. return null;
  67212. }
  67213. var impostorObjectCenter = impostor.getObjectCenter();
  67214. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  67215. var direction = this._originDirection;
  67216. }
  67217. else {
  67218. var direction = impostorObjectCenter.subtract(this._originTop);
  67219. }
  67220. var multiplier = this._strength * -1;
  67221. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  67222. return { force: force, contactPoint: impostorObjectCenter };
  67223. };
  67224. PhysicsUpdraftEvent.prototype._tick = function () {
  67225. var _this = this;
  67226. this._physicsEngine.getImpostors().forEach(function (impostor) {
  67227. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  67228. if (!impostorForceAndContactPoint) {
  67229. return;
  67230. }
  67231. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  67232. });
  67233. };
  67234. /*** Helpers ***/
  67235. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  67236. if (!this._cylinder) {
  67237. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  67238. height: this._height,
  67239. diameter: this._radius * 2,
  67240. }, this._scene);
  67241. this._cylinder.isVisible = false;
  67242. }
  67243. };
  67244. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  67245. var impostorObject = impostor.object;
  67246. this._prepareCylinder();
  67247. this._cylinder.position = this._cylinderPosition;
  67248. return this._cylinder.intersectsMesh(impostorObject, true);
  67249. };
  67250. return PhysicsUpdraftEvent;
  67251. }());
  67252. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  67253. })(BABYLON || (BABYLON = {}));
  67254. //# sourceMappingURL=babylon.physicsHelper.js.map
  67255. var BABYLON;
  67256. (function (BABYLON) {
  67257. var CannonJSPlugin = /** @class */ (function () {
  67258. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  67259. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  67260. if (iterations === void 0) { iterations = 10; }
  67261. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  67262. this.name = "CannonJSPlugin";
  67263. this._physicsMaterials = new Array();
  67264. this._fixedTimeStep = 1 / 60;
  67265. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  67266. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  67267. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  67268. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  67269. this._tmpPosition = BABYLON.Vector3.Zero();
  67270. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  67271. this._tmpUnityRotation = new BABYLON.Quaternion();
  67272. if (!this.isSupported()) {
  67273. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  67274. return;
  67275. }
  67276. this.world = new this.BJSCANNON.World();
  67277. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  67278. this.world.solver.iterations = iterations;
  67279. }
  67280. CannonJSPlugin.prototype.setGravity = function (gravity) {
  67281. this.world.gravity.copy(gravity);
  67282. };
  67283. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  67284. this._fixedTimeStep = timeStep;
  67285. };
  67286. CannonJSPlugin.prototype.getTimeStep = function () {
  67287. return this._fixedTimeStep;
  67288. };
  67289. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  67290. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  67291. };
  67292. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  67293. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  67294. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  67295. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  67296. };
  67297. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  67298. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  67299. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  67300. impostor.physicsBody.applyForce(impulse, worldPoint);
  67301. };
  67302. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  67303. //parent-child relationship. Does this impostor has a parent impostor?
  67304. if (impostor.parent) {
  67305. if (impostor.physicsBody) {
  67306. this.removePhysicsBody(impostor);
  67307. //TODO is that needed?
  67308. impostor.forceUpdate();
  67309. }
  67310. return;
  67311. }
  67312. //should a new body be created for this impostor?
  67313. if (impostor.isBodyInitRequired()) {
  67314. var shape = this._createShape(impostor);
  67315. //unregister events, if body is being changed
  67316. var oldBody = impostor.physicsBody;
  67317. if (oldBody) {
  67318. this.removePhysicsBody(impostor);
  67319. }
  67320. //create the body and material
  67321. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  67322. var bodyCreationObject = {
  67323. mass: impostor.getParam("mass"),
  67324. material: material
  67325. };
  67326. // A simple extend, in case native options were used.
  67327. var nativeOptions = impostor.getParam("nativeOptions");
  67328. for (var key in nativeOptions) {
  67329. if (nativeOptions.hasOwnProperty(key)) {
  67330. bodyCreationObject[key] = nativeOptions[key];
  67331. }
  67332. }
  67333. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  67334. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  67335. this.world.addEventListener("preStep", impostor.beforeStep);
  67336. this.world.addEventListener("postStep", impostor.afterStep);
  67337. impostor.physicsBody.addShape(shape);
  67338. this.world.add(impostor.physicsBody);
  67339. //try to keep the body moving in the right direction by taking old properties.
  67340. //Should be tested!
  67341. if (oldBody) {
  67342. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  67343. impostor.physicsBody[param].copy(oldBody[param]);
  67344. });
  67345. }
  67346. this._processChildMeshes(impostor);
  67347. }
  67348. //now update the body's transformation
  67349. this._updatePhysicsBodyTransformation(impostor);
  67350. };
  67351. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  67352. var _this = this;
  67353. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  67354. var currentRotation = mainImpostor.object.rotationQuaternion;
  67355. if (meshChildren.length) {
  67356. var processMesh = function (localPosition, mesh) {
  67357. if (!currentRotation || !mesh.rotationQuaternion) {
  67358. return;
  67359. }
  67360. var childImpostor = mesh.getPhysicsImpostor();
  67361. if (childImpostor) {
  67362. var parent = childImpostor.parent;
  67363. if (parent !== mainImpostor) {
  67364. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  67365. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  67366. if (childImpostor.physicsBody) {
  67367. _this.removePhysicsBody(childImpostor);
  67368. childImpostor.physicsBody = null;
  67369. }
  67370. childImpostor.parent = mainImpostor;
  67371. childImpostor.resetUpdateFlags();
  67372. 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));
  67373. //Add the mass of the children.
  67374. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  67375. }
  67376. }
  67377. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  67378. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  67379. };
  67380. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  67381. }
  67382. };
  67383. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  67384. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  67385. this.world.removeEventListener("preStep", impostor.beforeStep);
  67386. this.world.removeEventListener("postStep", impostor.afterStep);
  67387. this.world.remove(impostor.physicsBody);
  67388. };
  67389. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  67390. var mainBody = impostorJoint.mainImpostor.physicsBody;
  67391. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  67392. if (!mainBody || !connectedBody) {
  67393. return;
  67394. }
  67395. var constraint;
  67396. var jointData = impostorJoint.joint.jointData;
  67397. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  67398. var constraintData = {
  67399. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  67400. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  67401. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  67402. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  67403. maxForce: jointData.nativeParams.maxForce,
  67404. collideConnected: !!jointData.collision
  67405. };
  67406. switch (impostorJoint.joint.type) {
  67407. case BABYLON.PhysicsJoint.HingeJoint:
  67408. case BABYLON.PhysicsJoint.Hinge2Joint:
  67409. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  67410. break;
  67411. case BABYLON.PhysicsJoint.DistanceJoint:
  67412. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  67413. break;
  67414. case BABYLON.PhysicsJoint.SpringJoint:
  67415. var springData = jointData;
  67416. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  67417. restLength: springData.length,
  67418. stiffness: springData.stiffness,
  67419. damping: springData.damping,
  67420. localAnchorA: constraintData.pivotA,
  67421. localAnchorB: constraintData.pivotB
  67422. });
  67423. break;
  67424. case BABYLON.PhysicsJoint.LockJoint:
  67425. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  67426. break;
  67427. case BABYLON.PhysicsJoint.PointToPointJoint:
  67428. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  67429. default:
  67430. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  67431. break;
  67432. }
  67433. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  67434. constraint.collideConnected = !!jointData.collision;
  67435. impostorJoint.joint.physicsJoint = constraint;
  67436. //don't add spring as constraint, as it is not one.
  67437. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  67438. this.world.addConstraint(constraint);
  67439. }
  67440. else {
  67441. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  67442. constraint.applyForce();
  67443. });
  67444. }
  67445. };
  67446. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  67447. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  67448. };
  67449. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  67450. var index;
  67451. var mat;
  67452. for (index = 0; index < this._physicsMaterials.length; index++) {
  67453. mat = this._physicsMaterials[index];
  67454. if (mat.friction === friction && mat.restitution === restitution) {
  67455. return mat;
  67456. }
  67457. }
  67458. var currentMat = new this.BJSCANNON.Material(name);
  67459. currentMat.friction = friction;
  67460. currentMat.restitution = restitution;
  67461. this._physicsMaterials.push(currentMat);
  67462. return currentMat;
  67463. };
  67464. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  67465. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  67466. };
  67467. CannonJSPlugin.prototype._createShape = function (impostor) {
  67468. var object = impostor.object;
  67469. var returnValue;
  67470. var extendSize = impostor.getObjectExtendSize();
  67471. switch (impostor.type) {
  67472. case BABYLON.PhysicsImpostor.SphereImpostor:
  67473. var radiusX = extendSize.x;
  67474. var radiusY = extendSize.y;
  67475. var radiusZ = extendSize.z;
  67476. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  67477. break;
  67478. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  67479. case BABYLON.PhysicsImpostor.CylinderImpostor:
  67480. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  67481. break;
  67482. case BABYLON.PhysicsImpostor.BoxImpostor:
  67483. var box = extendSize.scale(0.5);
  67484. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  67485. break;
  67486. case BABYLON.PhysicsImpostor.PlaneImpostor:
  67487. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  67488. returnValue = new this.BJSCANNON.Plane();
  67489. break;
  67490. case BABYLON.PhysicsImpostor.MeshImpostor:
  67491. // should transform the vertex data to world coordinates!!
  67492. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  67493. var rawFaces = object.getIndices ? object.getIndices() : [];
  67494. if (!rawVerts)
  67495. return;
  67496. // get only scale! so the object could transform correctly.
  67497. var oldPosition = object.position.clone();
  67498. var oldRotation = object.rotation && object.rotation.clone();
  67499. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  67500. object.position.copyFromFloats(0, 0, 0);
  67501. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  67502. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  67503. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  67504. var transform = object.computeWorldMatrix(true);
  67505. // convert rawVerts to object space
  67506. var temp = new Array();
  67507. var index;
  67508. for (index = 0; index < rawVerts.length; index += 3) {
  67509. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  67510. }
  67511. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  67512. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  67513. //now set back the transformation!
  67514. object.position.copyFrom(oldPosition);
  67515. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  67516. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  67517. break;
  67518. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  67519. var oldPosition2 = object.position.clone();
  67520. var oldRotation2 = object.rotation && object.rotation.clone();
  67521. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  67522. object.position.copyFromFloats(0, 0, 0);
  67523. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  67524. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  67525. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  67526. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  67527. returnValue = this._createHeightmap(object);
  67528. object.position.copyFrom(oldPosition2);
  67529. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  67530. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  67531. object.computeWorldMatrix(true);
  67532. break;
  67533. case BABYLON.PhysicsImpostor.ParticleImpostor:
  67534. returnValue = new this.BJSCANNON.Particle();
  67535. break;
  67536. }
  67537. return returnValue;
  67538. };
  67539. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  67540. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  67541. var transform = object.computeWorldMatrix(true);
  67542. // convert rawVerts to object space
  67543. var temp = new Array();
  67544. var index;
  67545. for (index = 0; index < pos.length; index += 3) {
  67546. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  67547. }
  67548. pos = temp;
  67549. var matrix = new Array();
  67550. //For now pointDepth will not be used and will be automatically calculated.
  67551. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  67552. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  67553. var boundingInfo = object.getBoundingInfo();
  67554. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  67555. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  67556. var elementSize = dim * 2 / arraySize;
  67557. for (var i = 0; i < pos.length; i = i + 3) {
  67558. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  67559. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  67560. var y = -pos[i + 2] + minY;
  67561. if (!matrix[x]) {
  67562. matrix[x] = [];
  67563. }
  67564. if (!matrix[x][z]) {
  67565. matrix[x][z] = y;
  67566. }
  67567. matrix[x][z] = Math.max(y, matrix[x][z]);
  67568. }
  67569. for (var x = 0; x <= arraySize; ++x) {
  67570. if (!matrix[x]) {
  67571. var loc = 1;
  67572. while (!matrix[(x + loc) % arraySize]) {
  67573. loc++;
  67574. }
  67575. matrix[x] = matrix[(x + loc) % arraySize].slice();
  67576. //console.log("missing x", x);
  67577. }
  67578. for (var z = 0; z <= arraySize; ++z) {
  67579. if (!matrix[x][z]) {
  67580. var loc = 1;
  67581. var newValue;
  67582. while (newValue === undefined) {
  67583. newValue = matrix[x][(z + loc++) % arraySize];
  67584. }
  67585. matrix[x][z] = newValue;
  67586. }
  67587. }
  67588. }
  67589. var shape = new this.BJSCANNON.Heightfield(matrix, {
  67590. elementSize: elementSize
  67591. });
  67592. //For future reference, needed for body transformation
  67593. shape.minY = minY;
  67594. return shape;
  67595. };
  67596. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  67597. var object = impostor.object;
  67598. //make sure it is updated...
  67599. object.computeWorldMatrix && object.computeWorldMatrix(true);
  67600. // The delta between the mesh position and the mesh bounding box center
  67601. var bInfo = object.getBoundingInfo();
  67602. if (!bInfo)
  67603. return;
  67604. var center = impostor.getObjectCenter();
  67605. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  67606. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  67607. this._tmpPosition.copyFrom(center);
  67608. var quaternion = object.rotationQuaternion;
  67609. if (!quaternion) {
  67610. return;
  67611. }
  67612. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  67613. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  67614. //-90 DEG in X, precalculated
  67615. quaternion = quaternion.multiply(this._minus90X);
  67616. //Invert! (Precalculated, 90 deg in X)
  67617. //No need to clone. this will never change.
  67618. impostor.setDeltaRotation(this._plus90X);
  67619. }
  67620. //If it is a heightfield, if should be centered.
  67621. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  67622. var mesh = object;
  67623. var boundingInfo = mesh.getBoundingInfo();
  67624. //calculate the correct body position:
  67625. var rotationQuaternion = mesh.rotationQuaternion;
  67626. mesh.rotationQuaternion = this._tmpUnityRotation;
  67627. mesh.computeWorldMatrix(true);
  67628. //get original center with no rotation
  67629. var c = center.clone();
  67630. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  67631. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  67632. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  67633. mesh.setPivotMatrix(p);
  67634. mesh.computeWorldMatrix(true);
  67635. //calculate the translation
  67636. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  67637. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  67638. //add it inverted to the delta
  67639. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  67640. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  67641. //rotation is back
  67642. mesh.rotationQuaternion = rotationQuaternion;
  67643. mesh.setPivotMatrix(oldPivot);
  67644. mesh.computeWorldMatrix(true);
  67645. }
  67646. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  67647. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  67648. //this._tmpPosition.copyFrom(object.position);
  67649. }
  67650. impostor.setDeltaPosition(this._tmpDeltaPosition);
  67651. //Now update the impostor object
  67652. impostor.physicsBody.position.copy(this._tmpPosition);
  67653. impostor.physicsBody.quaternion.copy(quaternion);
  67654. };
  67655. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  67656. impostor.object.position.copyFrom(impostor.physicsBody.position);
  67657. if (impostor.object.rotationQuaternion) {
  67658. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  67659. }
  67660. };
  67661. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  67662. impostor.physicsBody.position.copy(newPosition);
  67663. impostor.physicsBody.quaternion.copy(newRotation);
  67664. };
  67665. CannonJSPlugin.prototype.isSupported = function () {
  67666. return this.BJSCANNON !== undefined;
  67667. };
  67668. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  67669. impostor.physicsBody.velocity.copy(velocity);
  67670. };
  67671. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  67672. impostor.physicsBody.angularVelocity.copy(velocity);
  67673. };
  67674. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  67675. var v = impostor.physicsBody.velocity;
  67676. if (!v) {
  67677. return null;
  67678. }
  67679. return new BABYLON.Vector3(v.x, v.y, v.z);
  67680. };
  67681. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  67682. var v = impostor.physicsBody.angularVelocity;
  67683. if (!v) {
  67684. return null;
  67685. }
  67686. return new BABYLON.Vector3(v.x, v.y, v.z);
  67687. };
  67688. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  67689. impostor.physicsBody.mass = mass;
  67690. impostor.physicsBody.updateMassProperties();
  67691. };
  67692. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  67693. return impostor.physicsBody.mass;
  67694. };
  67695. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  67696. return impostor.physicsBody.material.friction;
  67697. };
  67698. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  67699. impostor.physicsBody.material.friction = friction;
  67700. };
  67701. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  67702. return impostor.physicsBody.material.restitution;
  67703. };
  67704. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  67705. impostor.physicsBody.material.restitution = restitution;
  67706. };
  67707. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  67708. impostor.physicsBody.sleep();
  67709. };
  67710. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  67711. impostor.physicsBody.wakeUp();
  67712. };
  67713. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  67714. joint.physicsJoint.distance = maxDistance;
  67715. };
  67716. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  67717. // if (!motorIndex) {
  67718. // joint.physicsJoint.enableMotor();
  67719. // }
  67720. // }
  67721. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  67722. // if (!motorIndex) {
  67723. // joint.physicsJoint.disableMotor();
  67724. // }
  67725. // }
  67726. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  67727. if (!motorIndex) {
  67728. joint.physicsJoint.enableMotor();
  67729. joint.physicsJoint.setMotorSpeed(speed);
  67730. if (maxForce) {
  67731. this.setLimit(joint, maxForce);
  67732. }
  67733. }
  67734. };
  67735. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  67736. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  67737. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  67738. };
  67739. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  67740. var body = impostor.physicsBody;
  67741. mesh.position.x = body.position.x;
  67742. mesh.position.y = body.position.y;
  67743. mesh.position.z = body.position.z;
  67744. if (mesh.rotationQuaternion) {
  67745. mesh.rotationQuaternion.x = body.quaternion.x;
  67746. mesh.rotationQuaternion.y = body.quaternion.y;
  67747. mesh.rotationQuaternion.z = body.quaternion.z;
  67748. mesh.rotationQuaternion.w = body.quaternion.w;
  67749. }
  67750. };
  67751. CannonJSPlugin.prototype.getRadius = function (impostor) {
  67752. var shape = impostor.physicsBody.shapes[0];
  67753. return shape.boundingSphereRadius;
  67754. };
  67755. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  67756. var shape = impostor.physicsBody.shapes[0];
  67757. result.x = shape.halfExtents.x * 2;
  67758. result.y = shape.halfExtents.y * 2;
  67759. result.z = shape.halfExtents.z * 2;
  67760. };
  67761. CannonJSPlugin.prototype.dispose = function () {
  67762. };
  67763. return CannonJSPlugin;
  67764. }());
  67765. BABYLON.CannonJSPlugin = CannonJSPlugin;
  67766. })(BABYLON || (BABYLON = {}));
  67767. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  67768. var BABYLON;
  67769. (function (BABYLON) {
  67770. var OimoJSPlugin = /** @class */ (function () {
  67771. function OimoJSPlugin(iterations) {
  67772. this.name = "OimoJSPlugin";
  67773. this._tmpImpostorsArray = [];
  67774. this._tmpPositionVector = BABYLON.Vector3.Zero();
  67775. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  67776. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  67777. this.world.worldscale(1);
  67778. this.world.clear();
  67779. //making sure no stats are calculated
  67780. this.world.isNoStat = true;
  67781. }
  67782. OimoJSPlugin.prototype.setGravity = function (gravity) {
  67783. this.world.gravity.copy(gravity);
  67784. };
  67785. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  67786. this.world.timeStep = timeStep;
  67787. };
  67788. OimoJSPlugin.prototype.getTimeStep = function () {
  67789. return this.world.timeStep;
  67790. };
  67791. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  67792. var _this = this;
  67793. impostors.forEach(function (impostor) {
  67794. impostor.beforeStep();
  67795. });
  67796. this.world.step();
  67797. impostors.forEach(function (impostor) {
  67798. impostor.afterStep();
  67799. //update the ordered impostors array
  67800. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  67801. });
  67802. //check for collisions
  67803. var contact = this.world.contacts;
  67804. while (contact !== null) {
  67805. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  67806. contact = contact.next;
  67807. continue;
  67808. }
  67809. //is this body colliding with any other? get the impostor
  67810. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  67811. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  67812. if (!mainImpostor || !collidingImpostor) {
  67813. contact = contact.next;
  67814. continue;
  67815. }
  67816. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  67817. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  67818. contact = contact.next;
  67819. }
  67820. };
  67821. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  67822. var mass = impostor.physicsBody.massInfo.mass;
  67823. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  67824. };
  67825. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  67826. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  67827. this.applyImpulse(impostor, force, contactPoint);
  67828. };
  67829. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  67830. var _this = this;
  67831. //parent-child relationship. Does this impostor has a parent impostor?
  67832. if (impostor.parent) {
  67833. if (impostor.physicsBody) {
  67834. this.removePhysicsBody(impostor);
  67835. //TODO is that needed?
  67836. impostor.forceUpdate();
  67837. }
  67838. return;
  67839. }
  67840. if (impostor.isBodyInitRequired()) {
  67841. var bodyConfig = {
  67842. name: impostor.uniqueId,
  67843. //Oimo must have mass, also for static objects.
  67844. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  67845. size: [],
  67846. type: [],
  67847. pos: [],
  67848. rot: [],
  67849. move: impostor.getParam("mass") !== 0,
  67850. //Supporting older versions of Oimo
  67851. world: this.world
  67852. };
  67853. var impostors = [impostor];
  67854. var addToArray = function (parent) {
  67855. if (!parent.getChildMeshes)
  67856. return;
  67857. parent.getChildMeshes().forEach(function (m) {
  67858. if (m.physicsImpostor) {
  67859. impostors.push(m.physicsImpostor);
  67860. //m.physicsImpostor._init();
  67861. }
  67862. });
  67863. };
  67864. addToArray(impostor.object);
  67865. var checkWithEpsilon_1 = function (value) {
  67866. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  67867. };
  67868. impostors.forEach(function (i) {
  67869. if (!impostor.object.rotationQuaternion) {
  67870. return;
  67871. }
  67872. //get the correct bounding box
  67873. var oldQuaternion = i.object.rotationQuaternion;
  67874. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  67875. x: impostor.object.rotationQuaternion.x,
  67876. y: impostor.object.rotationQuaternion.y,
  67877. z: impostor.object.rotationQuaternion.z,
  67878. s: impostor.object.rotationQuaternion.w
  67879. });
  67880. var extendSize = i.getObjectExtendSize();
  67881. if (i === impostor) {
  67882. var center = impostor.getObjectCenter();
  67883. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  67884. //Can also use Array.prototype.push.apply
  67885. bodyConfig.pos.push(center.x);
  67886. bodyConfig.pos.push(center.y);
  67887. bodyConfig.pos.push(center.z);
  67888. //tmp solution
  67889. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  67890. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  67891. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  67892. }
  67893. else {
  67894. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  67895. bodyConfig.pos.push(localPosition.x);
  67896. bodyConfig.pos.push(localPosition.y);
  67897. bodyConfig.pos.push(localPosition.z);
  67898. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  67899. bodyConfig.rot.push(0);
  67900. bodyConfig.rot.push(0);
  67901. bodyConfig.rot.push(0);
  67902. }
  67903. // register mesh
  67904. switch (i.type) {
  67905. case BABYLON.PhysicsImpostor.ParticleImpostor:
  67906. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  67907. case BABYLON.PhysicsImpostor.SphereImpostor:
  67908. var radiusX = extendSize.x;
  67909. var radiusY = extendSize.y;
  67910. var radiusZ = extendSize.z;
  67911. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  67912. bodyConfig.type.push('sphere');
  67913. //due to the way oimo works with compounds, add 3 times
  67914. bodyConfig.size.push(size);
  67915. bodyConfig.size.push(size);
  67916. bodyConfig.size.push(size);
  67917. break;
  67918. case BABYLON.PhysicsImpostor.CylinderImpostor:
  67919. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  67920. var sizeY = checkWithEpsilon_1(extendSize.y);
  67921. bodyConfig.type.push('cylinder');
  67922. bodyConfig.size.push(sizeX);
  67923. bodyConfig.size.push(sizeY);
  67924. //due to the way oimo works with compounds, add one more value.
  67925. bodyConfig.size.push(sizeY);
  67926. break;
  67927. case BABYLON.PhysicsImpostor.PlaneImpostor:
  67928. case BABYLON.PhysicsImpostor.BoxImpostor:
  67929. default:
  67930. var sizeX = checkWithEpsilon_1(extendSize.x);
  67931. var sizeY = checkWithEpsilon_1(extendSize.y);
  67932. var sizeZ = checkWithEpsilon_1(extendSize.z);
  67933. bodyConfig.type.push('box');
  67934. bodyConfig.size.push(sizeX);
  67935. bodyConfig.size.push(sizeY);
  67936. bodyConfig.size.push(sizeZ);
  67937. break;
  67938. }
  67939. //actually not needed, but hey...
  67940. i.object.rotationQuaternion = oldQuaternion;
  67941. });
  67942. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  67943. }
  67944. else {
  67945. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  67946. }
  67947. impostor.setDeltaPosition(this._tmpPositionVector);
  67948. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  67949. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  67950. };
  67951. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  67952. //impostor.physicsBody.dispose();
  67953. //Same as : (older oimo versions)
  67954. this.world.removeRigidBody(impostor.physicsBody);
  67955. };
  67956. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  67957. var mainBody = impostorJoint.mainImpostor.physicsBody;
  67958. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  67959. if (!mainBody || !connectedBody) {
  67960. return;
  67961. }
  67962. var jointData = impostorJoint.joint.jointData;
  67963. var options = jointData.nativeParams || {};
  67964. var type;
  67965. var nativeJointData = {
  67966. body1: mainBody,
  67967. body2: connectedBody,
  67968. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  67969. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  67970. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  67971. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  67972. min: options.min,
  67973. max: options.max,
  67974. collision: options.collision || jointData.collision,
  67975. spring: options.spring,
  67976. //supporting older version of Oimo
  67977. world: this.world
  67978. };
  67979. switch (impostorJoint.joint.type) {
  67980. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  67981. type = "jointBall";
  67982. break;
  67983. case BABYLON.PhysicsJoint.SpringJoint:
  67984. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  67985. var springData = jointData;
  67986. nativeJointData.min = springData.length || nativeJointData.min;
  67987. //Max should also be set, just make sure it is at least min
  67988. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  67989. case BABYLON.PhysicsJoint.DistanceJoint:
  67990. type = "jointDistance";
  67991. nativeJointData.max = jointData.maxDistance;
  67992. break;
  67993. case BABYLON.PhysicsJoint.PrismaticJoint:
  67994. type = "jointPrisme";
  67995. break;
  67996. case BABYLON.PhysicsJoint.SliderJoint:
  67997. type = "jointSlide";
  67998. break;
  67999. case BABYLON.PhysicsJoint.WheelJoint:
  68000. type = "jointWheel";
  68001. break;
  68002. case BABYLON.PhysicsJoint.HingeJoint:
  68003. default:
  68004. type = "jointHinge";
  68005. break;
  68006. }
  68007. nativeJointData.type = type;
  68008. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  68009. };
  68010. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  68011. //Bug in Oimo prevents us from disposing a joint in the playground
  68012. //joint.joint.physicsJoint.dispose();
  68013. //So we will bruteforce it!
  68014. try {
  68015. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  68016. }
  68017. catch (e) {
  68018. BABYLON.Tools.Warn(e);
  68019. }
  68020. };
  68021. OimoJSPlugin.prototype.isSupported = function () {
  68022. return this.BJSOIMO !== undefined;
  68023. };
  68024. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  68025. if (!impostor.physicsBody.sleeping) {
  68026. //TODO check that
  68027. if (impostor.physicsBody.shapes.next) {
  68028. var parentShape = this._getLastShape(impostor.physicsBody);
  68029. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  68030. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  68031. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  68032. }
  68033. else {
  68034. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  68035. }
  68036. if (impostor.object.rotationQuaternion) {
  68037. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  68038. impostor.object.rotationQuaternion.normalize();
  68039. }
  68040. }
  68041. };
  68042. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  68043. var body = impostor.physicsBody;
  68044. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  68045. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  68046. body.syncShapes();
  68047. body.awake();
  68048. };
  68049. OimoJSPlugin.prototype._getLastShape = function (body) {
  68050. var lastShape = body.shapes;
  68051. while (lastShape.next) {
  68052. lastShape = lastShape.next;
  68053. }
  68054. return lastShape;
  68055. };
  68056. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  68057. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  68058. };
  68059. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  68060. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  68061. };
  68062. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  68063. var v = impostor.physicsBody.linearVelocity;
  68064. if (!v) {
  68065. return null;
  68066. }
  68067. return new BABYLON.Vector3(v.x, v.y, v.z);
  68068. };
  68069. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  68070. var v = impostor.physicsBody.angularVelocity;
  68071. if (!v) {
  68072. return null;
  68073. }
  68074. return new BABYLON.Vector3(v.x, v.y, v.z);
  68075. };
  68076. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  68077. var staticBody = mass === 0;
  68078. //this will actually set the body's density and not its mass.
  68079. //But this is how oimo treats the mass variable.
  68080. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  68081. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  68082. };
  68083. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  68084. return impostor.physicsBody.shapes.density;
  68085. };
  68086. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  68087. return impostor.physicsBody.shapes.friction;
  68088. };
  68089. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  68090. impostor.physicsBody.shapes.friction = friction;
  68091. };
  68092. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  68093. return impostor.physicsBody.shapes.restitution;
  68094. };
  68095. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  68096. impostor.physicsBody.shapes.restitution = restitution;
  68097. };
  68098. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  68099. impostor.physicsBody.sleep();
  68100. };
  68101. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  68102. impostor.physicsBody.awake();
  68103. };
  68104. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  68105. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  68106. if (minDistance !== void 0) {
  68107. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  68108. }
  68109. };
  68110. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  68111. //TODO separate rotational and transational motors.
  68112. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  68113. if (motor) {
  68114. motor.setMotor(speed, maxForce);
  68115. }
  68116. };
  68117. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  68118. //TODO separate rotational and transational motors.
  68119. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  68120. if (motor) {
  68121. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  68122. }
  68123. };
  68124. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  68125. var body = impostor.physicsBody;
  68126. mesh.position.x = body.position.x;
  68127. mesh.position.y = body.position.y;
  68128. mesh.position.z = body.position.z;
  68129. if (mesh.rotationQuaternion) {
  68130. mesh.rotationQuaternion.x = body.orientation.x;
  68131. mesh.rotationQuaternion.y = body.orientation.y;
  68132. mesh.rotationQuaternion.z = body.orientation.z;
  68133. mesh.rotationQuaternion.w = body.orientation.s;
  68134. }
  68135. };
  68136. OimoJSPlugin.prototype.getRadius = function (impostor) {
  68137. return impostor.physicsBody.shapes.radius;
  68138. };
  68139. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  68140. var shape = impostor.physicsBody.shapes;
  68141. result.x = shape.halfWidth * 2;
  68142. result.y = shape.halfHeight * 2;
  68143. result.z = shape.halfDepth * 2;
  68144. };
  68145. OimoJSPlugin.prototype.dispose = function () {
  68146. this.world.clear();
  68147. };
  68148. return OimoJSPlugin;
  68149. }());
  68150. BABYLON.OimoJSPlugin = OimoJSPlugin;
  68151. })(BABYLON || (BABYLON = {}));
  68152. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  68153. var BABYLON;
  68154. (function (BABYLON) {
  68155. var Internals;
  68156. (function (Internals) {
  68157. /*
  68158. * Based on jsTGALoader - Javascript loader for TGA file
  68159. * By Vincent Thibault
  68160. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  68161. */
  68162. var TGATools = /** @class */ (function () {
  68163. function TGATools() {
  68164. }
  68165. TGATools.GetTGAHeader = function (data) {
  68166. var offset = 0;
  68167. var header = {
  68168. id_length: data[offset++],
  68169. colormap_type: data[offset++],
  68170. image_type: data[offset++],
  68171. colormap_index: data[offset++] | data[offset++] << 8,
  68172. colormap_length: data[offset++] | data[offset++] << 8,
  68173. colormap_size: data[offset++],
  68174. origin: [
  68175. data[offset++] | data[offset++] << 8,
  68176. data[offset++] | data[offset++] << 8
  68177. ],
  68178. width: data[offset++] | data[offset++] << 8,
  68179. height: data[offset++] | data[offset++] << 8,
  68180. pixel_size: data[offset++],
  68181. flags: data[offset++]
  68182. };
  68183. return header;
  68184. };
  68185. TGATools.UploadContent = function (gl, data) {
  68186. // Not enough data to contain header ?
  68187. if (data.length < 19) {
  68188. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  68189. return;
  68190. }
  68191. // Read Header
  68192. var offset = 18;
  68193. var header = TGATools.GetTGAHeader(data);
  68194. // Assume it's a valid Targa file.
  68195. if (header.id_length + offset > data.length) {
  68196. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  68197. return;
  68198. }
  68199. // Skip not needed data
  68200. offset += header.id_length;
  68201. var use_rle = false;
  68202. var use_pal = false;
  68203. var use_grey = false;
  68204. // Get some informations.
  68205. switch (header.image_type) {
  68206. case TGATools._TYPE_RLE_INDEXED:
  68207. use_rle = true;
  68208. case TGATools._TYPE_INDEXED:
  68209. use_pal = true;
  68210. break;
  68211. case TGATools._TYPE_RLE_RGB:
  68212. use_rle = true;
  68213. case TGATools._TYPE_RGB:
  68214. // use_rgb = true;
  68215. break;
  68216. case TGATools._TYPE_RLE_GREY:
  68217. use_rle = true;
  68218. case TGATools._TYPE_GREY:
  68219. use_grey = true;
  68220. break;
  68221. }
  68222. var pixel_data;
  68223. // var numAlphaBits = header.flags & 0xf;
  68224. var pixel_size = header.pixel_size >> 3;
  68225. var pixel_total = header.width * header.height * pixel_size;
  68226. // Read palettes
  68227. var palettes;
  68228. if (use_pal) {
  68229. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  68230. }
  68231. // Read LRE
  68232. if (use_rle) {
  68233. pixel_data = new Uint8Array(pixel_total);
  68234. var c, count, i;
  68235. var localOffset = 0;
  68236. var pixels = new Uint8Array(pixel_size);
  68237. while (offset < pixel_total && localOffset < pixel_total) {
  68238. c = data[offset++];
  68239. count = (c & 0x7f) + 1;
  68240. // RLE pixels
  68241. if (c & 0x80) {
  68242. // Bind pixel tmp array
  68243. for (i = 0; i < pixel_size; ++i) {
  68244. pixels[i] = data[offset++];
  68245. }
  68246. // Copy pixel array
  68247. for (i = 0; i < count; ++i) {
  68248. pixel_data.set(pixels, localOffset + i * pixel_size);
  68249. }
  68250. localOffset += pixel_size * count;
  68251. }
  68252. else {
  68253. count *= pixel_size;
  68254. for (i = 0; i < count; ++i) {
  68255. pixel_data[localOffset + i] = data[offset++];
  68256. }
  68257. localOffset += count;
  68258. }
  68259. }
  68260. }
  68261. else {
  68262. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  68263. }
  68264. // Load to texture
  68265. var x_start, y_start, x_step, y_step, y_end, x_end;
  68266. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  68267. default:
  68268. case TGATools._ORIGIN_UL:
  68269. x_start = 0;
  68270. x_step = 1;
  68271. x_end = header.width;
  68272. y_start = 0;
  68273. y_step = 1;
  68274. y_end = header.height;
  68275. break;
  68276. case TGATools._ORIGIN_BL:
  68277. x_start = 0;
  68278. x_step = 1;
  68279. x_end = header.width;
  68280. y_start = header.height - 1;
  68281. y_step = -1;
  68282. y_end = -1;
  68283. break;
  68284. case TGATools._ORIGIN_UR:
  68285. x_start = header.width - 1;
  68286. x_step = -1;
  68287. x_end = -1;
  68288. y_start = 0;
  68289. y_step = 1;
  68290. y_end = header.height;
  68291. break;
  68292. case TGATools._ORIGIN_BR:
  68293. x_start = header.width - 1;
  68294. x_step = -1;
  68295. x_end = -1;
  68296. y_start = header.height - 1;
  68297. y_step = -1;
  68298. y_end = -1;
  68299. break;
  68300. }
  68301. // Load the specify method
  68302. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  68303. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  68304. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  68305. };
  68306. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  68307. var image = pixel_data, colormap = palettes;
  68308. var width = header.width, height = header.height;
  68309. var color, i = 0, x, y;
  68310. var imageData = new Uint8Array(width * height * 4);
  68311. for (y = y_start; y !== y_end; y += y_step) {
  68312. for (x = x_start; x !== x_end; x += x_step, i++) {
  68313. color = image[i];
  68314. imageData[(x + width * y) * 4 + 3] = 255;
  68315. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  68316. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  68317. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  68318. }
  68319. }
  68320. return imageData;
  68321. };
  68322. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  68323. var image = pixel_data;
  68324. var width = header.width, height = header.height;
  68325. var color, i = 0, x, y;
  68326. var imageData = new Uint8Array(width * height * 4);
  68327. for (y = y_start; y !== y_end; y += y_step) {
  68328. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  68329. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  68330. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  68331. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  68332. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  68333. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  68334. }
  68335. }
  68336. return imageData;
  68337. };
  68338. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  68339. var image = pixel_data;
  68340. var width = header.width, height = header.height;
  68341. var i = 0, x, y;
  68342. var imageData = new Uint8Array(width * height * 4);
  68343. for (y = y_start; y !== y_end; y += y_step) {
  68344. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  68345. imageData[(x + width * y) * 4 + 3] = 255;
  68346. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  68347. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  68348. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  68349. }
  68350. }
  68351. return imageData;
  68352. };
  68353. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  68354. var image = pixel_data;
  68355. var width = header.width, height = header.height;
  68356. var i = 0, x, y;
  68357. var imageData = new Uint8Array(width * height * 4);
  68358. for (y = y_start; y !== y_end; y += y_step) {
  68359. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  68360. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  68361. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  68362. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  68363. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  68364. }
  68365. }
  68366. return imageData;
  68367. };
  68368. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  68369. var image = pixel_data;
  68370. var width = header.width, height = header.height;
  68371. var color, i = 0, x, y;
  68372. var imageData = new Uint8Array(width * height * 4);
  68373. for (y = y_start; y !== y_end; y += y_step) {
  68374. for (x = x_start; x !== x_end; x += x_step, i++) {
  68375. color = image[i];
  68376. imageData[(x + width * y) * 4 + 0] = color;
  68377. imageData[(x + width * y) * 4 + 1] = color;
  68378. imageData[(x + width * y) * 4 + 2] = color;
  68379. imageData[(x + width * y) * 4 + 3] = 255;
  68380. }
  68381. }
  68382. return imageData;
  68383. };
  68384. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  68385. var image = pixel_data;
  68386. var width = header.width, height = header.height;
  68387. var i = 0, x, y;
  68388. var imageData = new Uint8Array(width * height * 4);
  68389. for (y = y_start; y !== y_end; y += y_step) {
  68390. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  68391. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  68392. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  68393. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  68394. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  68395. }
  68396. }
  68397. return imageData;
  68398. };
  68399. //private static _TYPE_NO_DATA = 0;
  68400. TGATools._TYPE_INDEXED = 1;
  68401. TGATools._TYPE_RGB = 2;
  68402. TGATools._TYPE_GREY = 3;
  68403. TGATools._TYPE_RLE_INDEXED = 9;
  68404. TGATools._TYPE_RLE_RGB = 10;
  68405. TGATools._TYPE_RLE_GREY = 11;
  68406. TGATools._ORIGIN_MASK = 0x30;
  68407. TGATools._ORIGIN_SHIFT = 0x04;
  68408. TGATools._ORIGIN_BL = 0x00;
  68409. TGATools._ORIGIN_BR = 0x01;
  68410. TGATools._ORIGIN_UL = 0x02;
  68411. TGATools._ORIGIN_UR = 0x03;
  68412. return TGATools;
  68413. }());
  68414. Internals.TGATools = TGATools;
  68415. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  68416. })(BABYLON || (BABYLON = {}));
  68417. //# sourceMappingURL=babylon.tga.js.map
  68418. var BABYLON;
  68419. (function (BABYLON) {
  68420. var Internals;
  68421. (function (Internals) {
  68422. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  68423. // All values and structures referenced from:
  68424. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  68425. var DDS_MAGIC = 0x20534444;
  68426. var
  68427. //DDSD_CAPS = 0x1,
  68428. //DDSD_HEIGHT = 0x2,
  68429. //DDSD_WIDTH = 0x4,
  68430. //DDSD_PITCH = 0x8,
  68431. //DDSD_PIXELFORMAT = 0x1000,
  68432. DDSD_MIPMAPCOUNT = 0x20000;
  68433. //DDSD_LINEARSIZE = 0x80000,
  68434. //DDSD_DEPTH = 0x800000;
  68435. // var DDSCAPS_COMPLEX = 0x8,
  68436. // DDSCAPS_MIPMAP = 0x400000,
  68437. // DDSCAPS_TEXTURE = 0x1000;
  68438. var DDSCAPS2_CUBEMAP = 0x200;
  68439. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  68440. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  68441. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  68442. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  68443. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  68444. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  68445. // DDSCAPS2_VOLUME = 0x200000;
  68446. var
  68447. //DDPF_ALPHAPIXELS = 0x1,
  68448. //DDPF_ALPHA = 0x2,
  68449. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  68450. //DDPF_YUV = 0x200,
  68451. DDPF_LUMINANCE = 0x20000;
  68452. function FourCCToInt32(value) {
  68453. return value.charCodeAt(0) +
  68454. (value.charCodeAt(1) << 8) +
  68455. (value.charCodeAt(2) << 16) +
  68456. (value.charCodeAt(3) << 24);
  68457. }
  68458. function Int32ToFourCC(value) {
  68459. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  68460. }
  68461. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  68462. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  68463. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  68464. var FOURCC_DX10 = FourCCToInt32("DX10");
  68465. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  68466. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  68467. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  68468. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  68469. var headerLengthInt = 31; // The header length in 32 bit ints
  68470. // Offsets into the header array
  68471. var off_magic = 0;
  68472. var off_size = 1;
  68473. var off_flags = 2;
  68474. var off_height = 3;
  68475. var off_width = 4;
  68476. var off_mipmapCount = 7;
  68477. var off_pfFlags = 20;
  68478. var off_pfFourCC = 21;
  68479. var off_RGBbpp = 22;
  68480. // var off_RMask = 23;
  68481. // var off_GMask = 24;
  68482. // var off_BMask = 25;
  68483. // var off_AMask = 26;
  68484. // var off_caps1 = 27;
  68485. var off_caps2 = 28;
  68486. // var off_caps3 = 29;
  68487. // var off_caps4 = 30;
  68488. var off_dxgiFormat = 32;
  68489. ;
  68490. var DDSTools = /** @class */ (function () {
  68491. function DDSTools() {
  68492. }
  68493. DDSTools.GetDDSInfo = function (arrayBuffer) {
  68494. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  68495. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  68496. var mipmapCount = 1;
  68497. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  68498. mipmapCount = Math.max(1, header[off_mipmapCount]);
  68499. }
  68500. var fourCC = header[off_pfFourCC];
  68501. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  68502. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68503. switch (fourCC) {
  68504. case FOURCC_D3DFMT_R16G16B16A16F:
  68505. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68506. break;
  68507. case FOURCC_D3DFMT_R32G32B32A32F:
  68508. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  68509. break;
  68510. case FOURCC_DX10:
  68511. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  68512. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68513. break;
  68514. }
  68515. }
  68516. return {
  68517. width: header[off_width],
  68518. height: header[off_height],
  68519. mipmapCount: mipmapCount,
  68520. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  68521. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  68522. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  68523. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  68524. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  68525. dxgiFormat: dxgiFormat,
  68526. textureType: textureType
  68527. };
  68528. };
  68529. DDSTools._ToHalfFloat = function (value) {
  68530. if (!DDSTools._FloatView) {
  68531. DDSTools._FloatView = new Float32Array(1);
  68532. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  68533. }
  68534. DDSTools._FloatView[0] = value;
  68535. var x = DDSTools._Int32View[0];
  68536. var bits = (x >> 16) & 0x8000; /* Get the sign */
  68537. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  68538. var e = (x >> 23) & 0xff; /* Using int is faster here */
  68539. /* If zero, or denormal, or exponent underflows too much for a denormal
  68540. * half, return signed zero. */
  68541. if (e < 103) {
  68542. return bits;
  68543. }
  68544. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  68545. if (e > 142) {
  68546. bits |= 0x7c00;
  68547. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  68548. * not Inf, so make sure we set one mantissa bit too. */
  68549. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  68550. return bits;
  68551. }
  68552. /* If exponent underflows but not too much, return a denormal */
  68553. if (e < 113) {
  68554. m |= 0x0800;
  68555. /* Extra rounding may overflow and set mantissa to 0 and exponent
  68556. * to 1, which is OK. */
  68557. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  68558. return bits;
  68559. }
  68560. bits |= ((e - 112) << 10) | (m >> 1);
  68561. bits += m & 1;
  68562. return bits;
  68563. };
  68564. DDSTools._FromHalfFloat = function (value) {
  68565. var s = (value & 0x8000) >> 15;
  68566. var e = (value & 0x7C00) >> 10;
  68567. var f = value & 0x03FF;
  68568. if (e === 0) {
  68569. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  68570. }
  68571. else if (e == 0x1F) {
  68572. return f ? NaN : ((s ? -1 : 1) * Infinity);
  68573. }
  68574. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  68575. };
  68576. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  68577. var destArray = new Float32Array(dataLength);
  68578. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  68579. var index = 0;
  68580. for (var y = 0; y < height; y++) {
  68581. for (var x = 0; x < width; x++) {
  68582. var srcPos = (x + y * width) * 4;
  68583. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  68584. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  68585. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  68586. if (DDSTools.StoreLODInAlphaChannel) {
  68587. destArray[index + 3] = lod;
  68588. }
  68589. else {
  68590. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  68591. }
  68592. index += 4;
  68593. }
  68594. }
  68595. return destArray;
  68596. };
  68597. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  68598. if (DDSTools.StoreLODInAlphaChannel) {
  68599. var destArray = new Uint16Array(dataLength);
  68600. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  68601. var index = 0;
  68602. for (var y = 0; y < height; y++) {
  68603. for (var x = 0; x < width; x++) {
  68604. var srcPos = (x + y * width) * 4;
  68605. destArray[index] = srcData[srcPos];
  68606. destArray[index + 1] = srcData[srcPos + 1];
  68607. destArray[index + 2] = srcData[srcPos + 2];
  68608. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  68609. index += 4;
  68610. }
  68611. }
  68612. return destArray;
  68613. }
  68614. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  68615. };
  68616. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  68617. if (DDSTools.StoreLODInAlphaChannel) {
  68618. var destArray = new Float32Array(dataLength);
  68619. var srcData = new Float32Array(arrayBuffer, dataOffset);
  68620. var index = 0;
  68621. for (var y = 0; y < height; y++) {
  68622. for (var x = 0; x < width; x++) {
  68623. var srcPos = (x + y * width) * 4;
  68624. destArray[index] = srcData[srcPos];
  68625. destArray[index + 1] = srcData[srcPos + 1];
  68626. destArray[index + 2] = srcData[srcPos + 2];
  68627. destArray[index + 3] = lod;
  68628. index += 4;
  68629. }
  68630. }
  68631. return destArray;
  68632. }
  68633. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  68634. };
  68635. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  68636. var destArray = new Uint8Array(dataLength);
  68637. var srcData = new Float32Array(arrayBuffer, dataOffset);
  68638. var index = 0;
  68639. for (var y = 0; y < height; y++) {
  68640. for (var x = 0; x < width; x++) {
  68641. var srcPos = (x + y * width) * 4;
  68642. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  68643. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  68644. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  68645. if (DDSTools.StoreLODInAlphaChannel) {
  68646. destArray[index + 3] = lod;
  68647. }
  68648. else {
  68649. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  68650. }
  68651. index += 4;
  68652. }
  68653. }
  68654. return destArray;
  68655. };
  68656. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  68657. var destArray = new Uint8Array(dataLength);
  68658. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  68659. var index = 0;
  68660. for (var y = 0; y < height; y++) {
  68661. for (var x = 0; x < width; x++) {
  68662. var srcPos = (x + y * width) * 4;
  68663. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  68664. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  68665. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  68666. if (DDSTools.StoreLODInAlphaChannel) {
  68667. destArray[index + 3] = lod;
  68668. }
  68669. else {
  68670. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  68671. }
  68672. index += 4;
  68673. }
  68674. }
  68675. return destArray;
  68676. };
  68677. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  68678. var byteArray = new Uint8Array(dataLength);
  68679. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  68680. var index = 0;
  68681. for (var y = 0; y < height; y++) {
  68682. for (var x = 0; x < width; x++) {
  68683. var srcPos = (x + y * width) * 4;
  68684. byteArray[index] = srcData[srcPos + 2];
  68685. byteArray[index + 1] = srcData[srcPos + 1];
  68686. byteArray[index + 2] = srcData[srcPos];
  68687. byteArray[index + 3] = srcData[srcPos + 3];
  68688. index += 4;
  68689. }
  68690. }
  68691. return byteArray;
  68692. };
  68693. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  68694. var byteArray = new Uint8Array(dataLength);
  68695. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  68696. var index = 0;
  68697. for (var y = 0; y < height; y++) {
  68698. for (var x = 0; x < width; x++) {
  68699. var srcPos = (x + y * width) * 3;
  68700. byteArray[index] = srcData[srcPos + 2];
  68701. byteArray[index + 1] = srcData[srcPos + 1];
  68702. byteArray[index + 2] = srcData[srcPos];
  68703. index += 3;
  68704. }
  68705. }
  68706. return byteArray;
  68707. };
  68708. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  68709. var byteArray = new Uint8Array(dataLength);
  68710. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  68711. var index = 0;
  68712. for (var y = 0; y < height; y++) {
  68713. for (var x = 0; x < width; x++) {
  68714. var srcPos = (x + y * width);
  68715. byteArray[index] = srcData[srcPos];
  68716. index++;
  68717. }
  68718. }
  68719. return byteArray;
  68720. };
  68721. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  68722. if (lodIndex === void 0) { lodIndex = -1; }
  68723. var ext = engine.getCaps().s3tc;
  68724. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  68725. var fourCC, width, height, dataLength = 0, dataOffset;
  68726. var byteArray, mipmapCount, mip;
  68727. var internalFormat = 0;
  68728. var format = 0;
  68729. var blockBytes = 1;
  68730. if (header[off_magic] !== DDS_MAGIC) {
  68731. BABYLON.Tools.Error("Invalid magic number in DDS header");
  68732. return;
  68733. }
  68734. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  68735. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  68736. return;
  68737. }
  68738. if (info.isCompressed && !ext) {
  68739. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  68740. return;
  68741. }
  68742. var bpp = header[off_RGBbpp];
  68743. dataOffset = header[off_size] + 4;
  68744. var computeFormats = false;
  68745. if (info.isFourCC) {
  68746. fourCC = header[off_pfFourCC];
  68747. switch (fourCC) {
  68748. case FOURCC_DXT1:
  68749. blockBytes = 8;
  68750. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  68751. break;
  68752. case FOURCC_DXT3:
  68753. blockBytes = 16;
  68754. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  68755. break;
  68756. case FOURCC_DXT5:
  68757. blockBytes = 16;
  68758. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  68759. break;
  68760. case FOURCC_D3DFMT_R16G16B16A16F:
  68761. computeFormats = true;
  68762. break;
  68763. case FOURCC_D3DFMT_R32G32B32A32F:
  68764. computeFormats = true;
  68765. break;
  68766. case FOURCC_DX10:
  68767. // There is an additionnal header so dataOffset need to be changed
  68768. dataOffset += 5 * 4; // 5 uints
  68769. var supported = false;
  68770. switch (info.dxgiFormat) {
  68771. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  68772. computeFormats = true;
  68773. supported = true;
  68774. break;
  68775. case DXGI_FORMAT_B8G8R8X8_UNORM:
  68776. info.isRGB = true;
  68777. info.isFourCC = false;
  68778. bpp = 32;
  68779. supported = true;
  68780. break;
  68781. }
  68782. if (supported) {
  68783. break;
  68784. }
  68785. default:
  68786. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  68787. return;
  68788. }
  68789. }
  68790. if (computeFormats) {
  68791. format = engine._getWebGLTextureType(info.textureType);
  68792. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  68793. }
  68794. mipmapCount = 1;
  68795. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  68796. mipmapCount = Math.max(1, header[off_mipmapCount]);
  68797. }
  68798. for (var face = 0; face < faces; face++) {
  68799. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  68800. width = header[off_width];
  68801. height = header[off_height];
  68802. for (mip = 0; mip < mipmapCount; ++mip) {
  68803. if (lodIndex === -1 || lodIndex === mip) {
  68804. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  68805. var i = (lodIndex === -1) ? mip : 0;
  68806. if (!info.isCompressed && info.isFourCC) {
  68807. dataLength = width * height * 4;
  68808. var floatArray = null;
  68809. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  68810. if (bpp === 128) {
  68811. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  68812. }
  68813. else if (bpp === 64) {
  68814. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  68815. }
  68816. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68817. format = engine._getWebGLTextureType(info.textureType);
  68818. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  68819. }
  68820. else {
  68821. if (bpp === 128) {
  68822. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  68823. }
  68824. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  68825. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  68826. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  68827. format = engine._getWebGLTextureType(info.textureType);
  68828. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  68829. }
  68830. else {
  68831. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  68832. }
  68833. }
  68834. if (floatArray) {
  68835. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  68836. }
  68837. }
  68838. else if (info.isRGB) {
  68839. if (bpp === 24) {
  68840. dataLength = width * height * 3;
  68841. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  68842. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  68843. }
  68844. else {
  68845. dataLength = width * height * 4;
  68846. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  68847. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  68848. }
  68849. }
  68850. else if (info.isLuminance) {
  68851. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  68852. var unpaddedRowSize = width;
  68853. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  68854. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  68855. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  68856. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  68857. }
  68858. else {
  68859. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  68860. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  68861. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  68862. }
  68863. }
  68864. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  68865. width *= 0.5;
  68866. height *= 0.5;
  68867. width = Math.max(1.0, width);
  68868. height = Math.max(1.0, height);
  68869. }
  68870. if (currentFace !== undefined) {
  68871. // Loading a single face
  68872. break;
  68873. }
  68874. }
  68875. };
  68876. DDSTools.StoreLODInAlphaChannel = false;
  68877. return DDSTools;
  68878. }());
  68879. Internals.DDSTools = DDSTools;
  68880. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  68881. })(BABYLON || (BABYLON = {}));
  68882. //# sourceMappingURL=babylon.dds.js.map
  68883. var BABYLON;
  68884. (function (BABYLON) {
  68885. var Internals;
  68886. (function (Internals) {
  68887. /**
  68888. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  68889. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  68890. */
  68891. var KhronosTextureContainer = /** @class */ (function () {
  68892. /**
  68893. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  68894. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  68895. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  68896. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  68897. */
  68898. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  68899. this.arrayBuffer = arrayBuffer;
  68900. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  68901. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  68902. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  68903. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  68904. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  68905. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  68906. BABYLON.Tools.Error("texture missing KTX identifier");
  68907. return;
  68908. }
  68909. // load the reset of the header in native 32 bit int
  68910. var header = new Int32Array(this.arrayBuffer, 12, 13);
  68911. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  68912. var oppositeEndianess = header[0] === 0x01020304;
  68913. // read all the header elements in order they exist in the file, without modification (sans endainness)
  68914. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  68915. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  68916. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  68917. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  68918. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  68919. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  68920. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  68921. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  68922. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  68923. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  68924. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  68925. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  68926. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  68927. if (this.glType !== 0) {
  68928. BABYLON.Tools.Error("only compressed formats currently supported");
  68929. return;
  68930. }
  68931. else {
  68932. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  68933. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  68934. }
  68935. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  68936. BABYLON.Tools.Error("only 2D textures currently supported");
  68937. return;
  68938. }
  68939. if (this.numberOfArrayElements !== 0) {
  68940. BABYLON.Tools.Error("texture arrays not currently supported");
  68941. return;
  68942. }
  68943. if (this.numberOfFaces !== facesExpected) {
  68944. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  68945. return;
  68946. }
  68947. // we now have a completely validated file, so could use existence of loadType as success
  68948. // would need to make this more elaborate & adjust checks above to support more than one load type
  68949. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  68950. }
  68951. // not as fast hardware based, but will probably never need to use
  68952. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  68953. return ((val & 0xFF) << 24)
  68954. | ((val & 0xFF00) << 8)
  68955. | ((val >> 8) & 0xFF00)
  68956. | ((val >> 24) & 0xFF);
  68957. };
  68958. /**
  68959. * It is assumed that the texture has already been created & is currently bound
  68960. */
  68961. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  68962. switch (this.loadType) {
  68963. case KhronosTextureContainer.COMPRESSED_2D:
  68964. this._upload2DCompressedLevels(gl, loadMipmaps);
  68965. break;
  68966. case KhronosTextureContainer.TEX_2D:
  68967. case KhronosTextureContainer.COMPRESSED_3D:
  68968. case KhronosTextureContainer.TEX_3D:
  68969. }
  68970. };
  68971. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  68972. // initialize width & height for level 1
  68973. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  68974. var width = this.pixelWidth;
  68975. var height = this.pixelHeight;
  68976. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  68977. for (var level = 0; level < mipmapCount; level++) {
  68978. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  68979. for (var face = 0; face < this.numberOfFaces; face++) {
  68980. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  68981. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  68982. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  68983. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  68984. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  68985. }
  68986. width = Math.max(1.0, width * 0.5);
  68987. height = Math.max(1.0, height * 0.5);
  68988. }
  68989. };
  68990. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  68991. // load types
  68992. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  68993. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  68994. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  68995. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  68996. return KhronosTextureContainer;
  68997. }());
  68998. Internals.KhronosTextureContainer = KhronosTextureContainer;
  68999. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  69000. })(BABYLON || (BABYLON = {}));
  69001. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  69002. var BABYLON;
  69003. (function (BABYLON) {
  69004. var Debug;
  69005. (function (Debug) {
  69006. /**
  69007. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  69008. */
  69009. var SkeletonViewer = /** @class */ (function () {
  69010. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  69011. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  69012. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  69013. this.skeleton = skeleton;
  69014. this.mesh = mesh;
  69015. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  69016. this.renderingGroupId = renderingGroupId;
  69017. this.color = BABYLON.Color3.White();
  69018. this._debugLines = new Array();
  69019. this._isEnabled = false;
  69020. this._scene = scene;
  69021. this.update();
  69022. this._renderFunction = this.update.bind(this);
  69023. }
  69024. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  69025. get: function () {
  69026. return this._isEnabled;
  69027. },
  69028. set: function (value) {
  69029. if (this._isEnabled === value) {
  69030. return;
  69031. }
  69032. this._isEnabled = value;
  69033. if (value) {
  69034. this._scene.registerBeforeRender(this._renderFunction);
  69035. }
  69036. else {
  69037. this._scene.unregisterBeforeRender(this._renderFunction);
  69038. }
  69039. },
  69040. enumerable: true,
  69041. configurable: true
  69042. });
  69043. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  69044. if (x === void 0) { x = 0; }
  69045. if (y === void 0) { y = 0; }
  69046. if (z === void 0) { z = 0; }
  69047. var tmat = BABYLON.Tmp.Matrix[0];
  69048. var parentBone = bone.getParent();
  69049. tmat.copyFrom(bone.getLocalMatrix());
  69050. if (x !== 0 || y !== 0 || z !== 0) {
  69051. var tmat2 = BABYLON.Tmp.Matrix[1];
  69052. BABYLON.Matrix.IdentityToRef(tmat2);
  69053. tmat2.m[12] = x;
  69054. tmat2.m[13] = y;
  69055. tmat2.m[14] = z;
  69056. tmat2.multiplyToRef(tmat, tmat);
  69057. }
  69058. if (parentBone) {
  69059. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  69060. }
  69061. tmat.multiplyToRef(meshMat, tmat);
  69062. position.x = tmat.m[12];
  69063. position.y = tmat.m[13];
  69064. position.z = tmat.m[14];
  69065. };
  69066. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  69067. var len = bones.length;
  69068. var meshPos = this.mesh.position;
  69069. for (var i = 0; i < len; i++) {
  69070. var bone = bones[i];
  69071. var points = this._debugLines[i];
  69072. if (!points) {
  69073. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69074. this._debugLines[i] = points;
  69075. }
  69076. this._getBonePosition(points[0], bone, meshMat);
  69077. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  69078. points[0].subtractInPlace(meshPos);
  69079. points[1].subtractInPlace(meshPos);
  69080. }
  69081. };
  69082. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  69083. var len = bones.length;
  69084. var boneNum = 0;
  69085. var meshPos = this.mesh.position;
  69086. for (var i = len - 1; i >= 0; i--) {
  69087. var childBone = bones[i];
  69088. var parentBone = childBone.getParent();
  69089. if (!parentBone) {
  69090. continue;
  69091. }
  69092. var points = this._debugLines[boneNum];
  69093. if (!points) {
  69094. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69095. this._debugLines[boneNum] = points;
  69096. }
  69097. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  69098. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  69099. points[0].subtractInPlace(meshPos);
  69100. points[1].subtractInPlace(meshPos);
  69101. boneNum++;
  69102. }
  69103. };
  69104. SkeletonViewer.prototype.update = function () {
  69105. if (this.autoUpdateBonesMatrices) {
  69106. this.skeleton.computeAbsoluteTransforms();
  69107. }
  69108. if (this.skeleton.bones[0].length === undefined) {
  69109. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  69110. }
  69111. else {
  69112. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  69113. }
  69114. if (!this._debugMesh) {
  69115. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  69116. this._debugMesh.renderingGroupId = this.renderingGroupId;
  69117. }
  69118. else {
  69119. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  69120. }
  69121. this._debugMesh.position.copyFrom(this.mesh.position);
  69122. this._debugMesh.color = this.color;
  69123. };
  69124. SkeletonViewer.prototype.dispose = function () {
  69125. if (this._debugMesh) {
  69126. this.isEnabled = false;
  69127. this._debugMesh.dispose();
  69128. this._debugMesh = null;
  69129. }
  69130. };
  69131. return SkeletonViewer;
  69132. }());
  69133. Debug.SkeletonViewer = SkeletonViewer;
  69134. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  69135. })(BABYLON || (BABYLON = {}));
  69136. //# sourceMappingURL=babylon.skeletonViewer.js.map
  69137. var BABYLON;
  69138. (function (BABYLON) {
  69139. var Debug;
  69140. (function (Debug) {
  69141. var AxesViewer = /** @class */ (function () {
  69142. function AxesViewer(scene, scaleLines) {
  69143. if (scaleLines === void 0) { scaleLines = 1; }
  69144. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69145. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69146. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69147. this.scaleLines = 1;
  69148. this.scaleLines = scaleLines;
  69149. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  69150. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  69151. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  69152. this._xmesh.renderingGroupId = 2;
  69153. this._ymesh.renderingGroupId = 2;
  69154. this._zmesh.renderingGroupId = 2;
  69155. this._xmesh.material.checkReadyOnlyOnce = true;
  69156. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  69157. this._ymesh.material.checkReadyOnlyOnce = true;
  69158. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  69159. this._zmesh.material.checkReadyOnlyOnce = true;
  69160. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  69161. this.scene = scene;
  69162. }
  69163. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  69164. var scaleLines = this.scaleLines;
  69165. if (this._xmesh) {
  69166. this._xmesh.position.copyFrom(position);
  69167. }
  69168. if (this._ymesh) {
  69169. this._ymesh.position.copyFrom(position);
  69170. }
  69171. if (this._zmesh) {
  69172. this._zmesh.position.copyFrom(position);
  69173. }
  69174. var point2 = this._xline[1];
  69175. point2.x = xaxis.x * scaleLines;
  69176. point2.y = xaxis.y * scaleLines;
  69177. point2.z = xaxis.z * scaleLines;
  69178. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  69179. point2 = this._yline[1];
  69180. point2.x = yaxis.x * scaleLines;
  69181. point2.y = yaxis.y * scaleLines;
  69182. point2.z = yaxis.z * scaleLines;
  69183. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  69184. point2 = this._zline[1];
  69185. point2.x = zaxis.x * scaleLines;
  69186. point2.y = zaxis.y * scaleLines;
  69187. point2.z = zaxis.z * scaleLines;
  69188. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  69189. };
  69190. AxesViewer.prototype.dispose = function () {
  69191. if (this._xmesh) {
  69192. this._xmesh.dispose();
  69193. }
  69194. if (this._ymesh) {
  69195. this._ymesh.dispose();
  69196. }
  69197. if (this._zmesh) {
  69198. this._zmesh.dispose();
  69199. }
  69200. this._xmesh = null;
  69201. this._ymesh = null;
  69202. this._zmesh = null;
  69203. this.scene = null;
  69204. };
  69205. return AxesViewer;
  69206. }());
  69207. Debug.AxesViewer = AxesViewer;
  69208. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  69209. })(BABYLON || (BABYLON = {}));
  69210. //# sourceMappingURL=babylon.axesViewer.js.map
  69211. var BABYLON;
  69212. (function (BABYLON) {
  69213. var Debug;
  69214. (function (Debug) {
  69215. var BoneAxesViewer = /** @class */ (function (_super) {
  69216. __extends(BoneAxesViewer, _super);
  69217. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  69218. if (scaleLines === void 0) { scaleLines = 1; }
  69219. var _this = _super.call(this, scene, scaleLines) || this;
  69220. _this.pos = BABYLON.Vector3.Zero();
  69221. _this.xaxis = BABYLON.Vector3.Zero();
  69222. _this.yaxis = BABYLON.Vector3.Zero();
  69223. _this.zaxis = BABYLON.Vector3.Zero();
  69224. _this.mesh = mesh;
  69225. _this.bone = bone;
  69226. return _this;
  69227. }
  69228. BoneAxesViewer.prototype.update = function () {
  69229. if (!this.mesh || !this.bone) {
  69230. return;
  69231. }
  69232. var bone = this.bone;
  69233. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  69234. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  69235. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  69236. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  69237. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  69238. };
  69239. BoneAxesViewer.prototype.dispose = function () {
  69240. if (this.mesh) {
  69241. this.mesh = null;
  69242. this.bone = null;
  69243. _super.prototype.dispose.call(this);
  69244. }
  69245. };
  69246. return BoneAxesViewer;
  69247. }(Debug.AxesViewer));
  69248. Debug.BoneAxesViewer = BoneAxesViewer;
  69249. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  69250. })(BABYLON || (BABYLON = {}));
  69251. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  69252. var BABYLON;
  69253. (function (BABYLON) {
  69254. var RayHelper = /** @class */ (function () {
  69255. function RayHelper(ray) {
  69256. this.ray = ray;
  69257. }
  69258. RayHelper.CreateAndShow = function (ray, scene, color) {
  69259. var helper = new RayHelper(ray);
  69260. helper.show(scene, color);
  69261. return helper;
  69262. };
  69263. RayHelper.prototype.show = function (scene, color) {
  69264. if (!this._renderFunction && this.ray) {
  69265. var ray = this.ray;
  69266. this._renderFunction = this._render.bind(this);
  69267. this._scene = scene;
  69268. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  69269. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  69270. if (this._renderFunction) {
  69271. this._scene.registerBeforeRender(this._renderFunction);
  69272. }
  69273. }
  69274. if (color && this._renderLine) {
  69275. this._renderLine.color.copyFrom(color);
  69276. }
  69277. };
  69278. RayHelper.prototype.hide = function () {
  69279. if (this._renderFunction && this._scene) {
  69280. this._scene.unregisterBeforeRender(this._renderFunction);
  69281. this._scene = null;
  69282. this._renderFunction = null;
  69283. if (this._renderLine) {
  69284. this._renderLine.dispose();
  69285. this._renderLine = null;
  69286. }
  69287. this._renderPoints = [];
  69288. }
  69289. };
  69290. RayHelper.prototype._render = function () {
  69291. var ray = this.ray;
  69292. if (!ray) {
  69293. return;
  69294. }
  69295. var point = this._renderPoints[1];
  69296. var len = Math.min(ray.length, 1000000);
  69297. point.copyFrom(ray.direction);
  69298. point.scaleInPlace(len);
  69299. point.addInPlace(ray.origin);
  69300. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  69301. };
  69302. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  69303. this._attachedToMesh = mesh;
  69304. var ray = this.ray;
  69305. if (!ray) {
  69306. return;
  69307. }
  69308. if (!ray.direction) {
  69309. ray.direction = BABYLON.Vector3.Zero();
  69310. }
  69311. if (!ray.origin) {
  69312. ray.origin = BABYLON.Vector3.Zero();
  69313. }
  69314. if (length) {
  69315. ray.length = length;
  69316. }
  69317. if (!meshSpaceOrigin) {
  69318. meshSpaceOrigin = BABYLON.Vector3.Zero();
  69319. }
  69320. if (!meshSpaceDirection) {
  69321. // -1 so that this will work with Mesh.lookAt
  69322. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  69323. }
  69324. if (!this._meshSpaceDirection) {
  69325. this._meshSpaceDirection = meshSpaceDirection.clone();
  69326. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  69327. }
  69328. else {
  69329. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  69330. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  69331. }
  69332. if (!this._updateToMeshFunction) {
  69333. this._updateToMeshFunction = this._updateToMesh.bind(this);
  69334. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  69335. }
  69336. this._updateToMesh();
  69337. };
  69338. RayHelper.prototype.detachFromMesh = function () {
  69339. if (this._attachedToMesh) {
  69340. if (this._updateToMeshFunction) {
  69341. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  69342. }
  69343. this._attachedToMesh = null;
  69344. this._updateToMeshFunction = null;
  69345. }
  69346. };
  69347. RayHelper.prototype._updateToMesh = function () {
  69348. var ray = this.ray;
  69349. if (!this._attachedToMesh || !ray) {
  69350. return;
  69351. }
  69352. if (this._attachedToMesh._isDisposed) {
  69353. this.detachFromMesh();
  69354. return;
  69355. }
  69356. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  69357. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  69358. };
  69359. RayHelper.prototype.dispose = function () {
  69360. this.hide();
  69361. this.detachFromMesh();
  69362. this.ray = null;
  69363. };
  69364. return RayHelper;
  69365. }());
  69366. BABYLON.RayHelper = RayHelper;
  69367. })(BABYLON || (BABYLON = {}));
  69368. //# sourceMappingURL=babylon.rayHelper.js.map
  69369. var BABYLON;
  69370. (function (BABYLON) {
  69371. // load the inspector using require, if not present in the global namespace.
  69372. var DebugLayer = /** @class */ (function () {
  69373. function DebugLayer(scene) {
  69374. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  69375. this._scene = scene;
  69376. // load inspector using require, if it doesn't exist on the global namespace.
  69377. }
  69378. /** Creates the inspector window. */
  69379. DebugLayer.prototype._createInspector = function (config) {
  69380. if (config === void 0) { config = {}; }
  69381. var popup = config.popup || false;
  69382. var initialTab = config.initialTab || 0;
  69383. var parentElement = config.parentElement || null;
  69384. if (!this._inspector) {
  69385. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  69386. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  69387. } // else nothing to do,; instance is already existing
  69388. };
  69389. DebugLayer.prototype.isVisible = function () {
  69390. if (!this._inspector) {
  69391. return false;
  69392. }
  69393. return true;
  69394. };
  69395. DebugLayer.prototype.hide = function () {
  69396. if (this._inspector) {
  69397. try {
  69398. this._inspector.dispose();
  69399. }
  69400. catch (e) {
  69401. // If the inspector has been removed directly from the inspector tool
  69402. }
  69403. this._inspector = null;
  69404. }
  69405. };
  69406. DebugLayer.prototype.show = function (config) {
  69407. if (config === void 0) { config = {}; }
  69408. if (typeof this.BJSINSPECTOR == 'undefined') {
  69409. // Load inspector and add it to the DOM
  69410. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  69411. }
  69412. else {
  69413. // Otherwise creates the inspector
  69414. this._createInspector(config);
  69415. }
  69416. };
  69417. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  69418. return DebugLayer;
  69419. }());
  69420. BABYLON.DebugLayer = DebugLayer;
  69421. })(BABYLON || (BABYLON = {}));
  69422. //# sourceMappingURL=babylon.debugLayer.js.map
  69423. var BABYLON;
  69424. (function (BABYLON) {
  69425. var Debug;
  69426. (function (Debug) {
  69427. var PhysicsViewer = /** @class */ (function () {
  69428. function PhysicsViewer(scene) {
  69429. this._impostors = [];
  69430. this._meshes = [];
  69431. this._numMeshes = 0;
  69432. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  69433. var physicEngine = this._scene.getPhysicsEngine();
  69434. if (physicEngine) {
  69435. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  69436. }
  69437. }
  69438. PhysicsViewer.prototype._updateDebugMeshes = function () {
  69439. var plugin = this._physicsEnginePlugin;
  69440. for (var i = 0; i < this._numMeshes; i++) {
  69441. var impostor = this._impostors[i];
  69442. if (!impostor) {
  69443. continue;
  69444. }
  69445. if (impostor.isDisposed) {
  69446. this.hideImpostor(this._impostors[i--]);
  69447. }
  69448. else {
  69449. var mesh = this._meshes[i];
  69450. if (mesh && plugin) {
  69451. plugin.syncMeshWithImpostor(mesh, impostor);
  69452. }
  69453. }
  69454. }
  69455. };
  69456. PhysicsViewer.prototype.showImpostor = function (impostor) {
  69457. if (!this._scene) {
  69458. return;
  69459. }
  69460. for (var i = 0; i < this._numMeshes; i++) {
  69461. if (this._impostors[i] == impostor) {
  69462. return;
  69463. }
  69464. }
  69465. var debugMesh = this._getDebugMesh(impostor, this._scene);
  69466. if (debugMesh) {
  69467. this._impostors[this._numMeshes] = impostor;
  69468. this._meshes[this._numMeshes] = debugMesh;
  69469. if (this._numMeshes === 0) {
  69470. this._renderFunction = this._updateDebugMeshes.bind(this);
  69471. this._scene.registerBeforeRender(this._renderFunction);
  69472. }
  69473. this._numMeshes++;
  69474. }
  69475. };
  69476. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  69477. if (!impostor || !this._scene) {
  69478. return;
  69479. }
  69480. var removed = false;
  69481. for (var i = 0; i < this._numMeshes; i++) {
  69482. if (this._impostors[i] == impostor) {
  69483. var mesh = this._meshes[i];
  69484. if (!mesh) {
  69485. continue;
  69486. }
  69487. this._scene.removeMesh(mesh);
  69488. mesh.dispose();
  69489. this._numMeshes--;
  69490. if (this._numMeshes > 0) {
  69491. this._meshes[i] = this._meshes[this._numMeshes];
  69492. this._impostors[i] = this._impostors[this._numMeshes];
  69493. this._meshes[this._numMeshes] = null;
  69494. this._impostors[this._numMeshes] = null;
  69495. }
  69496. else {
  69497. this._meshes[0] = null;
  69498. this._impostors[0] = null;
  69499. }
  69500. removed = true;
  69501. break;
  69502. }
  69503. }
  69504. if (removed && this._numMeshes === 0) {
  69505. this._scene.unregisterBeforeRender(this._renderFunction);
  69506. }
  69507. };
  69508. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  69509. if (!this._debugMaterial) {
  69510. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  69511. this._debugMaterial.wireframe = true;
  69512. }
  69513. return this._debugMaterial;
  69514. };
  69515. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  69516. if (!this._debugBoxMesh) {
  69517. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  69518. this._debugBoxMesh.renderingGroupId = 1;
  69519. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  69520. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  69521. scene.removeMesh(this._debugBoxMesh);
  69522. }
  69523. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  69524. };
  69525. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  69526. if (!this._debugSphereMesh) {
  69527. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  69528. this._debugSphereMesh.renderingGroupId = 1;
  69529. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  69530. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  69531. scene.removeMesh(this._debugSphereMesh);
  69532. }
  69533. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  69534. };
  69535. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  69536. var mesh = null;
  69537. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  69538. mesh = this._getDebugBoxMesh(scene);
  69539. impostor.getBoxSizeToRef(mesh.scaling);
  69540. }
  69541. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  69542. mesh = this._getDebugSphereMesh(scene);
  69543. var radius = impostor.getRadius();
  69544. mesh.scaling.x = radius * 2;
  69545. mesh.scaling.y = radius * 2;
  69546. mesh.scaling.z = radius * 2;
  69547. }
  69548. return mesh;
  69549. };
  69550. PhysicsViewer.prototype.dispose = function () {
  69551. for (var i = 0; i < this._numMeshes; i++) {
  69552. this.hideImpostor(this._impostors[i]);
  69553. }
  69554. if (this._debugBoxMesh) {
  69555. this._debugBoxMesh.dispose();
  69556. }
  69557. if (this._debugSphereMesh) {
  69558. this._debugSphereMesh.dispose();
  69559. }
  69560. if (this._debugMaterial) {
  69561. this._debugMaterial.dispose();
  69562. }
  69563. this._impostors.length = 0;
  69564. this._scene = null;
  69565. this._physicsEnginePlugin = null;
  69566. };
  69567. return PhysicsViewer;
  69568. }());
  69569. Debug.PhysicsViewer = PhysicsViewer;
  69570. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  69571. })(BABYLON || (BABYLON = {}));
  69572. //# sourceMappingURL=babylon.physicsViewer.js.map
  69573. var BABYLON;
  69574. (function (BABYLON) {
  69575. var BoundingBoxRenderer = /** @class */ (function () {
  69576. function BoundingBoxRenderer(scene) {
  69577. this.frontColor = new BABYLON.Color3(1, 1, 1);
  69578. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  69579. this.showBackLines = true;
  69580. this.renderList = new BABYLON.SmartArray(32);
  69581. this._vertexBuffers = {};
  69582. this._scene = scene;
  69583. }
  69584. BoundingBoxRenderer.prototype._prepareRessources = function () {
  69585. if (this._colorShader) {
  69586. return;
  69587. }
  69588. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  69589. attributes: [BABYLON.VertexBuffer.PositionKind],
  69590. uniforms: ["world", "viewProjection", "color"]
  69591. });
  69592. var engine = this._scene.getEngine();
  69593. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  69594. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  69595. this._createIndexBuffer();
  69596. };
  69597. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  69598. var engine = this._scene.getEngine();
  69599. 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]);
  69600. };
  69601. BoundingBoxRenderer.prototype._rebuild = function () {
  69602. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69603. if (vb) {
  69604. vb._rebuild();
  69605. }
  69606. this._createIndexBuffer();
  69607. };
  69608. BoundingBoxRenderer.prototype.reset = function () {
  69609. this.renderList.reset();
  69610. };
  69611. BoundingBoxRenderer.prototype.render = function () {
  69612. if (this.renderList.length === 0) {
  69613. return;
  69614. }
  69615. this._prepareRessources();
  69616. if (!this._colorShader.isReady()) {
  69617. return;
  69618. }
  69619. var engine = this._scene.getEngine();
  69620. engine.setDepthWrite(false);
  69621. this._colorShader._preBind();
  69622. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  69623. var boundingBox = this.renderList.data[boundingBoxIndex];
  69624. var min = boundingBox.minimum;
  69625. var max = boundingBox.maximum;
  69626. var diff = max.subtract(min);
  69627. var median = min.add(diff.scale(0.5));
  69628. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  69629. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  69630. .multiply(boundingBox.getWorldMatrix());
  69631. // VBOs
  69632. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  69633. if (this.showBackLines) {
  69634. // Back
  69635. engine.setDepthFunctionToGreaterOrEqual();
  69636. this._scene.resetCachedMaterial();
  69637. this._colorShader.setColor4("color", this.backColor.toColor4());
  69638. this._colorShader.bind(worldMatrix);
  69639. // Draw order
  69640. engine.draw(false, 0, 24);
  69641. }
  69642. // Front
  69643. engine.setDepthFunctionToLess();
  69644. this._scene.resetCachedMaterial();
  69645. this._colorShader.setColor4("color", this.frontColor.toColor4());
  69646. this._colorShader.bind(worldMatrix);
  69647. // Draw order
  69648. engine.draw(false, 0, 24);
  69649. }
  69650. this._colorShader.unbind();
  69651. engine.setDepthFunctionToLessOrEqual();
  69652. engine.setDepthWrite(true);
  69653. };
  69654. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  69655. this._prepareRessources();
  69656. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  69657. return;
  69658. }
  69659. var engine = this._scene.getEngine();
  69660. engine.setDepthWrite(false);
  69661. engine.setColorWrite(false);
  69662. this._colorShader._preBind();
  69663. var boundingBox = mesh._boundingInfo.boundingBox;
  69664. var min = boundingBox.minimum;
  69665. var max = boundingBox.maximum;
  69666. var diff = max.subtract(min);
  69667. var median = min.add(diff.scale(0.5));
  69668. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  69669. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  69670. .multiply(boundingBox.getWorldMatrix());
  69671. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  69672. engine.setDepthFunctionToLess();
  69673. this._scene.resetCachedMaterial();
  69674. this._colorShader.bind(worldMatrix);
  69675. engine.draw(false, 0, 24);
  69676. this._colorShader.unbind();
  69677. engine.setDepthFunctionToLessOrEqual();
  69678. engine.setDepthWrite(true);
  69679. engine.setColorWrite(true);
  69680. };
  69681. BoundingBoxRenderer.prototype.dispose = function () {
  69682. if (!this._colorShader) {
  69683. return;
  69684. }
  69685. this.renderList.dispose();
  69686. this._colorShader.dispose();
  69687. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69688. if (buffer) {
  69689. buffer.dispose();
  69690. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69691. }
  69692. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  69693. };
  69694. return BoundingBoxRenderer;
  69695. }());
  69696. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  69697. })(BABYLON || (BABYLON = {}));
  69698. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  69699. var BABYLON;
  69700. (function (BABYLON) {
  69701. var MorphTarget = /** @class */ (function () {
  69702. function MorphTarget(name, influence) {
  69703. if (influence === void 0) { influence = 0; }
  69704. this.name = name;
  69705. this.animations = new Array();
  69706. this._positions = null;
  69707. this._normals = null;
  69708. this._tangents = null;
  69709. this.onInfluenceChanged = new BABYLON.Observable();
  69710. this.influence = influence;
  69711. }
  69712. Object.defineProperty(MorphTarget.prototype, "influence", {
  69713. get: function () {
  69714. return this._influence;
  69715. },
  69716. set: function (influence) {
  69717. if (this._influence === influence) {
  69718. return;
  69719. }
  69720. var previous = this._influence;
  69721. this._influence = influence;
  69722. if (this.onInfluenceChanged.hasObservers) {
  69723. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  69724. }
  69725. },
  69726. enumerable: true,
  69727. configurable: true
  69728. });
  69729. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  69730. get: function () {
  69731. return !!this._positions;
  69732. },
  69733. enumerable: true,
  69734. configurable: true
  69735. });
  69736. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  69737. get: function () {
  69738. return !!this._normals;
  69739. },
  69740. enumerable: true,
  69741. configurable: true
  69742. });
  69743. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  69744. get: function () {
  69745. return !!this._tangents;
  69746. },
  69747. enumerable: true,
  69748. configurable: true
  69749. });
  69750. MorphTarget.prototype.setPositions = function (data) {
  69751. this._positions = data;
  69752. };
  69753. MorphTarget.prototype.getPositions = function () {
  69754. return this._positions;
  69755. };
  69756. MorphTarget.prototype.setNormals = function (data) {
  69757. this._normals = data;
  69758. };
  69759. MorphTarget.prototype.getNormals = function () {
  69760. return this._normals;
  69761. };
  69762. MorphTarget.prototype.setTangents = function (data) {
  69763. this._tangents = data;
  69764. };
  69765. MorphTarget.prototype.getTangents = function () {
  69766. return this._tangents;
  69767. };
  69768. /**
  69769. * Serializes the current target into a Serialization object.
  69770. * Returns the serialized object.
  69771. */
  69772. MorphTarget.prototype.serialize = function () {
  69773. var serializationObject = {};
  69774. serializationObject.name = this.name;
  69775. serializationObject.influence = this.influence;
  69776. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  69777. if (this.hasNormals) {
  69778. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  69779. }
  69780. if (this.hasTangents) {
  69781. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  69782. }
  69783. // Animations
  69784. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  69785. return serializationObject;
  69786. };
  69787. // Statics
  69788. MorphTarget.Parse = function (serializationObject) {
  69789. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  69790. result.setPositions(serializationObject.positions);
  69791. if (serializationObject.normals) {
  69792. result.setNormals(serializationObject.normals);
  69793. }
  69794. if (serializationObject.tangents) {
  69795. result.setTangents(serializationObject.tangents);
  69796. }
  69797. // Animations
  69798. if (serializationObject.animations) {
  69799. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  69800. var parsedAnimation = serializationObject.animations[animationIndex];
  69801. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  69802. }
  69803. }
  69804. return result;
  69805. };
  69806. MorphTarget.FromMesh = function (mesh, name, influence) {
  69807. if (!name) {
  69808. name = mesh.name;
  69809. }
  69810. var result = new MorphTarget(name, influence);
  69811. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  69812. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  69813. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  69814. }
  69815. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  69816. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  69817. }
  69818. return result;
  69819. };
  69820. return MorphTarget;
  69821. }());
  69822. BABYLON.MorphTarget = MorphTarget;
  69823. })(BABYLON || (BABYLON = {}));
  69824. //# sourceMappingURL=babylon.morphTarget.js.map
  69825. var BABYLON;
  69826. (function (BABYLON) {
  69827. var MorphTargetManager = /** @class */ (function () {
  69828. function MorphTargetManager(scene) {
  69829. if (scene === void 0) { scene = null; }
  69830. this._targets = new Array();
  69831. this._targetObservable = new Array();
  69832. this._activeTargets = new BABYLON.SmartArray(16);
  69833. this._supportsNormals = false;
  69834. this._supportsTangents = false;
  69835. this._vertexCount = 0;
  69836. this._uniqueId = 0;
  69837. this._tempInfluences = new Array();
  69838. if (!scene) {
  69839. scene = BABYLON.Engine.LastCreatedScene;
  69840. }
  69841. this._scene = scene;
  69842. if (this._scene) {
  69843. this._scene.morphTargetManagers.push(this);
  69844. this._uniqueId = this._scene.getUniqueId();
  69845. }
  69846. }
  69847. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  69848. get: function () {
  69849. return this._uniqueId;
  69850. },
  69851. enumerable: true,
  69852. configurable: true
  69853. });
  69854. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  69855. get: function () {
  69856. return this._vertexCount;
  69857. },
  69858. enumerable: true,
  69859. configurable: true
  69860. });
  69861. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  69862. get: function () {
  69863. return this._supportsNormals;
  69864. },
  69865. enumerable: true,
  69866. configurable: true
  69867. });
  69868. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  69869. get: function () {
  69870. return this._supportsTangents;
  69871. },
  69872. enumerable: true,
  69873. configurable: true
  69874. });
  69875. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  69876. get: function () {
  69877. return this._targets.length;
  69878. },
  69879. enumerable: true,
  69880. configurable: true
  69881. });
  69882. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  69883. get: function () {
  69884. return this._activeTargets.length;
  69885. },
  69886. enumerable: true,
  69887. configurable: true
  69888. });
  69889. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  69890. get: function () {
  69891. return this._influences;
  69892. },
  69893. enumerable: true,
  69894. configurable: true
  69895. });
  69896. MorphTargetManager.prototype.getActiveTarget = function (index) {
  69897. return this._activeTargets.data[index];
  69898. };
  69899. MorphTargetManager.prototype.getTarget = function (index) {
  69900. return this._targets[index];
  69901. };
  69902. MorphTargetManager.prototype.addTarget = function (target) {
  69903. var _this = this;
  69904. this._targets.push(target);
  69905. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  69906. _this._syncActiveTargets(needUpdate);
  69907. }));
  69908. this._syncActiveTargets(true);
  69909. };
  69910. MorphTargetManager.prototype.removeTarget = function (target) {
  69911. var index = this._targets.indexOf(target);
  69912. if (index >= 0) {
  69913. this._targets.splice(index, 1);
  69914. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  69915. this._syncActiveTargets(true);
  69916. }
  69917. };
  69918. /**
  69919. * Serializes the current manager into a Serialization object.
  69920. * Returns the serialized object.
  69921. */
  69922. MorphTargetManager.prototype.serialize = function () {
  69923. var serializationObject = {};
  69924. serializationObject.id = this.uniqueId;
  69925. serializationObject.targets = [];
  69926. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  69927. var target = _a[_i];
  69928. serializationObject.targets.push(target.serialize());
  69929. }
  69930. return serializationObject;
  69931. };
  69932. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  69933. var influenceCount = 0;
  69934. this._activeTargets.reset();
  69935. this._supportsNormals = true;
  69936. this._supportsTangents = true;
  69937. this._vertexCount = 0;
  69938. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  69939. var target = _a[_i];
  69940. if (target.influence > 0) {
  69941. this._activeTargets.push(target);
  69942. this._tempInfluences[influenceCount++] = target.influence;
  69943. this._supportsNormals = this._supportsNormals && target.hasNormals;
  69944. this._supportsTangents = this._supportsTangents && target.hasTangents;
  69945. var positions = target.getPositions();
  69946. if (!positions) {
  69947. BABYLON.Tools.Error("Invalid target. Target must positions.");
  69948. return;
  69949. }
  69950. var vertexCount = positions.length / 3;
  69951. if (this._vertexCount === 0) {
  69952. this._vertexCount = vertexCount;
  69953. }
  69954. else if (this._vertexCount !== vertexCount) {
  69955. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  69956. return;
  69957. }
  69958. }
  69959. }
  69960. if (!this._influences || this._influences.length !== influenceCount) {
  69961. this._influences = new Float32Array(influenceCount);
  69962. }
  69963. for (var index = 0; index < influenceCount; index++) {
  69964. this._influences[index] = this._tempInfluences[index];
  69965. }
  69966. if (needUpdate && this._scene) {
  69967. // Flag meshes as dirty to resync with the active targets
  69968. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  69969. var mesh = _c[_b];
  69970. if (mesh.morphTargetManager === this) {
  69971. mesh._syncGeometryWithMorphTargetManager();
  69972. }
  69973. }
  69974. }
  69975. };
  69976. // Statics
  69977. MorphTargetManager.Parse = function (serializationObject, scene) {
  69978. var result = new MorphTargetManager(scene);
  69979. result._uniqueId = serializationObject.id;
  69980. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  69981. var targetData = _a[_i];
  69982. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  69983. }
  69984. return result;
  69985. };
  69986. return MorphTargetManager;
  69987. }());
  69988. BABYLON.MorphTargetManager = MorphTargetManager;
  69989. })(BABYLON || (BABYLON = {}));
  69990. //# sourceMappingURL=babylon.morphTargetManager.js.map
  69991. var BABYLON;
  69992. (function (BABYLON) {
  69993. var Octree = /** @class */ (function () {
  69994. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  69995. if (maxDepth === void 0) { maxDepth = 2; }
  69996. this.maxDepth = maxDepth;
  69997. this.dynamicContent = new Array();
  69998. this._maxBlockCapacity = maxBlockCapacity || 64;
  69999. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  70000. this._creationFunc = creationFunc;
  70001. }
  70002. // Methods
  70003. Octree.prototype.update = function (worldMin, worldMax, entries) {
  70004. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  70005. };
  70006. Octree.prototype.addMesh = function (entry) {
  70007. for (var index = 0; index < this.blocks.length; index++) {
  70008. var block = this.blocks[index];
  70009. block.addEntry(entry);
  70010. }
  70011. };
  70012. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  70013. this._selectionContent.reset();
  70014. for (var index = 0; index < this.blocks.length; index++) {
  70015. var block = this.blocks[index];
  70016. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  70017. }
  70018. if (allowDuplicate) {
  70019. this._selectionContent.concat(this.dynamicContent);
  70020. }
  70021. else {
  70022. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  70023. }
  70024. return this._selectionContent;
  70025. };
  70026. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  70027. this._selectionContent.reset();
  70028. for (var index = 0; index < this.blocks.length; index++) {
  70029. var block = this.blocks[index];
  70030. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  70031. }
  70032. if (allowDuplicate) {
  70033. this._selectionContent.concat(this.dynamicContent);
  70034. }
  70035. else {
  70036. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  70037. }
  70038. return this._selectionContent;
  70039. };
  70040. Octree.prototype.intersectsRay = function (ray) {
  70041. this._selectionContent.reset();
  70042. for (var index = 0; index < this.blocks.length; index++) {
  70043. var block = this.blocks[index];
  70044. block.intersectsRay(ray, this._selectionContent);
  70045. }
  70046. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  70047. return this._selectionContent;
  70048. };
  70049. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  70050. target.blocks = new Array();
  70051. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  70052. // Segmenting space
  70053. for (var x = 0; x < 2; x++) {
  70054. for (var y = 0; y < 2; y++) {
  70055. for (var z = 0; z < 2; z++) {
  70056. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  70057. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  70058. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  70059. block.addEntries(entries);
  70060. target.blocks.push(block);
  70061. }
  70062. }
  70063. }
  70064. };
  70065. Octree.CreationFuncForMeshes = function (entry, block) {
  70066. var boundingInfo = entry.getBoundingInfo();
  70067. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  70068. block.entries.push(entry);
  70069. }
  70070. };
  70071. Octree.CreationFuncForSubMeshes = function (entry, block) {
  70072. var boundingInfo = entry.getBoundingInfo();
  70073. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  70074. block.entries.push(entry);
  70075. }
  70076. };
  70077. return Octree;
  70078. }());
  70079. BABYLON.Octree = Octree;
  70080. })(BABYLON || (BABYLON = {}));
  70081. //# sourceMappingURL=babylon.octree.js.map
  70082. var BABYLON;
  70083. (function (BABYLON) {
  70084. var OctreeBlock = /** @class */ (function () {
  70085. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  70086. this.entries = new Array();
  70087. this._boundingVectors = new Array();
  70088. this._capacity = capacity;
  70089. this._depth = depth;
  70090. this._maxDepth = maxDepth;
  70091. this._creationFunc = creationFunc;
  70092. this._minPoint = minPoint;
  70093. this._maxPoint = maxPoint;
  70094. this._boundingVectors.push(minPoint.clone());
  70095. this._boundingVectors.push(maxPoint.clone());
  70096. this._boundingVectors.push(minPoint.clone());
  70097. this._boundingVectors[2].x = maxPoint.x;
  70098. this._boundingVectors.push(minPoint.clone());
  70099. this._boundingVectors[3].y = maxPoint.y;
  70100. this._boundingVectors.push(minPoint.clone());
  70101. this._boundingVectors[4].z = maxPoint.z;
  70102. this._boundingVectors.push(maxPoint.clone());
  70103. this._boundingVectors[5].z = minPoint.z;
  70104. this._boundingVectors.push(maxPoint.clone());
  70105. this._boundingVectors[6].x = minPoint.x;
  70106. this._boundingVectors.push(maxPoint.clone());
  70107. this._boundingVectors[7].y = minPoint.y;
  70108. }
  70109. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  70110. // Property
  70111. get: function () {
  70112. return this._capacity;
  70113. },
  70114. enumerable: true,
  70115. configurable: true
  70116. });
  70117. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  70118. get: function () {
  70119. return this._minPoint;
  70120. },
  70121. enumerable: true,
  70122. configurable: true
  70123. });
  70124. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  70125. get: function () {
  70126. return this._maxPoint;
  70127. },
  70128. enumerable: true,
  70129. configurable: true
  70130. });
  70131. // Methods
  70132. OctreeBlock.prototype.addEntry = function (entry) {
  70133. if (this.blocks) {
  70134. for (var index = 0; index < this.blocks.length; index++) {
  70135. var block = this.blocks[index];
  70136. block.addEntry(entry);
  70137. }
  70138. return;
  70139. }
  70140. this._creationFunc(entry, this);
  70141. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  70142. this.createInnerBlocks();
  70143. }
  70144. };
  70145. OctreeBlock.prototype.addEntries = function (entries) {
  70146. for (var index = 0; index < entries.length; index++) {
  70147. var mesh = entries[index];
  70148. this.addEntry(mesh);
  70149. }
  70150. };
  70151. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  70152. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  70153. if (this.blocks) {
  70154. for (var index = 0; index < this.blocks.length; index++) {
  70155. var block = this.blocks[index];
  70156. block.select(frustumPlanes, selection, allowDuplicate);
  70157. }
  70158. return;
  70159. }
  70160. if (allowDuplicate) {
  70161. selection.concat(this.entries);
  70162. }
  70163. else {
  70164. selection.concatWithNoDuplicate(this.entries);
  70165. }
  70166. }
  70167. };
  70168. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  70169. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  70170. if (this.blocks) {
  70171. for (var index = 0; index < this.blocks.length; index++) {
  70172. var block = this.blocks[index];
  70173. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  70174. }
  70175. return;
  70176. }
  70177. if (allowDuplicate) {
  70178. selection.concat(this.entries);
  70179. }
  70180. else {
  70181. selection.concatWithNoDuplicate(this.entries);
  70182. }
  70183. }
  70184. };
  70185. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  70186. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  70187. if (this.blocks) {
  70188. for (var index = 0; index < this.blocks.length; index++) {
  70189. var block = this.blocks[index];
  70190. block.intersectsRay(ray, selection);
  70191. }
  70192. return;
  70193. }
  70194. selection.concatWithNoDuplicate(this.entries);
  70195. }
  70196. };
  70197. OctreeBlock.prototype.createInnerBlocks = function () {
  70198. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  70199. };
  70200. return OctreeBlock;
  70201. }());
  70202. BABYLON.OctreeBlock = OctreeBlock;
  70203. })(BABYLON || (BABYLON = {}));
  70204. //# sourceMappingURL=babylon.octreeBlock.js.map
  70205. var BABYLON;
  70206. (function (BABYLON) {
  70207. var SIMDVector3 = /** @class */ (function () {
  70208. function SIMDVector3() {
  70209. }
  70210. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  70211. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  70212. };
  70213. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  70214. var m = transformation.m;
  70215. var m0 = SIMD.Float32x4.load(m, 0);
  70216. var m1 = SIMD.Float32x4.load(m, 4);
  70217. var m2 = SIMD.Float32x4.load(m, 8);
  70218. var m3 = SIMD.Float32x4.load(m, 12);
  70219. 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));
  70220. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  70221. result.x = SIMD.Float32x4.extractLane(r, 0);
  70222. result.y = SIMD.Float32x4.extractLane(r, 1);
  70223. result.z = SIMD.Float32x4.extractLane(r, 2);
  70224. };
  70225. return SIMDVector3;
  70226. }());
  70227. var SIMDMatrix = /** @class */ (function () {
  70228. function SIMDMatrix() {
  70229. }
  70230. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  70231. var tm = this.m;
  70232. var om = other.m;
  70233. var m0 = SIMD.Float32x4.load(om, 0);
  70234. var m1 = SIMD.Float32x4.load(om, 4);
  70235. var m2 = SIMD.Float32x4.load(om, 8);
  70236. var m3 = SIMD.Float32x4.load(om, 12);
  70237. for (var i = 0; i < 16; i += 4) {
  70238. 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)))));
  70239. }
  70240. return this;
  70241. };
  70242. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  70243. var src = this.m;
  70244. var dest = other.m;
  70245. // Load the 4 rows
  70246. var src0 = SIMD.Float32x4.load(src, 0);
  70247. var src1 = SIMD.Float32x4.load(src, 4);
  70248. var src2 = SIMD.Float32x4.load(src, 8);
  70249. var src3 = SIMD.Float32x4.load(src, 12);
  70250. // Transpose the source matrix. Sort of. Not a true transpose operation
  70251. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  70252. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  70253. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  70254. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  70255. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  70256. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  70257. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  70258. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  70259. // This is a true transposition, but it will lead to an incorrect result
  70260. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  70261. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  70262. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  70263. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  70264. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  70265. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  70266. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  70267. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  70268. // ----
  70269. tmp1 = SIMD.Float32x4.mul(row2, row3);
  70270. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  70271. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  70272. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  70273. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  70274. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  70275. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  70276. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  70277. // ----
  70278. tmp1 = SIMD.Float32x4.mul(row1, row2);
  70279. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  70280. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  70281. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  70282. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  70283. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  70284. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  70285. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  70286. // ----
  70287. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  70288. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  70289. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  70290. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  70291. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  70292. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  70293. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  70294. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  70295. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  70296. // ----
  70297. tmp1 = SIMD.Float32x4.mul(row0, row1);
  70298. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  70299. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  70300. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  70301. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  70302. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  70303. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  70304. // ----
  70305. tmp1 = SIMD.Float32x4.mul(row0, row3);
  70306. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  70307. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  70308. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  70309. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  70310. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  70311. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  70312. // ----
  70313. tmp1 = SIMD.Float32x4.mul(row0, row2);
  70314. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  70315. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  70316. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  70317. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  70318. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  70319. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  70320. // Compute determinant
  70321. var det = SIMD.Float32x4.mul(row0, minor0);
  70322. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  70323. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  70324. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  70325. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  70326. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  70327. // These shuffles aren't necessary if the faulty transposition is done
  70328. // up at the top of this function.
  70329. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  70330. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  70331. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  70332. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  70333. // Compute final values by multiplying with 1/det
  70334. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  70335. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  70336. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  70337. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  70338. return this;
  70339. };
  70340. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  70341. var out = result.m;
  70342. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  70343. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  70344. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  70345. // cc.kmVec3Subtract(f, pCenter, pEye);
  70346. var f = SIMD.Float32x4.sub(center, eye);
  70347. // cc.kmVec3Normalize(f, f);
  70348. var tmp = SIMD.Float32x4.mul(f, f);
  70349. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  70350. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  70351. // cc.kmVec3Assign(up, pUp);
  70352. // cc.kmVec3Normalize(up, up);
  70353. tmp = SIMD.Float32x4.mul(up, up);
  70354. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  70355. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  70356. // cc.kmVec3Cross(s, f, up);
  70357. 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)));
  70358. // cc.kmVec3Normalize(s, s);
  70359. tmp = SIMD.Float32x4.mul(s, s);
  70360. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  70361. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  70362. // cc.kmVec3Cross(u, s, f);
  70363. 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)));
  70364. // cc.kmVec3Normalize(s, s);
  70365. tmp = SIMD.Float32x4.mul(s, s);
  70366. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  70367. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  70368. var zero = SIMD.Float32x4.splat(0.0);
  70369. s = SIMD.Float32x4.neg(s);
  70370. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  70371. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  70372. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  70373. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  70374. 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);
  70375. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  70376. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  70377. 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)))));
  70378. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  70379. 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)))));
  70380. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  70381. 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)))));
  70382. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  70383. 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)))));
  70384. };
  70385. return SIMDMatrix;
  70386. }());
  70387. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  70388. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  70389. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  70390. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  70391. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  70392. var SIMDHelper = /** @class */ (function () {
  70393. function SIMDHelper() {
  70394. }
  70395. Object.defineProperty(SIMDHelper, "IsEnabled", {
  70396. get: function () {
  70397. return SIMDHelper._isEnabled;
  70398. },
  70399. enumerable: true,
  70400. configurable: true
  70401. });
  70402. SIMDHelper.DisableSIMD = function () {
  70403. // Replace functions
  70404. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  70405. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  70406. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  70407. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  70408. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  70409. SIMDHelper._isEnabled = false;
  70410. };
  70411. SIMDHelper.EnableSIMD = function () {
  70412. if (self.SIMD === undefined) {
  70413. return;
  70414. }
  70415. // check if polyfills needed
  70416. if (!self.Math.fround) {
  70417. self.Math.fround = (function (array) { return function (x) {
  70418. return array[0] = x, array[0];
  70419. }; })(new Float32Array(1));
  70420. }
  70421. if (!self.Math.imul) {
  70422. self.Math.imul = function (a, b) {
  70423. var ah = (a >>> 16) & 0xffff;
  70424. var al = a & 0xffff;
  70425. var bh = (b >>> 16) & 0xffff;
  70426. var bl = b & 0xffff;
  70427. // the shift by 0 fixes the sign on the high part
  70428. // the final |0 converts the unsigned value into a signed value
  70429. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  70430. };
  70431. }
  70432. // Replace functions
  70433. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  70434. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  70435. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  70436. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  70437. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  70438. SIMDHelper._isEnabled = true;
  70439. };
  70440. SIMDHelper._isEnabled = false;
  70441. return SIMDHelper;
  70442. }());
  70443. BABYLON.SIMDHelper = SIMDHelper;
  70444. })(BABYLON || (BABYLON = {}));
  70445. //# sourceMappingURL=babylon.math.SIMD.js.map
  70446. var BABYLON;
  70447. (function (BABYLON) {
  70448. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  70449. __extends(VRDistortionCorrectionPostProcess, _super);
  70450. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  70451. var _this = _super.call(this, name, "vrDistortionCorrection", [
  70452. 'LensCenter',
  70453. 'Scale',
  70454. 'ScaleIn',
  70455. 'HmdWarpParam'
  70456. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  70457. _this._isRightEye = isRightEye;
  70458. _this._distortionFactors = vrMetrics.distortionK;
  70459. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  70460. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  70461. _this.adaptScaleToCurrentViewport = true;
  70462. _this.onSizeChangedObservable.add(function () {
  70463. _this.aspectRatio = _this.width * .5 / _this.height;
  70464. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  70465. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  70466. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  70467. });
  70468. _this.onApplyObservable.add(function (effect) {
  70469. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  70470. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  70471. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  70472. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  70473. });
  70474. return _this;
  70475. }
  70476. return VRDistortionCorrectionPostProcess;
  70477. }(BABYLON.PostProcess));
  70478. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  70479. })(BABYLON || (BABYLON = {}));
  70480. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  70481. var BABYLON;
  70482. (function (BABYLON) {
  70483. var AnaglyphPostProcess = /** @class */ (function (_super) {
  70484. __extends(AnaglyphPostProcess, _super);
  70485. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  70486. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  70487. _this._passedProcess = rigCameras[0]._rigPostProcess;
  70488. _this.onApplyObservable.add(function (effect) {
  70489. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  70490. });
  70491. return _this;
  70492. }
  70493. return AnaglyphPostProcess;
  70494. }(BABYLON.PostProcess));
  70495. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  70496. })(BABYLON || (BABYLON = {}));
  70497. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  70498. var BABYLON;
  70499. (function (BABYLON) {
  70500. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  70501. __extends(StereoscopicInterlacePostProcess, _super);
  70502. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  70503. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  70504. _this._passedProcess = rigCameras[0]._rigPostProcess;
  70505. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  70506. _this.onSizeChangedObservable.add(function () {
  70507. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  70508. });
  70509. _this.onApplyObservable.add(function (effect) {
  70510. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  70511. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  70512. });
  70513. return _this;
  70514. }
  70515. return StereoscopicInterlacePostProcess;
  70516. }(BABYLON.PostProcess));
  70517. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  70518. })(BABYLON || (BABYLON = {}));
  70519. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  70520. var BABYLON;
  70521. (function (BABYLON) {
  70522. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  70523. function FreeCameraDeviceOrientationInput() {
  70524. var _this = this;
  70525. this._screenOrientationAngle = 0;
  70526. this._screenQuaternion = new BABYLON.Quaternion();
  70527. this._alpha = 0;
  70528. this._beta = 0;
  70529. this._gamma = 0;
  70530. this._orientationChanged = function () {
  70531. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  70532. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  70533. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  70534. };
  70535. this._deviceOrientation = function (evt) {
  70536. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  70537. _this._beta = evt.beta !== null ? evt.beta : 0;
  70538. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  70539. };
  70540. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  70541. this._orientationChanged();
  70542. }
  70543. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  70544. get: function () {
  70545. return this._camera;
  70546. },
  70547. set: function (camera) {
  70548. this._camera = camera;
  70549. if (this._camera != null && !this._camera.rotationQuaternion) {
  70550. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  70551. }
  70552. },
  70553. enumerable: true,
  70554. configurable: true
  70555. });
  70556. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  70557. window.addEventListener("orientationchange", this._orientationChanged);
  70558. window.addEventListener("deviceorientation", this._deviceOrientation);
  70559. //In certain cases, the attach control is called AFTER orientation was changed,
  70560. //So this is needed.
  70561. this._orientationChanged();
  70562. };
  70563. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  70564. window.removeEventListener("orientationchange", this._orientationChanged);
  70565. window.removeEventListener("deviceorientation", this._deviceOrientation);
  70566. };
  70567. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  70568. //if no device orientation provided, don't update the rotation.
  70569. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  70570. if (!this._alpha)
  70571. return;
  70572. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  70573. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  70574. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  70575. //Mirror on XY Plane
  70576. this._camera.rotationQuaternion.z *= -1;
  70577. this._camera.rotationQuaternion.w *= -1;
  70578. };
  70579. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  70580. return "FreeCameraDeviceOrientationInput";
  70581. };
  70582. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  70583. return "deviceOrientation";
  70584. };
  70585. return FreeCameraDeviceOrientationInput;
  70586. }());
  70587. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  70588. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  70589. })(BABYLON || (BABYLON = {}));
  70590. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  70591. var BABYLON;
  70592. (function (BABYLON) {
  70593. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  70594. function ArcRotateCameraVRDeviceOrientationInput() {
  70595. this.alphaCorrection = 1;
  70596. this.betaCorrection = 1;
  70597. this.gammaCorrection = 1;
  70598. this._alpha = 0;
  70599. this._gamma = 0;
  70600. this._dirty = false;
  70601. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  70602. }
  70603. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  70604. this.camera.attachControl(element, noPreventDefault);
  70605. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  70606. };
  70607. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  70608. if (evt.alpha !== null) {
  70609. this._alpha = +evt.alpha | 0;
  70610. }
  70611. if (evt.gamma !== null) {
  70612. this._gamma = +evt.gamma | 0;
  70613. }
  70614. this._dirty = true;
  70615. };
  70616. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  70617. if (this._dirty) {
  70618. this._dirty = false;
  70619. if (this._gamma < 0) {
  70620. this._gamma = 180 + this._gamma;
  70621. }
  70622. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  70623. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  70624. }
  70625. };
  70626. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  70627. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  70628. };
  70629. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  70630. return "ArcRotateCameraVRDeviceOrientationInput";
  70631. };
  70632. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  70633. return "VRDeviceOrientation";
  70634. };
  70635. return ArcRotateCameraVRDeviceOrientationInput;
  70636. }());
  70637. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  70638. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  70639. })(BABYLON || (BABYLON = {}));
  70640. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  70641. var BABYLON;
  70642. (function (BABYLON) {
  70643. var VRCameraMetrics = /** @class */ (function () {
  70644. function VRCameraMetrics() {
  70645. this.compensateDistortion = true;
  70646. }
  70647. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  70648. get: function () {
  70649. return this.hResolution / (2 * this.vResolution);
  70650. },
  70651. enumerable: true,
  70652. configurable: true
  70653. });
  70654. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  70655. get: function () {
  70656. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  70657. },
  70658. enumerable: true,
  70659. configurable: true
  70660. });
  70661. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  70662. get: function () {
  70663. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  70664. var h = (4 * meters) / this.hScreenSize;
  70665. return BABYLON.Matrix.Translation(h, 0, 0);
  70666. },
  70667. enumerable: true,
  70668. configurable: true
  70669. });
  70670. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  70671. get: function () {
  70672. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  70673. var h = (4 * meters) / this.hScreenSize;
  70674. return BABYLON.Matrix.Translation(-h, 0, 0);
  70675. },
  70676. enumerable: true,
  70677. configurable: true
  70678. });
  70679. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  70680. get: function () {
  70681. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  70682. },
  70683. enumerable: true,
  70684. configurable: true
  70685. });
  70686. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  70687. get: function () {
  70688. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  70689. },
  70690. enumerable: true,
  70691. configurable: true
  70692. });
  70693. VRCameraMetrics.GetDefault = function () {
  70694. var result = new VRCameraMetrics();
  70695. result.hResolution = 1280;
  70696. result.vResolution = 800;
  70697. result.hScreenSize = 0.149759993;
  70698. result.vScreenSize = 0.0935999975;
  70699. result.vScreenCenter = 0.0467999987;
  70700. result.eyeToScreenDistance = 0.0410000011;
  70701. result.lensSeparationDistance = 0.0635000020;
  70702. result.interpupillaryDistance = 0.0640000030;
  70703. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  70704. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  70705. result.postProcessScaleFactor = 1.714605507808412;
  70706. result.lensCenterOffset = 0.151976421;
  70707. return result;
  70708. };
  70709. return VRCameraMetrics;
  70710. }());
  70711. BABYLON.VRCameraMetrics = VRCameraMetrics;
  70712. })(BABYLON || (BABYLON = {}));
  70713. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  70714. var BABYLON;
  70715. (function (BABYLON) {
  70716. var WebVRFreeCamera = /** @class */ (function (_super) {
  70717. __extends(WebVRFreeCamera, _super);
  70718. function WebVRFreeCamera(name, position, scene, webVROptions) {
  70719. if (webVROptions === void 0) { webVROptions = {}; }
  70720. var _this = _super.call(this, name, position, scene) || this;
  70721. _this.webVROptions = webVROptions;
  70722. _this._vrDevice = null;
  70723. _this.rawPose = null;
  70724. _this._specsVersion = "1.1";
  70725. _this._attached = false;
  70726. _this._descendants = [];
  70727. _this.devicePosition = BABYLON.Vector3.Zero();
  70728. _this.deviceScaleFactor = 1;
  70729. _this.controllers = [];
  70730. _this.onControllersAttachedObservable = new BABYLON.Observable();
  70731. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  70732. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  70733. if (webVROptions.defaultHeight) {
  70734. _this.position.y = webVROptions.defaultHeight;
  70735. }
  70736. _this.minZ = 0.1;
  70737. //legacy support - the compensation boolean was removed.
  70738. if (arguments.length === 5) {
  70739. _this.webVROptions = arguments[4];
  70740. }
  70741. // default webVR options
  70742. if (_this.webVROptions.trackPosition == undefined) {
  70743. _this.webVROptions.trackPosition = true;
  70744. }
  70745. if (_this.webVROptions.controllerMeshes == undefined) {
  70746. _this.webVROptions.controllerMeshes = true;
  70747. }
  70748. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  70749. _this.webVROptions.defaultLightingOnControllers = true;
  70750. }
  70751. _this.rotationQuaternion = new BABYLON.Quaternion();
  70752. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  70753. if (_this.webVROptions && _this.webVROptions.positionScale) {
  70754. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  70755. }
  70756. //enable VR
  70757. var engine = _this.getEngine();
  70758. _this._onVREnabled = function (success) { if (success) {
  70759. _this.initControllers();
  70760. } };
  70761. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  70762. engine.initWebVR().add(function (event) {
  70763. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  70764. return;
  70765. }
  70766. _this._vrDevice = event.vrDisplay;
  70767. //reset the rig parameters.
  70768. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  70769. if (_this._attached) {
  70770. _this.getEngine().enableVR();
  70771. }
  70772. });
  70773. if (typeof (VRFrameData) !== "undefined")
  70774. _this._frameData = new VRFrameData();
  70775. /**
  70776. * The idea behind the following lines:
  70777. * objects that have the camera as parent should actually have the rig cameras as a parent.
  70778. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  70779. * the second will not show it correctly.
  70780. *
  70781. * To solve this - each object that has the camera as parent will be added to a protected array.
  70782. * When the rig camera renders, it will take this array and set all of those to be its children.
  70783. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  70784. * Amazing!
  70785. */
  70786. scene.onBeforeCameraRenderObservable.add(function (camera) {
  70787. if (camera.parent === _this && _this.rigParenting) {
  70788. _this._descendants = _this.getDescendants(true, function (n) {
  70789. // don't take the cameras or the controllers!
  70790. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  70791. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  70792. return !isController && !isRigCamera;
  70793. });
  70794. _this._descendants.forEach(function (node) {
  70795. node.parent = camera;
  70796. });
  70797. }
  70798. });
  70799. scene.onAfterCameraRenderObservable.add(function (camera) {
  70800. if (camera.parent === _this && _this.rigParenting) {
  70801. _this._descendants.forEach(function (node) {
  70802. node.parent = _this;
  70803. });
  70804. }
  70805. });
  70806. return _this;
  70807. }
  70808. WebVRFreeCamera.prototype.dispose = function () {
  70809. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  70810. _super.prototype.dispose.call(this);
  70811. };
  70812. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  70813. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  70814. var gp = _a[_i];
  70815. if (gp.hand === name) {
  70816. return gp;
  70817. }
  70818. }
  70819. return null;
  70820. };
  70821. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  70822. get: function () {
  70823. if (!this._leftController) {
  70824. this._leftController = this.getControllerByName("left");
  70825. }
  70826. return this._leftController;
  70827. },
  70828. enumerable: true,
  70829. configurable: true
  70830. });
  70831. ;
  70832. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  70833. get: function () {
  70834. if (!this._rightController) {
  70835. this._rightController = this.getControllerByName("right");
  70836. }
  70837. return this._rightController;
  70838. },
  70839. enumerable: true,
  70840. configurable: true
  70841. });
  70842. ;
  70843. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  70844. if (length === void 0) { length = 100; }
  70845. if (this.leftCamera) {
  70846. // Use left eye to avoid computation to compute center on every call
  70847. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  70848. }
  70849. else {
  70850. return _super.prototype.getForwardRay.call(this, length);
  70851. }
  70852. };
  70853. WebVRFreeCamera.prototype._checkInputs = function () {
  70854. if (this._vrDevice && this._vrDevice.isPresenting) {
  70855. this._vrDevice.getFrameData(this._frameData);
  70856. this.updateFromDevice(this._frameData.pose);
  70857. }
  70858. _super.prototype._checkInputs.call(this);
  70859. };
  70860. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  70861. if (poseData && poseData.orientation) {
  70862. this.rawPose = poseData;
  70863. this.deviceRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  70864. if (this.getScene().useRightHandedSystem) {
  70865. this.deviceRotationQuaternion.z *= -1;
  70866. this.deviceRotationQuaternion.w *= -1;
  70867. }
  70868. if (this.webVROptions.trackPosition && this.rawPose.position) {
  70869. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  70870. if (this.getScene().useRightHandedSystem) {
  70871. this.devicePosition.z *= -1;
  70872. }
  70873. }
  70874. }
  70875. };
  70876. /**
  70877. * WebVR's attach control will start broadcasting frames to the device.
  70878. * Note that in certain browsers (chrome for example) this function must be called
  70879. * within a user-interaction callback. Example:
  70880. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  70881. *
  70882. * @param {HTMLElement} element
  70883. * @param {boolean} [noPreventDefault]
  70884. *
  70885. * @memberOf WebVRFreeCamera
  70886. */
  70887. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  70888. _super.prototype.attachControl.call(this, element, noPreventDefault);
  70889. this._attached = true;
  70890. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  70891. if (this._vrDevice) {
  70892. this.getEngine().enableVR();
  70893. }
  70894. };
  70895. WebVRFreeCamera.prototype.detachControl = function (element) {
  70896. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70897. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70898. _super.prototype.detachControl.call(this, element);
  70899. this._attached = false;
  70900. this.getEngine().disableVR();
  70901. };
  70902. WebVRFreeCamera.prototype.getClassName = function () {
  70903. return "WebVRFreeCamera";
  70904. };
  70905. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  70906. //uses the vrDisplay's "resetPose()".
  70907. //pitch and roll won't be affected.
  70908. this._vrDevice.resetPose();
  70909. };
  70910. WebVRFreeCamera.prototype._updateRigCameras = function () {
  70911. var camLeft = this._rigCameras[0];
  70912. var camRight = this._rigCameras[1];
  70913. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  70914. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  70915. camLeft.position.copyFrom(this.devicePosition);
  70916. camRight.position.copyFrom(this.devicePosition);
  70917. };
  70918. /**
  70919. * This function is called by the two RIG cameras.
  70920. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  70921. */
  70922. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  70923. var _this = this;
  70924. //WebVR 1.1
  70925. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  70926. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  70927. if (!this.getScene().useRightHandedSystem) {
  70928. [2, 6, 8, 9, 14].forEach(function (num) {
  70929. _this._webvrViewMatrix.m[num] *= -1;
  70930. });
  70931. }
  70932. // update the camera rotation matrix
  70933. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  70934. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  70935. // Computing target and final matrix
  70936. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  70937. var parentCamera = this._cameraRigParams["parentCamera"];
  70938. // should the view matrix be updated with scale and position offset?
  70939. if (parentCamera.deviceScaleFactor !== 1) {
  70940. this._webvrViewMatrix.invert();
  70941. // scale the position, if set
  70942. if (parentCamera.deviceScaleFactor) {
  70943. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  70944. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  70945. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  70946. }
  70947. this._webvrViewMatrix.invert();
  70948. }
  70949. return this._webvrViewMatrix;
  70950. };
  70951. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  70952. var _this = this;
  70953. var parentCamera = this.parent;
  70954. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  70955. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  70956. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  70957. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  70958. //babylon compatible matrix
  70959. if (!this.getScene().useRightHandedSystem) {
  70960. [8, 9, 10, 11].forEach(function (num) {
  70961. _this._projectionMatrix.m[num] *= -1;
  70962. });
  70963. }
  70964. return this._projectionMatrix;
  70965. };
  70966. WebVRFreeCamera.prototype.initControllers = function () {
  70967. var _this = this;
  70968. this.controllers = [];
  70969. var manager = this.getScene().gamepadManager;
  70970. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70971. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  70972. var webVrController = gamepad;
  70973. if (webVrController.defaultModel) {
  70974. webVrController.defaultModel.setEnabled(false);
  70975. }
  70976. if (webVrController.hand === "right") {
  70977. _this._rightController = null;
  70978. }
  70979. if (webVrController.hand === "left") {
  70980. _this._rightController = null;
  70981. }
  70982. var controllerIndex = _this.controllers.indexOf(webVrController);
  70983. if (controllerIndex !== -1) {
  70984. _this.controllers.splice(controllerIndex, 1);
  70985. }
  70986. }
  70987. });
  70988. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70989. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  70990. var webVrController_1 = gamepad;
  70991. if (_this.webVROptions.controllerMeshes) {
  70992. if (webVrController_1.defaultModel) {
  70993. webVrController_1.defaultModel.setEnabled(true);
  70994. }
  70995. else {
  70996. // Load the meshes
  70997. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  70998. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  70999. if (_this.webVROptions.defaultLightingOnControllers) {
  71000. if (!_this._lightOnControllers) {
  71001. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  71002. }
  71003. var activateLightOnSubMeshes_1 = function (mesh, light) {
  71004. var children = mesh.getChildren();
  71005. if (children.length !== 0) {
  71006. children.forEach(function (mesh) {
  71007. light.includedOnlyMeshes.push(mesh);
  71008. activateLightOnSubMeshes_1(mesh, light);
  71009. });
  71010. }
  71011. };
  71012. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  71013. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  71014. }
  71015. });
  71016. }
  71017. }
  71018. webVrController_1.attachToPoseControlledCamera(_this);
  71019. // since this is async - sanity check. Is the controller already stored?
  71020. if (_this.controllers.indexOf(webVrController_1) === -1) {
  71021. //add to the controllers array
  71022. _this.controllers.push(webVrController_1);
  71023. //did we find enough controllers? Great! let the developer know.
  71024. if (_this.controllers.length >= 2) {
  71025. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  71026. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  71027. // So we're overriding setting left & right manually to be sure
  71028. var firstViveWandDetected = false;
  71029. for (var i = 0; i < _this.controllers.length; i++) {
  71030. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  71031. if (!firstViveWandDetected) {
  71032. firstViveWandDetected = true;
  71033. _this.controllers[i].hand = "left";
  71034. }
  71035. else {
  71036. _this.controllers[i].hand = "right";
  71037. }
  71038. }
  71039. }
  71040. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  71041. }
  71042. }
  71043. }
  71044. });
  71045. };
  71046. return WebVRFreeCamera;
  71047. }(BABYLON.FreeCamera));
  71048. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  71049. })(BABYLON || (BABYLON = {}));
  71050. //# sourceMappingURL=babylon.webVRCamera.js.map
  71051. var BABYLON;
  71052. (function (BABYLON) {
  71053. // We're mainly based on the logic defined into the FreeCamera code
  71054. var DeviceOrientationCamera = /** @class */ (function (_super) {
  71055. __extends(DeviceOrientationCamera, _super);
  71056. function DeviceOrientationCamera(name, position, scene) {
  71057. var _this = _super.call(this, name, position, scene) || this;
  71058. _this._quaternionCache = new BABYLON.Quaternion();
  71059. _this.inputs.addDeviceOrientation();
  71060. return _this;
  71061. }
  71062. DeviceOrientationCamera.prototype.getClassName = function () {
  71063. return "DeviceOrientationCamera";
  71064. };
  71065. DeviceOrientationCamera.prototype._checkInputs = function () {
  71066. _super.prototype._checkInputs.call(this);
  71067. this._quaternionCache.copyFrom(this.rotationQuaternion);
  71068. if (this._initialQuaternion) {
  71069. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  71070. }
  71071. };
  71072. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  71073. var _this = this;
  71074. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  71075. //can only work if this camera has a rotation quaternion already.
  71076. if (!this.rotationQuaternion)
  71077. return;
  71078. if (!this._initialQuaternion) {
  71079. this._initialQuaternion = new BABYLON.Quaternion();
  71080. }
  71081. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  71082. ['x', 'y', 'z'].forEach(function (axisName) {
  71083. if (!axis[axisName]) {
  71084. _this._initialQuaternion[axisName] = 0;
  71085. }
  71086. else {
  71087. _this._initialQuaternion[axisName] *= -1;
  71088. }
  71089. });
  71090. this._initialQuaternion.normalize();
  71091. //force rotation update
  71092. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  71093. };
  71094. return DeviceOrientationCamera;
  71095. }(BABYLON.FreeCamera));
  71096. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  71097. })(BABYLON || (BABYLON = {}));
  71098. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  71099. var BABYLON;
  71100. (function (BABYLON) {
  71101. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  71102. __extends(VRDeviceOrientationFreeCamera, _super);
  71103. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  71104. if (compensateDistortion === void 0) { compensateDistortion = true; }
  71105. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  71106. var _this = _super.call(this, name, position, scene) || this;
  71107. vrCameraMetrics.compensateDistortion = compensateDistortion;
  71108. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  71109. return _this;
  71110. }
  71111. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  71112. return "VRDeviceOrientationFreeCamera";
  71113. };
  71114. return VRDeviceOrientationFreeCamera;
  71115. }(BABYLON.DeviceOrientationCamera));
  71116. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  71117. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  71118. __extends(VRDeviceOrientationGamepadCamera, _super);
  71119. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  71120. if (compensateDistortion === void 0) { compensateDistortion = true; }
  71121. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  71122. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  71123. _this.inputs.addGamepad();
  71124. return _this;
  71125. }
  71126. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  71127. return "VRDeviceOrientationGamepadCamera";
  71128. };
  71129. return VRDeviceOrientationGamepadCamera;
  71130. }(VRDeviceOrientationFreeCamera));
  71131. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  71132. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  71133. __extends(VRDeviceOrientationArcRotateCamera, _super);
  71134. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  71135. if (compensateDistortion === void 0) { compensateDistortion = true; }
  71136. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  71137. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  71138. vrCameraMetrics.compensateDistortion = compensateDistortion;
  71139. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  71140. _this.inputs.addVRDeviceOrientation();
  71141. return _this;
  71142. }
  71143. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  71144. return "VRDeviceOrientationArcRotateCamera";
  71145. };
  71146. return VRDeviceOrientationArcRotateCamera;
  71147. }(BABYLON.ArcRotateCamera));
  71148. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  71149. })(BABYLON || (BABYLON = {}));
  71150. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  71151. var BABYLON;
  71152. (function (BABYLON) {
  71153. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  71154. __extends(AnaglyphFreeCamera, _super);
  71155. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  71156. var _this = _super.call(this, name, position, scene) || this;
  71157. _this.interaxialDistance = interaxialDistance;
  71158. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  71159. return _this;
  71160. }
  71161. AnaglyphFreeCamera.prototype.getClassName = function () {
  71162. return "AnaglyphFreeCamera";
  71163. };
  71164. return AnaglyphFreeCamera;
  71165. }(BABYLON.FreeCamera));
  71166. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  71167. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  71168. __extends(AnaglyphArcRotateCamera, _super);
  71169. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  71170. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  71171. _this.interaxialDistance = interaxialDistance;
  71172. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  71173. return _this;
  71174. }
  71175. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  71176. return "AnaglyphArcRotateCamera";
  71177. };
  71178. return AnaglyphArcRotateCamera;
  71179. }(BABYLON.ArcRotateCamera));
  71180. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  71181. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  71182. __extends(AnaglyphGamepadCamera, _super);
  71183. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  71184. var _this = _super.call(this, name, position, scene) || this;
  71185. _this.interaxialDistance = interaxialDistance;
  71186. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  71187. return _this;
  71188. }
  71189. AnaglyphGamepadCamera.prototype.getClassName = function () {
  71190. return "AnaglyphGamepadCamera";
  71191. };
  71192. return AnaglyphGamepadCamera;
  71193. }(BABYLON.GamepadCamera));
  71194. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  71195. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  71196. __extends(AnaglyphUniversalCamera, _super);
  71197. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  71198. var _this = _super.call(this, name, position, scene) || this;
  71199. _this.interaxialDistance = interaxialDistance;
  71200. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  71201. return _this;
  71202. }
  71203. AnaglyphUniversalCamera.prototype.getClassName = function () {
  71204. return "AnaglyphUniversalCamera";
  71205. };
  71206. return AnaglyphUniversalCamera;
  71207. }(BABYLON.UniversalCamera));
  71208. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  71209. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  71210. __extends(StereoscopicFreeCamera, _super);
  71211. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  71212. var _this = _super.call(this, name, position, scene) || this;
  71213. _this.interaxialDistance = interaxialDistance;
  71214. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  71215. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  71216. return _this;
  71217. }
  71218. StereoscopicFreeCamera.prototype.getClassName = function () {
  71219. return "StereoscopicFreeCamera";
  71220. };
  71221. return StereoscopicFreeCamera;
  71222. }(BABYLON.FreeCamera));
  71223. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  71224. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  71225. __extends(StereoscopicArcRotateCamera, _super);
  71226. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  71227. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  71228. _this.interaxialDistance = interaxialDistance;
  71229. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  71230. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  71231. return _this;
  71232. }
  71233. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  71234. return "StereoscopicArcRotateCamera";
  71235. };
  71236. return StereoscopicArcRotateCamera;
  71237. }(BABYLON.ArcRotateCamera));
  71238. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  71239. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  71240. __extends(StereoscopicGamepadCamera, _super);
  71241. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  71242. var _this = _super.call(this, name, position, scene) || this;
  71243. _this.interaxialDistance = interaxialDistance;
  71244. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  71245. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  71246. return _this;
  71247. }
  71248. StereoscopicGamepadCamera.prototype.getClassName = function () {
  71249. return "StereoscopicGamepadCamera";
  71250. };
  71251. return StereoscopicGamepadCamera;
  71252. }(BABYLON.GamepadCamera));
  71253. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  71254. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  71255. __extends(StereoscopicUniversalCamera, _super);
  71256. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  71257. var _this = _super.call(this, name, position, scene) || this;
  71258. _this.interaxialDistance = interaxialDistance;
  71259. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  71260. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  71261. return _this;
  71262. }
  71263. StereoscopicUniversalCamera.prototype.getClassName = function () {
  71264. return "StereoscopicUniversalCamera";
  71265. };
  71266. return StereoscopicUniversalCamera;
  71267. }(BABYLON.UniversalCamera));
  71268. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  71269. })(BABYLON || (BABYLON = {}));
  71270. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  71271. var BABYLON;
  71272. (function (BABYLON) {
  71273. var VRExperienceHelper = /** @class */ (function () {
  71274. function VRExperienceHelper(scene, webVROptions) {
  71275. if (webVROptions === void 0) { webVROptions = {}; }
  71276. var _this = this;
  71277. this.webVROptions = webVROptions;
  71278. // Can the system support WebVR, even if a headset isn't plugged in?
  71279. this._webVRsupported = false;
  71280. // If WebVR is supported, is a headset plugged in and are we ready to present?
  71281. this._webVRready = false;
  71282. // Are we waiting for the requestPresent callback to complete?
  71283. this._webVRrequesting = false;
  71284. // Are we presenting to the headset right now?
  71285. this._webVRpresenting = false;
  71286. // Are we presenting in the fullscreen fallback?
  71287. this._fullscreenVRpresenting = false;
  71288. this.onEnteringVR = new BABYLON.Observable();
  71289. this.onExitingVR = new BABYLON.Observable();
  71290. this.onControllerMeshLoaded = new BABYLON.Observable();
  71291. this._useCustomVRButton = false;
  71292. this._teleportationRequested = false;
  71293. this._teleportationEnabledOnLeftController = false;
  71294. this._teleportationEnabledOnRightController = false;
  71295. this._interactionsEnabledOnLeftController = false;
  71296. this._interactionsEnabledOnRightController = false;
  71297. this._leftControllerReady = false;
  71298. this._rightControllerReady = false;
  71299. this._floorMeshesCollection = [];
  71300. this._teleportationAllowed = false;
  71301. this._rotationAllowed = true;
  71302. this._teleportationRequestInitiated = false;
  71303. this._rotationRightAsked = false;
  71304. this._rotationLeftAsked = false;
  71305. this._teleportationFillColor = "#444444";
  71306. this._teleportationBorderColor = "#FFFFFF";
  71307. this._rotationAngle = 0;
  71308. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  71309. this._padSensibilityUp = 0.65;
  71310. this._padSensibilityDown = 0.35;
  71311. this.onNewMeshSelected = new BABYLON.Observable();
  71312. this._pointerDownOnMeshAsked = false;
  71313. this._isActionableMesh = false;
  71314. this._teleportationEnabled = false;
  71315. this._interactionsEnabled = false;
  71316. this._interactionsRequested = false;
  71317. this._displayGaze = true;
  71318. this._displayLaserPointer = true;
  71319. this._workingVector = BABYLON.Vector3.Zero();
  71320. this._scene = scene;
  71321. this._canvas = scene.getEngine().getRenderingCanvas();
  71322. this._defaultHeight = webVROptions.defaultHeight || 1.7;
  71323. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  71324. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  71325. }
  71326. if (webVROptions.createDeviceOrientationCamera === undefined) {
  71327. webVROptions.createDeviceOrientationCamera = true;
  71328. }
  71329. if (!this._scene.activeCamera || webVROptions.createDeviceOrientationCamera) {
  71330. if (!this._scene.activeCamera || isNaN(this._scene.activeCamera.position.x)) {
  71331. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  71332. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  71333. }
  71334. else {
  71335. this._position = this._scene.activeCamera.position.clone();
  71336. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  71337. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  71338. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  71339. // Set rotation from previous camera
  71340. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  71341. var targetCamera = this._scene.activeCamera;
  71342. if (targetCamera.rotationQuaternion) {
  71343. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  71344. }
  71345. else {
  71346. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  71347. }
  71348. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  71349. }
  71350. }
  71351. this._scene.activeCamera = this._deviceOrientationCamera;
  71352. if (this._canvas) {
  71353. this._scene.activeCamera.attachControl(this._canvas);
  71354. }
  71355. }
  71356. else {
  71357. this._existingCamera = this._scene.activeCamera;
  71358. this._position = this._scene.activeCamera.position.clone();
  71359. }
  71360. if (webVROptions) {
  71361. if (webVROptions.useCustomVRButton) {
  71362. this._useCustomVRButton = true;
  71363. if (webVROptions.customVRButton) {
  71364. this._btnVR = webVROptions.customVRButton;
  71365. }
  71366. }
  71367. if (webVROptions.rayLength) {
  71368. this._rayLength = webVROptions.rayLength;
  71369. }
  71370. }
  71371. if (!this._useCustomVRButton) {
  71372. this._btnVR = document.createElement("BUTTON");
  71373. this._btnVR.className = "babylonVRicon";
  71374. this._btnVR.id = "babylonVRiconbtn";
  71375. this._btnVR.title = "Click to switch to VR";
  71376. 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) }";
  71377. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  71378. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  71379. // css += ".babylonVRicon.vrdisplaysupported { }";
  71380. // css += ".babylonVRicon.vrdisplayready { }";
  71381. // css += ".babylonVRicon.vrdisplayrequesting { }";
  71382. var style = document.createElement('style');
  71383. style.appendChild(document.createTextNode(css));
  71384. document.getElementsByTagName('head')[0].appendChild(style);
  71385. }
  71386. if (this._canvas) {
  71387. if (!this._useCustomVRButton) {
  71388. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  71389. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  71390. }
  71391. if (this._btnVR) {
  71392. this._btnVR.addEventListener("click", function () {
  71393. _this.enterVR();
  71394. });
  71395. }
  71396. window.addEventListener("resize", function () {
  71397. if (_this._canvas && !_this._useCustomVRButton) {
  71398. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  71399. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  71400. }
  71401. if (_this._fullscreenVRpresenting && _this._webVRready) {
  71402. _this.exitVR();
  71403. }
  71404. });
  71405. }
  71406. document.addEventListener("fullscreenchange", function () { _this._onFullscreenChange(); }, false);
  71407. document.addEventListener("mozfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  71408. document.addEventListener("webkitfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  71409. document.addEventListener("msfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  71410. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  71411. if (!_this._useCustomVRButton && !_this._btnVRDisplayed && e.vrDisplay) {
  71412. document.body.appendChild(_this._btnVR);
  71413. _this._btnVRDisplayed = true;
  71414. }
  71415. });
  71416. if (!this._useCustomVRButton && !this._btnVRDisplayed && webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  71417. document.body.appendChild(this._btnVR);
  71418. this._btnVRDisplayed = true;
  71419. }
  71420. // Exiting VR mode using 'ESC' key on desktop
  71421. this._onKeyDown = function (event) {
  71422. if (event.keyCode === 27 && _this.isInVRMode()) {
  71423. _this.exitVR();
  71424. }
  71425. };
  71426. document.addEventListener("keydown", this._onKeyDown);
  71427. // Exiting VR mode double tapping the touch screen
  71428. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  71429. if (_this.isInVRMode()) {
  71430. _this.exitVR();
  71431. if (_this._fullscreenVRpresenting) {
  71432. _this._scene.getEngine().switchFullscreen(true);
  71433. }
  71434. }
  71435. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  71436. // Listen for WebVR display changes
  71437. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  71438. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  71439. this._onVRRequestPresentStart = function () {
  71440. _this._webVRrequesting = true;
  71441. _this.updateButtonVisibility();
  71442. };
  71443. this._onVRRequestPresentComplete = function (success) {
  71444. _this._webVRrequesting = false;
  71445. _this.updateButtonVisibility();
  71446. };
  71447. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  71448. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  71449. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  71450. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  71451. // Create the cameras
  71452. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  71453. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  71454. }
  71455. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  71456. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  71457. this._scene.gamepadManager.onGamepadConnectedObservable.add(function (pad) { return _this._onNewGamepadConnected(pad); });
  71458. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(function (pad) { return _this._onNewGamepadDisconnected(pad); });
  71459. this.updateButtonVisibility();
  71460. //create easing functions
  71461. this._circleEase = new BABYLON.CircleEase();
  71462. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  71463. }
  71464. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  71465. get: function () {
  71466. return this._displayGaze;
  71467. },
  71468. set: function (value) {
  71469. this._displayGaze = value;
  71470. if (!value) {
  71471. this._gazeTracker.isVisible = false;
  71472. }
  71473. },
  71474. enumerable: true,
  71475. configurable: true
  71476. });
  71477. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  71478. get: function () {
  71479. return this._displayLaserPointer;
  71480. },
  71481. set: function (value) {
  71482. this._displayLaserPointer = value;
  71483. if (!value) {
  71484. if (this._rightLaserPointer) {
  71485. this._rightLaserPointer.isVisible = false;
  71486. }
  71487. if (this._leftLaserPointer) {
  71488. this._leftLaserPointer.isVisible = false;
  71489. }
  71490. }
  71491. },
  71492. enumerable: true,
  71493. configurable: true
  71494. });
  71495. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  71496. get: function () {
  71497. return this._deviceOrientationCamera;
  71498. },
  71499. enumerable: true,
  71500. configurable: true
  71501. });
  71502. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  71503. // Based on the current WebVR support, returns the current VR camera used
  71504. get: function () {
  71505. if (this._webVRready) {
  71506. return this._webVRCamera;
  71507. }
  71508. else {
  71509. return this._scene.activeCamera;
  71510. }
  71511. },
  71512. enumerable: true,
  71513. configurable: true
  71514. });
  71515. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  71516. get: function () {
  71517. return this._webVRCamera;
  71518. },
  71519. enumerable: true,
  71520. configurable: true
  71521. });
  71522. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  71523. get: function () {
  71524. return this._vrDeviceOrientationCamera;
  71525. },
  71526. enumerable: true,
  71527. configurable: true
  71528. });
  71529. // Raised when one of the controller has loaded successfully its associated default mesh
  71530. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  71531. if (webVRController.hand === "left") {
  71532. this._leftControllerReady = true;
  71533. if (this._interactionsRequested && !this._interactionsEnabledOnLeftController) {
  71534. this._enableInteractionOnController(webVRController);
  71535. }
  71536. if (this._teleportationRequested && !this._teleportationEnabledOnLeftController) {
  71537. this._enableTeleportationOnController(webVRController);
  71538. }
  71539. }
  71540. if (webVRController.hand === "right") {
  71541. this._rightControllerReady = true;
  71542. if (this._interactionsRequested && !this._interactionsEnabledOnRightController) {
  71543. this._enableInteractionOnController(webVRController);
  71544. }
  71545. if (this._teleportationRequested && !this._teleportationEnabledOnRightController) {
  71546. this._enableTeleportationOnController(webVRController);
  71547. }
  71548. }
  71549. try {
  71550. this.onControllerMeshLoaded.notifyObservers(webVRController);
  71551. }
  71552. catch (err) {
  71553. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  71554. }
  71555. };
  71556. VRExperienceHelper.prototype._onFullscreenChange = function () {
  71557. if (document.fullscreen !== undefined) {
  71558. this._fullscreenVRpresenting = document.fullscreen;
  71559. }
  71560. else if (document.mozFullScreen !== undefined) {
  71561. this._fullscreenVRpresenting = document.mozFullScreen;
  71562. }
  71563. else if (document.webkitIsFullScreen !== undefined) {
  71564. this._fullscreenVRpresenting = document.webkitIsFullScreen;
  71565. }
  71566. else if (document.msIsFullScreen !== undefined) {
  71567. this._fullscreenVRpresenting = document.msIsFullScreen;
  71568. }
  71569. if (!this._fullscreenVRpresenting && this._canvas) {
  71570. this.exitVR();
  71571. if (!this._useCustomVRButton) {
  71572. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  71573. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  71574. }
  71575. }
  71576. };
  71577. VRExperienceHelper.prototype.isInVRMode = function () {
  71578. return this._webVRpresenting || this._fullscreenVRpresenting;
  71579. };
  71580. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  71581. var vrDisplay = this._scene.getEngine().getVRDevice();
  71582. if (vrDisplay) {
  71583. var wasPresenting = this._webVRpresenting;
  71584. // A VR display is connected
  71585. this._webVRpresenting = vrDisplay.isPresenting;
  71586. if (wasPresenting && !this._webVRpresenting)
  71587. this.exitVR();
  71588. }
  71589. else {
  71590. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  71591. }
  71592. this.updateButtonVisibility();
  71593. };
  71594. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  71595. this._webVRsupported = eventArgs.vrSupported;
  71596. this._webVRready = !!eventArgs.vrDisplay;
  71597. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  71598. this.updateButtonVisibility();
  71599. };
  71600. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  71601. if (!this._btnVR) {
  71602. return;
  71603. }
  71604. this._btnVR.className = "babylonVRicon";
  71605. if (this.isInVRMode()) {
  71606. this._btnVR.className += " vrdisplaypresenting";
  71607. }
  71608. else {
  71609. if (this._webVRready)
  71610. this._btnVR.className += " vrdisplayready";
  71611. if (this._webVRsupported)
  71612. this._btnVR.className += " vrdisplaysupported";
  71613. if (this._webVRrequesting)
  71614. this._btnVR.className += " vrdisplayrequesting";
  71615. }
  71616. };
  71617. /**
  71618. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  71619. * Otherwise, will use the fullscreen API.
  71620. */
  71621. VRExperienceHelper.prototype.enterVR = function () {
  71622. if (this._scene.activeCamera) {
  71623. this._position = this._scene.activeCamera.position.clone();
  71624. }
  71625. if (this.onEnteringVR) {
  71626. try {
  71627. this.onEnteringVR.notifyObservers(this);
  71628. }
  71629. catch (err) {
  71630. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  71631. }
  71632. }
  71633. if (this._webVRrequesting)
  71634. return;
  71635. // If WebVR is supported and a headset is connected
  71636. if (this._webVRready) {
  71637. if (!this._webVRpresenting) {
  71638. this._webVRCamera.position = this._position;
  71639. this._scene.activeCamera = this._webVRCamera;
  71640. }
  71641. }
  71642. else if (this._vrDeviceOrientationCamera) {
  71643. this._vrDeviceOrientationCamera.position = this._position;
  71644. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  71645. this._scene.getEngine().switchFullscreen(true);
  71646. this.updateButtonVisibility();
  71647. }
  71648. if (this._scene.activeCamera && this._canvas) {
  71649. this._scene.activeCamera.attachControl(this._canvas);
  71650. }
  71651. };
  71652. /**
  71653. * Attempt to exit VR, or fullscreen.
  71654. */
  71655. VRExperienceHelper.prototype.exitVR = function () {
  71656. if (this.onExitingVR) {
  71657. try {
  71658. this.onExitingVR.notifyObservers(this);
  71659. }
  71660. catch (err) {
  71661. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  71662. }
  71663. }
  71664. if (this._webVRpresenting) {
  71665. this._scene.getEngine().disableVR();
  71666. }
  71667. if (this._scene.activeCamera) {
  71668. this._position = this._scene.activeCamera.position.clone();
  71669. }
  71670. if (this._deviceOrientationCamera) {
  71671. this._deviceOrientationCamera.position = this._position;
  71672. this._scene.activeCamera = this._deviceOrientationCamera;
  71673. if (this._canvas) {
  71674. this._scene.activeCamera.attachControl(this._canvas);
  71675. }
  71676. }
  71677. else if (this._existingCamera) {
  71678. this._existingCamera.position = this._position;
  71679. this._scene.activeCamera = this._existingCamera;
  71680. }
  71681. this.updateButtonVisibility();
  71682. };
  71683. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  71684. get: function () {
  71685. return this._position;
  71686. },
  71687. set: function (value) {
  71688. this._position = value;
  71689. if (this._scene.activeCamera) {
  71690. this._scene.activeCamera.position = value;
  71691. }
  71692. },
  71693. enumerable: true,
  71694. configurable: true
  71695. });
  71696. VRExperienceHelper.prototype.enableInteractions = function () {
  71697. var _this = this;
  71698. if (!this._interactionsEnabled) {
  71699. this._interactionsRequested = true;
  71700. if (this._leftControllerReady && this._webVRCamera.leftController) {
  71701. this._enableInteractionOnController(this._webVRCamera.leftController);
  71702. }
  71703. if (this._rightControllerReady && this._webVRCamera.rightController) {
  71704. this._enableInteractionOnController(this._webVRCamera.rightController);
  71705. }
  71706. this._createGazeTracker();
  71707. this.raySelectionPredicate = function (mesh) {
  71708. return true;
  71709. };
  71710. this.meshSelectionPredicate = function (mesh) {
  71711. return true;
  71712. };
  71713. this._raySelectionPredicate = function (mesh) {
  71714. if (_this._isTeleportationFloor(mesh) || (mesh.isVisible && mesh.name.indexOf("gazeTracker") === -1
  71715. && mesh.name.indexOf("teleportationCircle") === -1
  71716. && mesh.name.indexOf("torusTeleportation") === -1
  71717. && mesh.name.indexOf("laserPointer") === -1)) {
  71718. return _this.raySelectionPredicate(mesh);
  71719. }
  71720. return false;
  71721. };
  71722. this._scene.registerBeforeRender(function () {
  71723. _this._castRayAndSelectObject();
  71724. });
  71725. this._interactionsEnabled = true;
  71726. }
  71727. };
  71728. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  71729. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  71730. if (this._floorMeshesCollection[i].id === mesh.id) {
  71731. return true;
  71732. }
  71733. }
  71734. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  71735. return true;
  71736. }
  71737. return false;
  71738. };
  71739. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  71740. if (!this._floorMeshesCollection) {
  71741. return;
  71742. }
  71743. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  71744. return;
  71745. }
  71746. this._floorMeshesCollection.push(floorMesh);
  71747. };
  71748. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  71749. if (!this._floorMeshesCollection) {
  71750. return;
  71751. }
  71752. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  71753. if (meshIndex !== -1) {
  71754. this._floorMeshesCollection.splice(meshIndex, 1);
  71755. }
  71756. };
  71757. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  71758. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  71759. if (!this._teleportationEnabled) {
  71760. this._teleportationRequested = true;
  71761. this.enableInteractions();
  71762. if (vrTeleportationOptions) {
  71763. if (vrTeleportationOptions.floorMeshName) {
  71764. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  71765. }
  71766. if (vrTeleportationOptions.floorMeshes) {
  71767. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  71768. }
  71769. }
  71770. if (this._leftControllerReady && this._webVRCamera.leftController) {
  71771. this._enableTeleportationOnController(this._webVRCamera.leftController);
  71772. }
  71773. if (this._rightControllerReady && this._webVRCamera.rightController) {
  71774. this._enableTeleportationOnController(this._webVRCamera.rightController);
  71775. }
  71776. // Creates an image processing post process for the vignette not relying
  71777. // on the main scene configuration for image processing to reduce setup and spaces
  71778. // (gamma/linear) conflicts.
  71779. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  71780. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  71781. imageProcessingConfiguration.vignetteEnabled = true;
  71782. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  71783. this._webVRCamera.detachPostProcess(this._postProcessMove);
  71784. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  71785. this._teleportationEnabled = true;
  71786. this._createTeleportationCircles();
  71787. }
  71788. };
  71789. VRExperienceHelper.prototype._onNewGamepadConnected = function (gamepad) {
  71790. var _this = this;
  71791. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  71792. if (gamepad.leftStick) {
  71793. gamepad.onleftstickchanged(function (stickValues) {
  71794. if (_this._teleportationEnabled) {
  71795. // Listening to classic/xbox gamepad only if no VR controller is active
  71796. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  71797. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  71798. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  71799. if (!_this._teleportationRequestInitiated) {
  71800. if (stickValues.y < -_this._padSensibilityUp) {
  71801. _this._teleportationRequestInitiated = true;
  71802. }
  71803. }
  71804. else {
  71805. if (stickValues.y > -_this._padSensibilityDown) {
  71806. if (_this._teleportationAllowed) {
  71807. _this._teleportCamera();
  71808. }
  71809. _this._teleportationRequestInitiated = false;
  71810. }
  71811. }
  71812. }
  71813. }
  71814. });
  71815. }
  71816. if (gamepad.rightStick) {
  71817. gamepad.onrightstickchanged(function (stickValues) {
  71818. if (_this._teleportationEnabled) {
  71819. if (!_this._rotationLeftAsked) {
  71820. if (stickValues.x < -_this._padSensibilityUp) {
  71821. _this._rotationLeftAsked = true;
  71822. if (_this._rotationAllowed) {
  71823. _this._rotateCamera(false);
  71824. }
  71825. }
  71826. }
  71827. else {
  71828. if (stickValues.x > -_this._padSensibilityDown) {
  71829. _this._rotationLeftAsked = false;
  71830. }
  71831. }
  71832. if (!_this._rotationRightAsked) {
  71833. if (stickValues.x > _this._padSensibilityUp) {
  71834. _this._rotationRightAsked = true;
  71835. if (_this._rotationAllowed) {
  71836. _this._rotateCamera(true);
  71837. }
  71838. }
  71839. }
  71840. else {
  71841. if (stickValues.x < _this._padSensibilityDown) {
  71842. _this._rotationRightAsked = false;
  71843. }
  71844. }
  71845. }
  71846. });
  71847. }
  71848. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  71849. gamepad.onbuttondown(function (buttonPressed) {
  71850. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  71851. _this._pointerDownOnMeshAsked = true;
  71852. if (_this._currentMeshSelected && _this._currentHit) {
  71853. _this._scene.simulatePointerDown(_this._currentHit);
  71854. }
  71855. }
  71856. });
  71857. gamepad.onbuttonup(function (buttonPressed) {
  71858. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  71859. if (_this._currentMeshSelected && _this._currentHit) {
  71860. _this._scene.simulatePointerUp(_this._currentHit);
  71861. }
  71862. _this._pointerDownOnMeshAsked = false;
  71863. }
  71864. });
  71865. }
  71866. }
  71867. };
  71868. VRExperienceHelper.prototype._onNewGamepadDisconnected = function (gamepad) {
  71869. if (gamepad instanceof BABYLON.WebVRController) {
  71870. if (gamepad.hand === "left") {
  71871. this._interactionsEnabledOnLeftController = false;
  71872. this._teleportationEnabledOnLeftController = false;
  71873. this._leftControllerReady = false;
  71874. if (this._leftLaserPointer) {
  71875. this._leftLaserPointer.dispose();
  71876. }
  71877. }
  71878. if (gamepad.hand === "right") {
  71879. this._interactionsEnabledOnRightController = false;
  71880. this._teleportationEnabledOnRightController = false;
  71881. this._rightControllerReady = false;
  71882. if (this._rightLaserPointer) {
  71883. this._rightLaserPointer.dispose();
  71884. }
  71885. }
  71886. }
  71887. };
  71888. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  71889. var _this = this;
  71890. var controllerMesh = webVRController.mesh;
  71891. if (controllerMesh) {
  71892. var childMeshes = controllerMesh.getChildMeshes();
  71893. for (var i = 0; i < childMeshes.length; i++) {
  71894. if (childMeshes[i].name === "POINTING_POSE") {
  71895. controllerMesh = childMeshes[i];
  71896. break;
  71897. }
  71898. }
  71899. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  71900. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  71901. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  71902. laserPointerMaterial.alpha = 0.6;
  71903. laserPointer.material = laserPointerMaterial;
  71904. laserPointer.rotation.x = Math.PI / 2;
  71905. laserPointer.parent = controllerMesh;
  71906. laserPointer.position.z = -0.5;
  71907. laserPointer.position.y = 0;
  71908. laserPointer.isVisible = false;
  71909. if (webVRController.hand === "left") {
  71910. this._leftLaserPointer = laserPointer;
  71911. this._interactionsEnabledOnLeftController = true;
  71912. }
  71913. else {
  71914. this._rightLaserPointer = laserPointer;
  71915. this._interactionsEnabledOnRightController = true;
  71916. }
  71917. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  71918. // Enabling / disabling laserPointer
  71919. if (_this._displayLaserPointer && stateObject.value === 1) {
  71920. laserPointer.isVisible = !laserPointer.isVisible;
  71921. // Laser pointer can only be active on left or right, not both at the same time
  71922. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  71923. _this._rightLaserPointer.isVisible = false;
  71924. }
  71925. else if (_this._leftLaserPointer) {
  71926. _this._leftLaserPointer.isVisible = false;
  71927. }
  71928. }
  71929. });
  71930. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  71931. if (!_this._pointerDownOnMeshAsked) {
  71932. if (stateObject.value > _this._padSensibilityUp) {
  71933. _this._pointerDownOnMeshAsked = true;
  71934. if (_this._currentMeshSelected && _this._currentHit) {
  71935. _this._scene.simulatePointerDown(_this._currentHit);
  71936. }
  71937. }
  71938. }
  71939. else if (stateObject.value < _this._padSensibilityDown) {
  71940. if (_this._currentMeshSelected && _this._currentHit) {
  71941. _this._scene.simulatePointerUp(_this._currentHit);
  71942. }
  71943. _this._pointerDownOnMeshAsked = false;
  71944. }
  71945. });
  71946. }
  71947. };
  71948. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  71949. var _this = this;
  71950. var controllerMesh = webVRController.mesh;
  71951. if (controllerMesh) {
  71952. if (webVRController.hand === "left") {
  71953. if (!this._interactionsEnabledOnLeftController) {
  71954. this._enableInteractionOnController(webVRController);
  71955. }
  71956. this._teleportationEnabledOnLeftController = true;
  71957. }
  71958. else {
  71959. if (!this._interactionsEnabledOnRightController) {
  71960. this._enableInteractionOnController(webVRController);
  71961. }
  71962. this._teleportationEnabledOnRightController = true;
  71963. }
  71964. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  71965. if (!_this._teleportationRequestInitiated) {
  71966. if (stateObject.y < -_this._padSensibilityUp) {
  71967. // If laser pointer wasn't enabled yet
  71968. if (_this._displayLaserPointer && webVRController.hand === "left" && _this._leftLaserPointer) {
  71969. _this._leftLaserPointer.isVisible = true;
  71970. if (_this._rightLaserPointer) {
  71971. _this._rightLaserPointer.isVisible = false;
  71972. }
  71973. }
  71974. else if (_this._displayLaserPointer && _this._rightLaserPointer) {
  71975. _this._rightLaserPointer.isVisible = true;
  71976. if (_this._leftLaserPointer) {
  71977. _this._leftLaserPointer.isVisible = false;
  71978. }
  71979. }
  71980. _this._teleportationRequestInitiated = true;
  71981. }
  71982. }
  71983. else {
  71984. // Listening to the proper controller values changes to confirm teleportation
  71985. if ((webVRController.hand === "left" && _this._leftLaserPointer && _this._leftLaserPointer.isVisible)
  71986. || (webVRController.hand === "right" && _this._rightLaserPointer && _this._rightLaserPointer.isVisible)) {
  71987. if (stateObject.y > -_this._padSensibilityDown) {
  71988. if (_this._teleportationAllowed) {
  71989. _this._teleportationAllowed = false;
  71990. _this._teleportCamera();
  71991. }
  71992. _this._teleportationRequestInitiated = false;
  71993. }
  71994. }
  71995. }
  71996. if (!_this._rotationLeftAsked) {
  71997. if (stateObject.x < -_this._padSensibilityUp) {
  71998. _this._rotationLeftAsked = true;
  71999. if (_this._rotationAllowed) {
  72000. _this._rotateCamera(false);
  72001. }
  72002. }
  72003. }
  72004. else {
  72005. if (stateObject.x > -_this._padSensibilityDown) {
  72006. _this._rotationLeftAsked = false;
  72007. }
  72008. }
  72009. if (!_this._rotationRightAsked) {
  72010. if (stateObject.x > _this._padSensibilityUp) {
  72011. _this._rotationRightAsked = true;
  72012. if (_this._rotationAllowed) {
  72013. _this._rotateCamera(true);
  72014. }
  72015. }
  72016. }
  72017. else {
  72018. if (stateObject.x < _this._padSensibilityDown) {
  72019. _this._rotationRightAsked = false;
  72020. }
  72021. }
  72022. });
  72023. }
  72024. };
  72025. // Gaze support used to point to teleport or to interact with an object
  72026. VRExperienceHelper.prototype._createGazeTracker = function () {
  72027. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  72028. this._gazeTracker.bakeCurrentTransformIntoVertices();
  72029. this._gazeTracker.isPickable = false;
  72030. this._gazeTracker.isVisible = false;
  72031. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  72032. targetMat.specularColor = BABYLON.Color3.Black();
  72033. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  72034. targetMat.backFaceCulling = false;
  72035. this._gazeTracker.material = targetMat;
  72036. };
  72037. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  72038. this._teleportationCircle = BABYLON.Mesh.CreateGround("teleportationCircle", 2, 2, 2, this._scene);
  72039. this._teleportationCircle.isPickable = false;
  72040. var length = 512;
  72041. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  72042. dynamicTexture.hasAlpha = true;
  72043. var context = dynamicTexture.getContext();
  72044. var centerX = length / 2;
  72045. var centerY = length / 2;
  72046. var radius = 200;
  72047. context.beginPath();
  72048. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  72049. context.fillStyle = this._teleportationFillColor;
  72050. context.fill();
  72051. context.lineWidth = 10;
  72052. context.strokeStyle = this._teleportationBorderColor;
  72053. context.stroke();
  72054. context.closePath();
  72055. dynamicTexture.update();
  72056. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  72057. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  72058. this._teleportationCircle.material = teleportationCircleMaterial;
  72059. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  72060. torus.isPickable = false;
  72061. torus.parent = this._teleportationCircle;
  72062. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  72063. var keys = [];
  72064. keys.push({
  72065. frame: 0,
  72066. value: 0
  72067. });
  72068. keys.push({
  72069. frame: 30,
  72070. value: 0.4
  72071. });
  72072. keys.push({
  72073. frame: 60,
  72074. value: 0
  72075. });
  72076. animationInnerCircle.setKeys(keys);
  72077. var easingFunction = new BABYLON.SineEase();
  72078. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  72079. animationInnerCircle.setEasingFunction(easingFunction);
  72080. torus.animations = [];
  72081. torus.animations.push(animationInnerCircle);
  72082. this._scene.beginAnimation(torus, 0, 60, true);
  72083. this._hideTeleportationCircle();
  72084. };
  72085. VRExperienceHelper.prototype._displayTeleportationCircle = function () {
  72086. if (this._teleportationEnabled) {
  72087. this._teleportationCircle.isVisible = true;
  72088. this._teleportationCircle.getChildren()[0].isVisible = true;
  72089. }
  72090. };
  72091. VRExperienceHelper.prototype._hideTeleportationCircle = function () {
  72092. if (this._teleportationEnabled) {
  72093. this._teleportationCircle.isVisible = false;
  72094. this._teleportationCircle.getChildren()[0].isVisible = false;
  72095. }
  72096. };
  72097. VRExperienceHelper.prototype._rotateCamera = function (right) {
  72098. var _this = this;
  72099. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  72100. return;
  72101. }
  72102. if (right) {
  72103. this._rotationAngle++;
  72104. }
  72105. else {
  72106. this._rotationAngle--;
  72107. }
  72108. this.currentVRCamera.animations = [];
  72109. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  72110. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  72111. var animationRotationKeys = [];
  72112. animationRotationKeys.push({
  72113. frame: 0,
  72114. value: this.currentVRCamera.rotationQuaternion
  72115. });
  72116. animationRotationKeys.push({
  72117. frame: 6,
  72118. value: target
  72119. });
  72120. animationRotation.setKeys(animationRotationKeys);
  72121. animationRotation.setEasingFunction(this._circleEase);
  72122. this.currentVRCamera.animations.push(animationRotation);
  72123. this._postProcessMove.animations = [];
  72124. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  72125. var vignetteWeightKeys = [];
  72126. vignetteWeightKeys.push({
  72127. frame: 0,
  72128. value: 0
  72129. });
  72130. vignetteWeightKeys.push({
  72131. frame: 3,
  72132. value: 4
  72133. });
  72134. vignetteWeightKeys.push({
  72135. frame: 6,
  72136. value: 0
  72137. });
  72138. animationPP.setKeys(vignetteWeightKeys);
  72139. animationPP.setEasingFunction(this._circleEase);
  72140. this._postProcessMove.animations.push(animationPP);
  72141. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  72142. var vignetteStretchKeys = [];
  72143. vignetteStretchKeys.push({
  72144. frame: 0,
  72145. value: 0
  72146. });
  72147. vignetteStretchKeys.push({
  72148. frame: 3,
  72149. value: 10
  72150. });
  72151. vignetteStretchKeys.push({
  72152. frame: 6,
  72153. value: 0
  72154. });
  72155. animationPP2.setKeys(vignetteStretchKeys);
  72156. animationPP2.setEasingFunction(this._circleEase);
  72157. this._postProcessMove.animations.push(animationPP2);
  72158. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  72159. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  72160. this._webVRCamera.attachPostProcess(this._postProcessMove);
  72161. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  72162. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  72163. });
  72164. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  72165. };
  72166. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  72167. if (hit.pickedPoint) {
  72168. this._teleportationAllowed = true;
  72169. if (this._teleportationRequestInitiated) {
  72170. this._displayTeleportationCircle();
  72171. }
  72172. else {
  72173. this._hideTeleportationCircle();
  72174. }
  72175. this._haloCenter.copyFrom(hit.pickedPoint);
  72176. this._teleportationCircle.position.copyFrom(hit.pickedPoint);
  72177. var pickNormal = hit.getNormal(true, false);
  72178. if (pickNormal) {
  72179. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  72180. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  72181. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationCircle.rotation);
  72182. }
  72183. this._teleportationCircle.position.y += 0.1;
  72184. }
  72185. };
  72186. VRExperienceHelper.prototype._teleportCamera = function () {
  72187. var _this = this;
  72188. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  72189. return;
  72190. }
  72191. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  72192. // offset of the headset from the anchor. Then add the helper's position to account for user's height offset
  72193. if (this.webVRCamera.leftCamera) {
  72194. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  72195. this._workingVector.subtractInPlace(this.webVRCamera.position);
  72196. this._haloCenter.subtractToRef(this._workingVector, this._workingVector);
  72197. }
  72198. else {
  72199. this._workingVector.copyFrom(this._haloCenter);
  72200. }
  72201. this._workingVector.y += this._defaultHeight;
  72202. // Create animation from the camera's position to the new location
  72203. this.currentVRCamera.animations = [];
  72204. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  72205. var animationCameraTeleportationKeys = [{
  72206. frame: 0,
  72207. value: this.currentVRCamera.position
  72208. },
  72209. {
  72210. frame: 11,
  72211. value: this._workingVector
  72212. }
  72213. ];
  72214. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  72215. animationCameraTeleportation.setEasingFunction(this._circleEase);
  72216. this.currentVRCamera.animations.push(animationCameraTeleportation);
  72217. this._postProcessMove.animations = [];
  72218. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  72219. var vignetteWeightKeys = [];
  72220. vignetteWeightKeys.push({
  72221. frame: 0,
  72222. value: 0
  72223. });
  72224. vignetteWeightKeys.push({
  72225. frame: 5,
  72226. value: 8
  72227. });
  72228. vignetteWeightKeys.push({
  72229. frame: 11,
  72230. value: 0
  72231. });
  72232. animationPP.setKeys(vignetteWeightKeys);
  72233. this._postProcessMove.animations.push(animationPP);
  72234. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  72235. var vignetteStretchKeys = [];
  72236. vignetteStretchKeys.push({
  72237. frame: 0,
  72238. value: 0
  72239. });
  72240. vignetteStretchKeys.push({
  72241. frame: 5,
  72242. value: 10
  72243. });
  72244. vignetteStretchKeys.push({
  72245. frame: 11,
  72246. value: 0
  72247. });
  72248. animationPP2.setKeys(vignetteStretchKeys);
  72249. this._postProcessMove.animations.push(animationPP2);
  72250. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  72251. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  72252. this._webVRCamera.attachPostProcess(this._postProcessMove);
  72253. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  72254. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  72255. });
  72256. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1);
  72257. };
  72258. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  72259. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  72260. return;
  72261. }
  72262. var ray;
  72263. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  72264. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  72265. }
  72266. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  72267. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  72268. }
  72269. else {
  72270. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  72271. }
  72272. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  72273. // Moving the gazeTracker on the mesh face targetted
  72274. if (hit && hit.pickedPoint) {
  72275. if (this._displayGaze) {
  72276. var multiplier = 1;
  72277. this._gazeTracker.isVisible = true;
  72278. if (this._isActionableMesh) {
  72279. multiplier = 3;
  72280. }
  72281. this._gazeTracker.scaling.x = hit.distance * multiplier;
  72282. this._gazeTracker.scaling.y = hit.distance * multiplier;
  72283. this._gazeTracker.scaling.z = hit.distance * multiplier;
  72284. var pickNormal = hit.getNormal();
  72285. // To avoid z-fighting
  72286. var deltaFighting = 0.002;
  72287. if (pickNormal) {
  72288. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  72289. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  72290. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  72291. }
  72292. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  72293. if (this._gazeTracker.position.x < 0) {
  72294. this._gazeTracker.position.x += deltaFighting;
  72295. }
  72296. else {
  72297. this._gazeTracker.position.x -= deltaFighting;
  72298. }
  72299. if (this._gazeTracker.position.y < 0) {
  72300. this._gazeTracker.position.y += deltaFighting;
  72301. }
  72302. else {
  72303. this._gazeTracker.position.y -= deltaFighting;
  72304. }
  72305. if (this._gazeTracker.position.z < 0) {
  72306. this._gazeTracker.position.z += deltaFighting;
  72307. }
  72308. else {
  72309. this._gazeTracker.position.z -= deltaFighting;
  72310. }
  72311. }
  72312. // Changing the size of the laser pointer based on the distance from the targetted point
  72313. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  72314. this._rightLaserPointer.scaling.y = hit.distance;
  72315. this._rightLaserPointer.position.z = -hit.distance / 2;
  72316. }
  72317. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  72318. this._leftLaserPointer.scaling.y = hit.distance;
  72319. this._leftLaserPointer.position.z = -hit.distance / 2;
  72320. }
  72321. }
  72322. else {
  72323. this._gazeTracker.isVisible = false;
  72324. }
  72325. if (hit && hit.pickedMesh) {
  72326. this._currentHit = hit;
  72327. if (this._pointerDownOnMeshAsked) {
  72328. this._scene.simulatePointerMove(this._currentHit);
  72329. }
  72330. // The object selected is the floor, we're in a teleportation scenario
  72331. if (this._teleportationEnabled && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  72332. // Moving the teleportation area to this targetted point
  72333. this._moveTeleportationSelectorTo(hit);
  72334. return;
  72335. }
  72336. // If not, we're in a selection scenario
  72337. this._hideTeleportationCircle();
  72338. this._teleportationAllowed = false;
  72339. if (hit.pickedMesh !== this._currentMeshSelected) {
  72340. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  72341. this._currentMeshSelected = hit.pickedMesh;
  72342. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  72343. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  72344. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  72345. this._isActionableMesh = true;
  72346. }
  72347. else {
  72348. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  72349. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  72350. this._isActionableMesh = false;
  72351. }
  72352. try {
  72353. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  72354. }
  72355. catch (err) {
  72356. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  72357. }
  72358. }
  72359. else {
  72360. this._currentMeshSelected = null;
  72361. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  72362. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  72363. }
  72364. }
  72365. }
  72366. else {
  72367. this._currentHit = null;
  72368. this._currentMeshSelected = null;
  72369. this._teleportationAllowed = false;
  72370. this._hideTeleportationCircle();
  72371. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  72372. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  72373. }
  72374. };
  72375. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  72376. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  72377. this._leftLaserPointer.material.emissiveColor = color;
  72378. }
  72379. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  72380. this._rightLaserPointer.material.emissiveColor = color;
  72381. }
  72382. };
  72383. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  72384. if (this._gazeTracker.material) {
  72385. this._gazeTracker.material.emissiveColor = color;
  72386. }
  72387. };
  72388. VRExperienceHelper.prototype.dispose = function () {
  72389. if (this.isInVRMode()) {
  72390. this.exitVR();
  72391. }
  72392. if (this._deviceOrientationCamera) {
  72393. this._deviceOrientationCamera.dispose();
  72394. }
  72395. if (this._passProcessMove) {
  72396. this._passProcessMove.dispose();
  72397. }
  72398. if (this._postProcessMove) {
  72399. this._postProcessMove.dispose();
  72400. }
  72401. if (this._webVRCamera) {
  72402. this._webVRCamera.dispose();
  72403. }
  72404. if (this._vrDeviceOrientationCamera) {
  72405. this._vrDeviceOrientationCamera.dispose();
  72406. }
  72407. if (!this._useCustomVRButton) {
  72408. document.body.removeChild(this._btnVR);
  72409. }
  72410. this._floorMeshesCollection = [];
  72411. document.removeEventListener("keydown", this._onKeyDown);
  72412. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  72413. };
  72414. VRExperienceHelper.prototype.getClassName = function () {
  72415. return "VRExperienceHelper";
  72416. };
  72417. return VRExperienceHelper;
  72418. }());
  72419. BABYLON.VRExperienceHelper = VRExperienceHelper;
  72420. })(BABYLON || (BABYLON = {}));
  72421. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  72422. // Mainly based on these 2 articles :
  72423. // 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
  72424. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  72425. var BABYLON;
  72426. (function (BABYLON) {
  72427. var JoystickAxis;
  72428. (function (JoystickAxis) {
  72429. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  72430. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  72431. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  72432. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  72433. var VirtualJoystick = /** @class */ (function () {
  72434. function VirtualJoystick(leftJoystick) {
  72435. var _this = this;
  72436. if (leftJoystick) {
  72437. this._leftJoystick = true;
  72438. }
  72439. else {
  72440. this._leftJoystick = false;
  72441. }
  72442. VirtualJoystick._globalJoystickIndex++;
  72443. // By default left & right arrow keys are moving the X
  72444. // and up & down keys are moving the Y
  72445. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  72446. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  72447. this.reverseLeftRight = false;
  72448. this.reverseUpDown = false;
  72449. // collections of pointers
  72450. this._touches = new BABYLON.StringDictionary();
  72451. this.deltaPosition = BABYLON.Vector3.Zero();
  72452. this._joystickSensibility = 25;
  72453. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  72454. this._onResize = function (evt) {
  72455. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  72456. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  72457. if (VirtualJoystick.vjCanvas) {
  72458. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  72459. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  72460. }
  72461. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  72462. };
  72463. // injecting a canvas element on top of the canvas 3D game
  72464. if (!VirtualJoystick.vjCanvas) {
  72465. window.addEventListener("resize", this._onResize, false);
  72466. VirtualJoystick.vjCanvas = document.createElement("canvas");
  72467. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  72468. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  72469. VirtualJoystick.vjCanvas.width = window.innerWidth;
  72470. VirtualJoystick.vjCanvas.height = window.innerHeight;
  72471. VirtualJoystick.vjCanvas.style.width = "100%";
  72472. VirtualJoystick.vjCanvas.style.height = "100%";
  72473. VirtualJoystick.vjCanvas.style.position = "absolute";
  72474. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  72475. VirtualJoystick.vjCanvas.style.top = "0px";
  72476. VirtualJoystick.vjCanvas.style.left = "0px";
  72477. VirtualJoystick.vjCanvas.style.zIndex = "5";
  72478. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  72479. // Support for jQuery PEP polyfill
  72480. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  72481. var context = VirtualJoystick.vjCanvas.getContext('2d');
  72482. if (!context) {
  72483. throw new Error("Unable to create canvas for virtual joystick");
  72484. }
  72485. VirtualJoystick.vjCanvasContext = context;
  72486. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  72487. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  72488. document.body.appendChild(VirtualJoystick.vjCanvas);
  72489. }
  72490. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  72491. this.pressed = false;
  72492. // default joystick color
  72493. this._joystickColor = "cyan";
  72494. this._joystickPointerID = -1;
  72495. // current joystick position
  72496. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  72497. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  72498. // origin joystick position
  72499. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  72500. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  72501. this._onPointerDownHandlerRef = function (evt) {
  72502. _this._onPointerDown(evt);
  72503. };
  72504. this._onPointerMoveHandlerRef = function (evt) {
  72505. _this._onPointerMove(evt);
  72506. };
  72507. this._onPointerUpHandlerRef = function (evt) {
  72508. _this._onPointerUp(evt);
  72509. };
  72510. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  72511. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  72512. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  72513. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  72514. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  72515. evt.preventDefault(); // Disables system menu
  72516. }, false);
  72517. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  72518. }
  72519. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  72520. this._joystickSensibility = newJoystickSensibility;
  72521. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  72522. };
  72523. VirtualJoystick.prototype._onPointerDown = function (e) {
  72524. var positionOnScreenCondition;
  72525. e.preventDefault();
  72526. if (this._leftJoystick === true) {
  72527. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  72528. }
  72529. else {
  72530. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  72531. }
  72532. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  72533. // First contact will be dedicated to the virtual joystick
  72534. this._joystickPointerID = e.pointerId;
  72535. this._joystickPointerStartPos.x = e.clientX;
  72536. this._joystickPointerStartPos.y = e.clientY;
  72537. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  72538. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  72539. this._deltaJoystickVector.x = 0;
  72540. this._deltaJoystickVector.y = 0;
  72541. this.pressed = true;
  72542. this._touches.add(e.pointerId.toString(), e);
  72543. }
  72544. else {
  72545. // You can only trigger the action buttons with a joystick declared
  72546. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  72547. this._action();
  72548. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  72549. }
  72550. }
  72551. };
  72552. VirtualJoystick.prototype._onPointerMove = function (e) {
  72553. // If the current pointer is the one associated to the joystick (first touch contact)
  72554. if (this._joystickPointerID == e.pointerId) {
  72555. this._joystickPointerPos.x = e.clientX;
  72556. this._joystickPointerPos.y = e.clientY;
  72557. this._deltaJoystickVector = this._joystickPointerPos.clone();
  72558. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  72559. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  72560. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  72561. switch (this._axisTargetedByLeftAndRight) {
  72562. case JoystickAxis.X:
  72563. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  72564. break;
  72565. case JoystickAxis.Y:
  72566. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  72567. break;
  72568. case JoystickAxis.Z:
  72569. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  72570. break;
  72571. }
  72572. var directionUpDown = this.reverseUpDown ? 1 : -1;
  72573. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  72574. switch (this._axisTargetedByUpAndDown) {
  72575. case JoystickAxis.X:
  72576. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  72577. break;
  72578. case JoystickAxis.Y:
  72579. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  72580. break;
  72581. case JoystickAxis.Z:
  72582. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  72583. break;
  72584. }
  72585. }
  72586. else {
  72587. var data = this._touches.get(e.pointerId.toString());
  72588. if (data) {
  72589. data.x = e.clientX;
  72590. data.y = e.clientY;
  72591. }
  72592. }
  72593. };
  72594. VirtualJoystick.prototype._onPointerUp = function (e) {
  72595. if (this._joystickPointerID == e.pointerId) {
  72596. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  72597. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  72598. this._joystickPointerID = -1;
  72599. this.pressed = false;
  72600. }
  72601. else {
  72602. var touch = this._touches.get(e.pointerId.toString());
  72603. if (touch) {
  72604. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  72605. }
  72606. }
  72607. this._deltaJoystickVector.x = 0;
  72608. this._deltaJoystickVector.y = 0;
  72609. this._touches.remove(e.pointerId.toString());
  72610. };
  72611. /**
  72612. * Change the color of the virtual joystick
  72613. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  72614. */
  72615. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  72616. this._joystickColor = newColor;
  72617. };
  72618. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  72619. this._action = action;
  72620. };
  72621. // Define which axis you'd like to control for left & right
  72622. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  72623. switch (axis) {
  72624. case JoystickAxis.X:
  72625. case JoystickAxis.Y:
  72626. case JoystickAxis.Z:
  72627. this._axisTargetedByLeftAndRight = axis;
  72628. break;
  72629. default:
  72630. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  72631. break;
  72632. }
  72633. };
  72634. // Define which axis you'd like to control for up & down
  72635. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  72636. switch (axis) {
  72637. case JoystickAxis.X:
  72638. case JoystickAxis.Y:
  72639. case JoystickAxis.Z:
  72640. this._axisTargetedByUpAndDown = axis;
  72641. break;
  72642. default:
  72643. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  72644. break;
  72645. }
  72646. };
  72647. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  72648. var _this = this;
  72649. if (this.pressed) {
  72650. this._touches.forEach(function (key, touch) {
  72651. if (touch.pointerId === _this._joystickPointerID) {
  72652. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  72653. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  72654. VirtualJoystick.vjCanvasContext.beginPath();
  72655. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  72656. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  72657. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  72658. VirtualJoystick.vjCanvasContext.stroke();
  72659. VirtualJoystick.vjCanvasContext.closePath();
  72660. VirtualJoystick.vjCanvasContext.beginPath();
  72661. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  72662. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  72663. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  72664. VirtualJoystick.vjCanvasContext.stroke();
  72665. VirtualJoystick.vjCanvasContext.closePath();
  72666. VirtualJoystick.vjCanvasContext.beginPath();
  72667. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  72668. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  72669. VirtualJoystick.vjCanvasContext.stroke();
  72670. VirtualJoystick.vjCanvasContext.closePath();
  72671. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  72672. }
  72673. else {
  72674. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  72675. VirtualJoystick.vjCanvasContext.beginPath();
  72676. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  72677. VirtualJoystick.vjCanvasContext.beginPath();
  72678. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  72679. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  72680. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  72681. VirtualJoystick.vjCanvasContext.stroke();
  72682. VirtualJoystick.vjCanvasContext.closePath();
  72683. touch.prevX = touch.x;
  72684. touch.prevY = touch.y;
  72685. }
  72686. ;
  72687. });
  72688. }
  72689. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  72690. };
  72691. VirtualJoystick.prototype.releaseCanvas = function () {
  72692. if (VirtualJoystick.vjCanvas) {
  72693. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  72694. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  72695. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  72696. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  72697. window.removeEventListener("resize", this._onResize);
  72698. document.body.removeChild(VirtualJoystick.vjCanvas);
  72699. VirtualJoystick.vjCanvas = null;
  72700. }
  72701. };
  72702. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  72703. VirtualJoystick._globalJoystickIndex = 0;
  72704. return VirtualJoystick;
  72705. }());
  72706. BABYLON.VirtualJoystick = VirtualJoystick;
  72707. })(BABYLON || (BABYLON = {}));
  72708. //# sourceMappingURL=babylon.virtualJoystick.js.map
  72709. var BABYLON;
  72710. (function (BABYLON) {
  72711. // We're mainly based on the logic defined into the FreeCamera code
  72712. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  72713. __extends(VirtualJoysticksCamera, _super);
  72714. function VirtualJoysticksCamera(name, position, scene) {
  72715. var _this = _super.call(this, name, position, scene) || this;
  72716. _this.inputs.addVirtualJoystick();
  72717. return _this;
  72718. }
  72719. VirtualJoysticksCamera.prototype.getClassName = function () {
  72720. return "VirtualJoysticksCamera";
  72721. };
  72722. return VirtualJoysticksCamera;
  72723. }(BABYLON.FreeCamera));
  72724. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  72725. })(BABYLON || (BABYLON = {}));
  72726. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  72727. var BABYLON;
  72728. (function (BABYLON) {
  72729. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  72730. function FreeCameraVirtualJoystickInput() {
  72731. }
  72732. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  72733. return this._leftjoystick;
  72734. };
  72735. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  72736. return this._rightjoystick;
  72737. };
  72738. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  72739. if (this._leftjoystick) {
  72740. var camera = this.camera;
  72741. var speed = camera._computeLocalCameraSpeed() * 50;
  72742. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  72743. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  72744. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  72745. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  72746. if (!this._leftjoystick.pressed) {
  72747. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  72748. }
  72749. if (!this._rightjoystick.pressed) {
  72750. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  72751. }
  72752. }
  72753. };
  72754. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  72755. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  72756. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  72757. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  72758. this._leftjoystick.setJoystickSensibility(0.15);
  72759. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  72760. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  72761. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  72762. this._rightjoystick.reverseUpDown = true;
  72763. this._rightjoystick.setJoystickSensibility(0.05);
  72764. this._rightjoystick.setJoystickColor("yellow");
  72765. };
  72766. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  72767. this._leftjoystick.releaseCanvas();
  72768. this._rightjoystick.releaseCanvas();
  72769. };
  72770. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  72771. return "FreeCameraVirtualJoystickInput";
  72772. };
  72773. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  72774. return "virtualJoystick";
  72775. };
  72776. return FreeCameraVirtualJoystickInput;
  72777. }());
  72778. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  72779. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  72780. })(BABYLON || (BABYLON = {}));
  72781. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  72782. var BABYLON;
  72783. (function (BABYLON) {
  72784. var SimplificationSettings = /** @class */ (function () {
  72785. function SimplificationSettings(quality, distance, optimizeMesh) {
  72786. this.quality = quality;
  72787. this.distance = distance;
  72788. this.optimizeMesh = optimizeMesh;
  72789. }
  72790. return SimplificationSettings;
  72791. }());
  72792. BABYLON.SimplificationSettings = SimplificationSettings;
  72793. var SimplificationQueue = /** @class */ (function () {
  72794. function SimplificationQueue() {
  72795. this.running = false;
  72796. this._simplificationArray = [];
  72797. }
  72798. SimplificationQueue.prototype.addTask = function (task) {
  72799. this._simplificationArray.push(task);
  72800. };
  72801. SimplificationQueue.prototype.executeNext = function () {
  72802. var task = this._simplificationArray.pop();
  72803. if (task) {
  72804. this.running = true;
  72805. this.runSimplification(task);
  72806. }
  72807. else {
  72808. this.running = false;
  72809. }
  72810. };
  72811. SimplificationQueue.prototype.runSimplification = function (task) {
  72812. var _this = this;
  72813. if (task.parallelProcessing) {
  72814. //parallel simplifier
  72815. task.settings.forEach(function (setting) {
  72816. var simplifier = _this.getSimplifier(task);
  72817. simplifier.simplify(setting, function (newMesh) {
  72818. task.mesh.addLODLevel(setting.distance, newMesh);
  72819. newMesh.isVisible = true;
  72820. //check if it is the last
  72821. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  72822. //all done, run the success callback.
  72823. task.successCallback();
  72824. }
  72825. _this.executeNext();
  72826. });
  72827. });
  72828. }
  72829. else {
  72830. //single simplifier.
  72831. var simplifier = this.getSimplifier(task);
  72832. var runDecimation = function (setting, callback) {
  72833. simplifier.simplify(setting, function (newMesh) {
  72834. task.mesh.addLODLevel(setting.distance, newMesh);
  72835. newMesh.isVisible = true;
  72836. //run the next quality level
  72837. callback();
  72838. });
  72839. };
  72840. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  72841. runDecimation(task.settings[loop.index], function () {
  72842. loop.executeNext();
  72843. });
  72844. }, function () {
  72845. //execution ended, run the success callback.
  72846. if (task.successCallback) {
  72847. task.successCallback();
  72848. }
  72849. _this.executeNext();
  72850. });
  72851. }
  72852. };
  72853. SimplificationQueue.prototype.getSimplifier = function (task) {
  72854. switch (task.simplificationType) {
  72855. case SimplificationType.QUADRATIC:
  72856. default:
  72857. return new QuadraticErrorSimplification(task.mesh);
  72858. }
  72859. };
  72860. return SimplificationQueue;
  72861. }());
  72862. BABYLON.SimplificationQueue = SimplificationQueue;
  72863. /**
  72864. * The implemented types of simplification.
  72865. * At the moment only Quadratic Error Decimation is implemented.
  72866. */
  72867. var SimplificationType;
  72868. (function (SimplificationType) {
  72869. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  72870. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  72871. var DecimationTriangle = /** @class */ (function () {
  72872. function DecimationTriangle(vertices) {
  72873. this.vertices = vertices;
  72874. this.error = new Array(4);
  72875. this.deleted = false;
  72876. this.isDirty = false;
  72877. this.deletePending = false;
  72878. this.borderFactor = 0;
  72879. }
  72880. return DecimationTriangle;
  72881. }());
  72882. BABYLON.DecimationTriangle = DecimationTriangle;
  72883. var DecimationVertex = /** @class */ (function () {
  72884. function DecimationVertex(position, id) {
  72885. this.position = position;
  72886. this.id = id;
  72887. this.isBorder = true;
  72888. this.q = new QuadraticMatrix();
  72889. this.triangleCount = 0;
  72890. this.triangleStart = 0;
  72891. this.originalOffsets = [];
  72892. }
  72893. DecimationVertex.prototype.updatePosition = function (newPosition) {
  72894. this.position.copyFrom(newPosition);
  72895. };
  72896. return DecimationVertex;
  72897. }());
  72898. BABYLON.DecimationVertex = DecimationVertex;
  72899. var QuadraticMatrix = /** @class */ (function () {
  72900. function QuadraticMatrix(data) {
  72901. this.data = new Array(10);
  72902. for (var i = 0; i < 10; ++i) {
  72903. if (data && data[i]) {
  72904. this.data[i] = data[i];
  72905. }
  72906. else {
  72907. this.data[i] = 0;
  72908. }
  72909. }
  72910. }
  72911. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  72912. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  72913. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  72914. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  72915. return det;
  72916. };
  72917. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  72918. for (var i = 0; i < 10; ++i) {
  72919. this.data[i] += matrix.data[i];
  72920. }
  72921. };
  72922. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  72923. for (var i = 0; i < 10; ++i) {
  72924. this.data[i] += data[i];
  72925. }
  72926. };
  72927. QuadraticMatrix.prototype.add = function (matrix) {
  72928. var m = new QuadraticMatrix();
  72929. for (var i = 0; i < 10; ++i) {
  72930. m.data[i] = this.data[i] + matrix.data[i];
  72931. }
  72932. return m;
  72933. };
  72934. QuadraticMatrix.FromData = function (a, b, c, d) {
  72935. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  72936. };
  72937. //returning an array to avoid garbage collection
  72938. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  72939. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  72940. };
  72941. return QuadraticMatrix;
  72942. }());
  72943. BABYLON.QuadraticMatrix = QuadraticMatrix;
  72944. var Reference = /** @class */ (function () {
  72945. function Reference(vertexId, triangleId) {
  72946. this.vertexId = vertexId;
  72947. this.triangleId = triangleId;
  72948. }
  72949. return Reference;
  72950. }());
  72951. BABYLON.Reference = Reference;
  72952. /**
  72953. * An implementation of the Quadratic Error simplification algorithm.
  72954. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  72955. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  72956. * @author RaananW
  72957. */
  72958. var QuadraticErrorSimplification = /** @class */ (function () {
  72959. function QuadraticErrorSimplification(_mesh) {
  72960. this._mesh = _mesh;
  72961. this.syncIterations = 5000;
  72962. this.aggressiveness = 7;
  72963. this.decimationIterations = 100;
  72964. this.boundingBoxEpsilon = BABYLON.Epsilon;
  72965. }
  72966. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  72967. var _this = this;
  72968. this.initDecimatedMesh();
  72969. //iterating through the submeshes array, one after the other.
  72970. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  72971. _this.initWithMesh(loop.index, function () {
  72972. _this.runDecimation(settings, loop.index, function () {
  72973. loop.executeNext();
  72974. });
  72975. }, settings.optimizeMesh);
  72976. }, function () {
  72977. setTimeout(function () {
  72978. successCallback(_this._reconstructedMesh);
  72979. }, 0);
  72980. });
  72981. };
  72982. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  72983. var _this = this;
  72984. var targetCount = ~~(this.triangles.length * settings.quality);
  72985. var deletedTriangles = 0;
  72986. var triangleCount = this.triangles.length;
  72987. var iterationFunction = function (iteration, callback) {
  72988. setTimeout(function () {
  72989. if (iteration % 5 === 0) {
  72990. _this.updateMesh(iteration === 0);
  72991. }
  72992. for (var i = 0; i < _this.triangles.length; ++i) {
  72993. _this.triangles[i].isDirty = false;
  72994. }
  72995. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  72996. var trianglesIterator = function (i) {
  72997. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  72998. var t = _this.triangles[tIdx];
  72999. if (!t)
  73000. return;
  73001. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  73002. return;
  73003. }
  73004. for (var j = 0; j < 3; ++j) {
  73005. if (t.error[j] < threshold) {
  73006. var deleted0 = [];
  73007. var deleted1 = [];
  73008. var v0 = t.vertices[j];
  73009. var v1 = t.vertices[(j + 1) % 3];
  73010. if (v0.isBorder || v1.isBorder)
  73011. continue;
  73012. var p = BABYLON.Vector3.Zero();
  73013. var n = BABYLON.Vector3.Zero();
  73014. var uv = BABYLON.Vector2.Zero();
  73015. var color = new BABYLON.Color4(0, 0, 0, 1);
  73016. _this.calculateError(v0, v1, p, n, uv, color);
  73017. var delTr = new Array();
  73018. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  73019. continue;
  73020. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  73021. continue;
  73022. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  73023. continue;
  73024. var uniqueArray = new Array();
  73025. delTr.forEach(function (deletedT) {
  73026. if (uniqueArray.indexOf(deletedT) === -1) {
  73027. deletedT.deletePending = true;
  73028. uniqueArray.push(deletedT);
  73029. }
  73030. });
  73031. if (uniqueArray.length % 2 !== 0) {
  73032. continue;
  73033. }
  73034. v0.q = v1.q.add(v0.q);
  73035. v0.updatePosition(p);
  73036. var tStart = _this.references.length;
  73037. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  73038. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  73039. var tCount = _this.references.length - tStart;
  73040. if (tCount <= v0.triangleCount) {
  73041. if (tCount) {
  73042. for (var c = 0; c < tCount; c++) {
  73043. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  73044. }
  73045. }
  73046. }
  73047. else {
  73048. v0.triangleStart = tStart;
  73049. }
  73050. v0.triangleCount = tCount;
  73051. break;
  73052. }
  73053. }
  73054. };
  73055. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  73056. }, 0);
  73057. };
  73058. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  73059. if (triangleCount - deletedTriangles <= targetCount)
  73060. loop.breakLoop();
  73061. else {
  73062. iterationFunction(loop.index, function () {
  73063. loop.executeNext();
  73064. });
  73065. }
  73066. }, function () {
  73067. setTimeout(function () {
  73068. //reconstruct this part of the mesh
  73069. _this.reconstructMesh(submeshIndex);
  73070. successCallback();
  73071. }, 0);
  73072. });
  73073. };
  73074. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  73075. var _this = this;
  73076. this.vertices = [];
  73077. this.triangles = [];
  73078. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  73079. var indices = this._mesh.getIndices();
  73080. var submesh = this._mesh.subMeshes[submeshIndex];
  73081. var findInVertices = function (positionToSearch) {
  73082. if (optimizeMesh) {
  73083. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  73084. if (_this.vertices[ii].position.equals(positionToSearch)) {
  73085. return _this.vertices[ii];
  73086. }
  73087. }
  73088. }
  73089. return null;
  73090. };
  73091. var vertexReferences = [];
  73092. var vertexInit = function (i) {
  73093. if (!positionData) {
  73094. return;
  73095. }
  73096. var offset = i + submesh.verticesStart;
  73097. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  73098. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  73099. vertex.originalOffsets.push(offset);
  73100. if (vertex.id === _this.vertices.length) {
  73101. _this.vertices.push(vertex);
  73102. }
  73103. vertexReferences.push(vertex.id);
  73104. };
  73105. //var totalVertices = mesh.getTotalVertices();
  73106. var totalVertices = submesh.verticesCount;
  73107. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  73108. var indicesInit = function (i) {
  73109. if (!indices) {
  73110. return;
  73111. }
  73112. var offset = (submesh.indexStart / 3) + i;
  73113. var pos = (offset * 3);
  73114. var i0 = indices[pos + 0];
  73115. var i1 = indices[pos + 1];
  73116. var i2 = indices[pos + 2];
  73117. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  73118. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  73119. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  73120. var triangle = new DecimationTriangle([v0, v1, v2]);
  73121. triangle.originalOffset = pos;
  73122. _this.triangles.push(triangle);
  73123. };
  73124. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  73125. _this.init(callback);
  73126. });
  73127. });
  73128. };
  73129. QuadraticErrorSimplification.prototype.init = function (callback) {
  73130. var _this = this;
  73131. var triangleInit1 = function (i) {
  73132. var t = _this.triangles[i];
  73133. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  73134. for (var j = 0; j < 3; j++) {
  73135. 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))));
  73136. }
  73137. };
  73138. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  73139. var triangleInit2 = function (i) {
  73140. var t = _this.triangles[i];
  73141. for (var j = 0; j < 3; ++j) {
  73142. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  73143. }
  73144. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  73145. };
  73146. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  73147. callback();
  73148. });
  73149. });
  73150. };
  73151. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  73152. var newTriangles = [];
  73153. var i;
  73154. for (i = 0; i < this.vertices.length; ++i) {
  73155. this.vertices[i].triangleCount = 0;
  73156. }
  73157. var t;
  73158. var j;
  73159. for (i = 0; i < this.triangles.length; ++i) {
  73160. if (!this.triangles[i].deleted) {
  73161. t = this.triangles[i];
  73162. for (j = 0; j < 3; ++j) {
  73163. t.vertices[j].triangleCount = 1;
  73164. }
  73165. newTriangles.push(t);
  73166. }
  73167. }
  73168. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  73169. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  73170. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  73171. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  73172. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  73173. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  73174. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  73175. var vertexCount = 0;
  73176. for (i = 0; i < this.vertices.length; ++i) {
  73177. var vertex = this.vertices[i];
  73178. vertex.id = vertexCount;
  73179. if (vertex.triangleCount) {
  73180. vertex.originalOffsets.forEach(function (originalOffset) {
  73181. if (!normalData) {
  73182. return;
  73183. }
  73184. newPositionData.push(vertex.position.x);
  73185. newPositionData.push(vertex.position.y);
  73186. newPositionData.push(vertex.position.z);
  73187. newNormalData.push(normalData[originalOffset * 3]);
  73188. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  73189. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  73190. if (uvs && uvs.length) {
  73191. newUVsData.push(uvs[(originalOffset * 2)]);
  73192. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  73193. }
  73194. else if (colorsData && colorsData.length) {
  73195. newColorsData.push(colorsData[(originalOffset * 4)]);
  73196. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  73197. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  73198. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  73199. }
  73200. ++vertexCount;
  73201. });
  73202. }
  73203. }
  73204. var startingIndex = this._reconstructedMesh.getTotalIndices();
  73205. var startingVertex = this._reconstructedMesh.getTotalVertices();
  73206. var submeshesArray = this._reconstructedMesh.subMeshes;
  73207. this._reconstructedMesh.subMeshes = [];
  73208. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  73209. var originalIndices = this._mesh.getIndices();
  73210. for (i = 0; i < newTriangles.length; ++i) {
  73211. t = newTriangles[i]; //now get the new referencing point for each vertex
  73212. [0, 1, 2].forEach(function (idx) {
  73213. var id = originalIndices[t.originalOffset + idx];
  73214. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  73215. if (offset < 0)
  73216. offset = 0;
  73217. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  73218. });
  73219. }
  73220. //overwriting the old vertex buffers and indices.
  73221. this._reconstructedMesh.setIndices(newIndicesArray);
  73222. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  73223. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  73224. if (newUVsData.length > 0)
  73225. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  73226. if (newColorsData.length > 0)
  73227. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  73228. //create submesh
  73229. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  73230. if (submeshIndex > 0) {
  73231. this._reconstructedMesh.subMeshes = [];
  73232. submeshesArray.forEach(function (submesh) {
  73233. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  73234. });
  73235. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  73236. }
  73237. };
  73238. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  73239. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  73240. this._reconstructedMesh.material = this._mesh.material;
  73241. this._reconstructedMesh.parent = this._mesh.parent;
  73242. this._reconstructedMesh.isVisible = false;
  73243. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  73244. };
  73245. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  73246. for (var i = 0; i < vertex1.triangleCount; ++i) {
  73247. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  73248. if (t.deleted)
  73249. continue;
  73250. var s = this.references[vertex1.triangleStart + i].vertexId;
  73251. var v1 = t.vertices[(s + 1) % 3];
  73252. var v2 = t.vertices[(s + 2) % 3];
  73253. if ((v1 === vertex2 || v2 === vertex2)) {
  73254. deletedArray[i] = true;
  73255. delTr.push(t);
  73256. continue;
  73257. }
  73258. var d1 = v1.position.subtract(point);
  73259. d1 = d1.normalize();
  73260. var d2 = v2.position.subtract(point);
  73261. d2 = d2.normalize();
  73262. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  73263. return true;
  73264. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  73265. deletedArray[i] = false;
  73266. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  73267. return true;
  73268. }
  73269. return false;
  73270. };
  73271. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  73272. var newDeleted = deletedTriangles;
  73273. for (var i = 0; i < vertex.triangleCount; ++i) {
  73274. var ref = this.references[vertex.triangleStart + i];
  73275. var t = this.triangles[ref.triangleId];
  73276. if (t.deleted)
  73277. continue;
  73278. if (deletedArray[i] && t.deletePending) {
  73279. t.deleted = true;
  73280. newDeleted++;
  73281. continue;
  73282. }
  73283. t.vertices[ref.vertexId] = origVertex;
  73284. t.isDirty = true;
  73285. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  73286. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  73287. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  73288. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  73289. this.references.push(ref);
  73290. }
  73291. return newDeleted;
  73292. };
  73293. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  73294. for (var i = 0; i < this.vertices.length; ++i) {
  73295. var vCount = [];
  73296. var vId = [];
  73297. var v = this.vertices[i];
  73298. var j;
  73299. for (j = 0; j < v.triangleCount; ++j) {
  73300. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  73301. for (var ii = 0; ii < 3; ii++) {
  73302. var ofs = 0;
  73303. var vv = triangle.vertices[ii];
  73304. while (ofs < vCount.length) {
  73305. if (vId[ofs] === vv.id)
  73306. break;
  73307. ++ofs;
  73308. }
  73309. if (ofs === vCount.length) {
  73310. vCount.push(1);
  73311. vId.push(vv.id);
  73312. }
  73313. else {
  73314. vCount[ofs]++;
  73315. }
  73316. }
  73317. }
  73318. for (j = 0; j < vCount.length; ++j) {
  73319. if (vCount[j] === 1) {
  73320. this.vertices[vId[j]].isBorder = true;
  73321. }
  73322. else {
  73323. this.vertices[vId[j]].isBorder = false;
  73324. }
  73325. }
  73326. }
  73327. };
  73328. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  73329. if (identifyBorders === void 0) { identifyBorders = false; }
  73330. var i;
  73331. if (!identifyBorders) {
  73332. var newTrianglesVector = [];
  73333. for (i = 0; i < this.triangles.length; ++i) {
  73334. if (!this.triangles[i].deleted) {
  73335. newTrianglesVector.push(this.triangles[i]);
  73336. }
  73337. }
  73338. this.triangles = newTrianglesVector;
  73339. }
  73340. for (i = 0; i < this.vertices.length; ++i) {
  73341. this.vertices[i].triangleCount = 0;
  73342. this.vertices[i].triangleStart = 0;
  73343. }
  73344. var t;
  73345. var j;
  73346. var v;
  73347. for (i = 0; i < this.triangles.length; ++i) {
  73348. t = this.triangles[i];
  73349. for (j = 0; j < 3; ++j) {
  73350. v = t.vertices[j];
  73351. v.triangleCount++;
  73352. }
  73353. }
  73354. var tStart = 0;
  73355. for (i = 0; i < this.vertices.length; ++i) {
  73356. this.vertices[i].triangleStart = tStart;
  73357. tStart += this.vertices[i].triangleCount;
  73358. this.vertices[i].triangleCount = 0;
  73359. }
  73360. var newReferences = new Array(this.triangles.length * 3);
  73361. for (i = 0; i < this.triangles.length; ++i) {
  73362. t = this.triangles[i];
  73363. for (j = 0; j < 3; ++j) {
  73364. v = t.vertices[j];
  73365. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  73366. v.triangleCount++;
  73367. }
  73368. }
  73369. this.references = newReferences;
  73370. if (identifyBorders) {
  73371. this.identifyBorder();
  73372. }
  73373. };
  73374. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  73375. var x = point.x;
  73376. var y = point.y;
  73377. var z = point.z;
  73378. 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
  73379. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  73380. };
  73381. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  73382. var q = vertex1.q.add(vertex2.q);
  73383. var border = vertex1.isBorder && vertex2.isBorder;
  73384. var error = 0;
  73385. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  73386. if (qDet !== 0 && !border) {
  73387. if (!pointResult) {
  73388. pointResult = BABYLON.Vector3.Zero();
  73389. }
  73390. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  73391. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  73392. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  73393. error = this.vertexError(q, pointResult);
  73394. }
  73395. else {
  73396. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  73397. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  73398. var error1 = this.vertexError(q, vertex1.position);
  73399. var error2 = this.vertexError(q, vertex2.position);
  73400. var error3 = this.vertexError(q, p3);
  73401. error = Math.min(error1, error2, error3);
  73402. if (error === error1) {
  73403. if (pointResult) {
  73404. pointResult.copyFrom(vertex1.position);
  73405. }
  73406. }
  73407. else if (error === error2) {
  73408. if (pointResult) {
  73409. pointResult.copyFrom(vertex2.position);
  73410. }
  73411. }
  73412. else {
  73413. if (pointResult) {
  73414. pointResult.copyFrom(p3);
  73415. }
  73416. }
  73417. }
  73418. return error;
  73419. };
  73420. return QuadraticErrorSimplification;
  73421. }());
  73422. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  73423. })(BABYLON || (BABYLON = {}));
  73424. //# sourceMappingURL=babylon.meshSimplification.js.map
  73425. var BABYLON;
  73426. (function (BABYLON) {
  73427. var Internals;
  73428. (function (Internals) {
  73429. var MeshLODLevel = /** @class */ (function () {
  73430. function MeshLODLevel(distance, mesh) {
  73431. this.distance = distance;
  73432. this.mesh = mesh;
  73433. }
  73434. return MeshLODLevel;
  73435. }());
  73436. Internals.MeshLODLevel = MeshLODLevel;
  73437. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  73438. })(BABYLON || (BABYLON = {}));
  73439. //# sourceMappingURL=babylon.meshLODLevel.js.map
  73440. var BABYLON;
  73441. (function (BABYLON) {
  73442. // Standard optimizations
  73443. var SceneOptimization = /** @class */ (function () {
  73444. function SceneOptimization(priority) {
  73445. if (priority === void 0) { priority = 0; }
  73446. this.priority = priority;
  73447. this.apply = function (scene) {
  73448. return true; // Return true if everything that can be done was applied
  73449. };
  73450. }
  73451. return SceneOptimization;
  73452. }());
  73453. BABYLON.SceneOptimization = SceneOptimization;
  73454. var TextureOptimization = /** @class */ (function (_super) {
  73455. __extends(TextureOptimization, _super);
  73456. function TextureOptimization(priority, maximumSize) {
  73457. if (priority === void 0) { priority = 0; }
  73458. if (maximumSize === void 0) { maximumSize = 1024; }
  73459. var _this = _super.call(this, priority) || this;
  73460. _this.priority = priority;
  73461. _this.maximumSize = maximumSize;
  73462. _this.apply = function (scene) {
  73463. var allDone = true;
  73464. for (var index = 0; index < scene.textures.length; index++) {
  73465. var texture = scene.textures[index];
  73466. if (!texture.canRescale || texture.getContext) {
  73467. continue;
  73468. }
  73469. var currentSize = texture.getSize();
  73470. var maxDimension = Math.max(currentSize.width, currentSize.height);
  73471. if (maxDimension > _this.maximumSize) {
  73472. texture.scale(0.5);
  73473. allDone = false;
  73474. }
  73475. }
  73476. return allDone;
  73477. };
  73478. return _this;
  73479. }
  73480. return TextureOptimization;
  73481. }(SceneOptimization));
  73482. BABYLON.TextureOptimization = TextureOptimization;
  73483. var HardwareScalingOptimization = /** @class */ (function (_super) {
  73484. __extends(HardwareScalingOptimization, _super);
  73485. function HardwareScalingOptimization(priority, maximumScale) {
  73486. if (priority === void 0) { priority = 0; }
  73487. if (maximumScale === void 0) { maximumScale = 2; }
  73488. var _this = _super.call(this, priority) || this;
  73489. _this.priority = priority;
  73490. _this.maximumScale = maximumScale;
  73491. _this._currentScale = 1;
  73492. _this.apply = function (scene) {
  73493. _this._currentScale++;
  73494. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  73495. return _this._currentScale >= _this.maximumScale;
  73496. };
  73497. return _this;
  73498. }
  73499. return HardwareScalingOptimization;
  73500. }(SceneOptimization));
  73501. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  73502. var ShadowsOptimization = /** @class */ (function (_super) {
  73503. __extends(ShadowsOptimization, _super);
  73504. function ShadowsOptimization() {
  73505. var _this = _super !== null && _super.apply(this, arguments) || this;
  73506. _this.apply = function (scene) {
  73507. scene.shadowsEnabled = false;
  73508. return true;
  73509. };
  73510. return _this;
  73511. }
  73512. return ShadowsOptimization;
  73513. }(SceneOptimization));
  73514. BABYLON.ShadowsOptimization = ShadowsOptimization;
  73515. var PostProcessesOptimization = /** @class */ (function (_super) {
  73516. __extends(PostProcessesOptimization, _super);
  73517. function PostProcessesOptimization() {
  73518. var _this = _super !== null && _super.apply(this, arguments) || this;
  73519. _this.apply = function (scene) {
  73520. scene.postProcessesEnabled = false;
  73521. return true;
  73522. };
  73523. return _this;
  73524. }
  73525. return PostProcessesOptimization;
  73526. }(SceneOptimization));
  73527. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  73528. var LensFlaresOptimization = /** @class */ (function (_super) {
  73529. __extends(LensFlaresOptimization, _super);
  73530. function LensFlaresOptimization() {
  73531. var _this = _super !== null && _super.apply(this, arguments) || this;
  73532. _this.apply = function (scene) {
  73533. scene.lensFlaresEnabled = false;
  73534. return true;
  73535. };
  73536. return _this;
  73537. }
  73538. return LensFlaresOptimization;
  73539. }(SceneOptimization));
  73540. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  73541. var ParticlesOptimization = /** @class */ (function (_super) {
  73542. __extends(ParticlesOptimization, _super);
  73543. function ParticlesOptimization() {
  73544. var _this = _super !== null && _super.apply(this, arguments) || this;
  73545. _this.apply = function (scene) {
  73546. scene.particlesEnabled = false;
  73547. return true;
  73548. };
  73549. return _this;
  73550. }
  73551. return ParticlesOptimization;
  73552. }(SceneOptimization));
  73553. BABYLON.ParticlesOptimization = ParticlesOptimization;
  73554. var RenderTargetsOptimization = /** @class */ (function (_super) {
  73555. __extends(RenderTargetsOptimization, _super);
  73556. function RenderTargetsOptimization() {
  73557. var _this = _super !== null && _super.apply(this, arguments) || this;
  73558. _this.apply = function (scene) {
  73559. scene.renderTargetsEnabled = false;
  73560. return true;
  73561. };
  73562. return _this;
  73563. }
  73564. return RenderTargetsOptimization;
  73565. }(SceneOptimization));
  73566. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  73567. var MergeMeshesOptimization = /** @class */ (function (_super) {
  73568. __extends(MergeMeshesOptimization, _super);
  73569. function MergeMeshesOptimization() {
  73570. var _this = _super !== null && _super.apply(this, arguments) || this;
  73571. _this._canBeMerged = function (abstractMesh) {
  73572. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  73573. return false;
  73574. }
  73575. var mesh = abstractMesh;
  73576. if (!mesh.isVisible || !mesh.isEnabled()) {
  73577. return false;
  73578. }
  73579. if (mesh.instances.length > 0) {
  73580. return false;
  73581. }
  73582. if (mesh.skeleton || mesh.hasLODLevels) {
  73583. return false;
  73584. }
  73585. if (mesh.parent) {
  73586. return false;
  73587. }
  73588. return true;
  73589. };
  73590. _this.apply = function (scene, updateSelectionTree) {
  73591. var globalPool = scene.meshes.slice(0);
  73592. var globalLength = globalPool.length;
  73593. for (var index = 0; index < globalLength; index++) {
  73594. var currentPool = new Array();
  73595. var current = globalPool[index];
  73596. // Checks
  73597. if (!_this._canBeMerged(current)) {
  73598. continue;
  73599. }
  73600. currentPool.push(current);
  73601. // Find compatible meshes
  73602. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  73603. var otherMesh = globalPool[subIndex];
  73604. if (!_this._canBeMerged(otherMesh)) {
  73605. continue;
  73606. }
  73607. if (otherMesh.material !== current.material) {
  73608. continue;
  73609. }
  73610. if (otherMesh.checkCollisions !== current.checkCollisions) {
  73611. continue;
  73612. }
  73613. currentPool.push(otherMesh);
  73614. globalLength--;
  73615. globalPool.splice(subIndex, 1);
  73616. subIndex--;
  73617. }
  73618. if (currentPool.length < 2) {
  73619. continue;
  73620. }
  73621. // Merge meshes
  73622. BABYLON.Mesh.MergeMeshes(currentPool);
  73623. }
  73624. if (updateSelectionTree != undefined) {
  73625. if (updateSelectionTree) {
  73626. scene.createOrUpdateSelectionOctree();
  73627. }
  73628. }
  73629. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  73630. scene.createOrUpdateSelectionOctree();
  73631. }
  73632. return true;
  73633. };
  73634. return _this;
  73635. }
  73636. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  73637. get: function () {
  73638. return MergeMeshesOptimization._UpdateSelectionTree;
  73639. },
  73640. set: function (value) {
  73641. MergeMeshesOptimization._UpdateSelectionTree = value;
  73642. },
  73643. enumerable: true,
  73644. configurable: true
  73645. });
  73646. MergeMeshesOptimization._UpdateSelectionTree = false;
  73647. return MergeMeshesOptimization;
  73648. }(SceneOptimization));
  73649. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  73650. // Options
  73651. var SceneOptimizerOptions = /** @class */ (function () {
  73652. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  73653. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  73654. if (trackerDuration === void 0) { trackerDuration = 2000; }
  73655. this.targetFrameRate = targetFrameRate;
  73656. this.trackerDuration = trackerDuration;
  73657. this.optimizations = new Array();
  73658. }
  73659. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  73660. var result = new SceneOptimizerOptions(targetFrameRate);
  73661. var priority = 0;
  73662. result.optimizations.push(new MergeMeshesOptimization(priority));
  73663. result.optimizations.push(new ShadowsOptimization(priority));
  73664. result.optimizations.push(new LensFlaresOptimization(priority));
  73665. // Next priority
  73666. priority++;
  73667. result.optimizations.push(new PostProcessesOptimization(priority));
  73668. result.optimizations.push(new ParticlesOptimization(priority));
  73669. // Next priority
  73670. priority++;
  73671. result.optimizations.push(new TextureOptimization(priority, 1024));
  73672. return result;
  73673. };
  73674. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  73675. var result = new SceneOptimizerOptions(targetFrameRate);
  73676. var priority = 0;
  73677. result.optimizations.push(new MergeMeshesOptimization(priority));
  73678. result.optimizations.push(new ShadowsOptimization(priority));
  73679. result.optimizations.push(new LensFlaresOptimization(priority));
  73680. // Next priority
  73681. priority++;
  73682. result.optimizations.push(new PostProcessesOptimization(priority));
  73683. result.optimizations.push(new ParticlesOptimization(priority));
  73684. // Next priority
  73685. priority++;
  73686. result.optimizations.push(new TextureOptimization(priority, 512));
  73687. // Next priority
  73688. priority++;
  73689. result.optimizations.push(new RenderTargetsOptimization(priority));
  73690. // Next priority
  73691. priority++;
  73692. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  73693. return result;
  73694. };
  73695. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  73696. var result = new SceneOptimizerOptions(targetFrameRate);
  73697. var priority = 0;
  73698. result.optimizations.push(new MergeMeshesOptimization(priority));
  73699. result.optimizations.push(new ShadowsOptimization(priority));
  73700. result.optimizations.push(new LensFlaresOptimization(priority));
  73701. // Next priority
  73702. priority++;
  73703. result.optimizations.push(new PostProcessesOptimization(priority));
  73704. result.optimizations.push(new ParticlesOptimization(priority));
  73705. // Next priority
  73706. priority++;
  73707. result.optimizations.push(new TextureOptimization(priority, 256));
  73708. // Next priority
  73709. priority++;
  73710. result.optimizations.push(new RenderTargetsOptimization(priority));
  73711. // Next priority
  73712. priority++;
  73713. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  73714. return result;
  73715. };
  73716. return SceneOptimizerOptions;
  73717. }());
  73718. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  73719. // Scene optimizer tool
  73720. var SceneOptimizer = /** @class */ (function () {
  73721. function SceneOptimizer() {
  73722. }
  73723. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  73724. // TODO: add an epsilon
  73725. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  73726. if (onSuccess) {
  73727. onSuccess();
  73728. }
  73729. return;
  73730. }
  73731. // Apply current level of optimizations
  73732. var allDone = true;
  73733. var noOptimizationApplied = true;
  73734. for (var index = 0; index < options.optimizations.length; index++) {
  73735. var optimization = options.optimizations[index];
  73736. if (optimization.priority === currentPriorityLevel) {
  73737. noOptimizationApplied = false;
  73738. allDone = allDone && optimization.apply(scene);
  73739. }
  73740. }
  73741. // If no optimization was applied, this is a failure :(
  73742. if (noOptimizationApplied) {
  73743. if (onFailure) {
  73744. onFailure();
  73745. }
  73746. return;
  73747. }
  73748. // If all optimizations were done, move to next level
  73749. if (allDone) {
  73750. currentPriorityLevel++;
  73751. }
  73752. // Let's the system running for a specific amount of time before checking FPS
  73753. scene.executeWhenReady(function () {
  73754. setTimeout(function () {
  73755. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  73756. }, options.trackerDuration);
  73757. });
  73758. };
  73759. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  73760. if (!options) {
  73761. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  73762. }
  73763. // Let's the system running for a specific amount of time before checking FPS
  73764. scene.executeWhenReady(function () {
  73765. setTimeout(function () {
  73766. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  73767. }, options.trackerDuration);
  73768. });
  73769. };
  73770. return SceneOptimizer;
  73771. }());
  73772. BABYLON.SceneOptimizer = SceneOptimizer;
  73773. })(BABYLON || (BABYLON = {}));
  73774. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  73775. var BABYLON;
  73776. (function (BABYLON) {
  73777. var OutlineRenderer = /** @class */ (function () {
  73778. function OutlineRenderer(scene) {
  73779. this.zOffset = 1;
  73780. this._scene = scene;
  73781. }
  73782. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  73783. var _this = this;
  73784. if (useOverlay === void 0) { useOverlay = false; }
  73785. var scene = this._scene;
  73786. var engine = this._scene.getEngine();
  73787. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  73788. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  73789. return;
  73790. }
  73791. var mesh = subMesh.getRenderingMesh();
  73792. var material = subMesh.getMaterial();
  73793. if (!material || !scene.activeCamera) {
  73794. return;
  73795. }
  73796. engine.enableEffect(this._effect);
  73797. // Logarithmic depth
  73798. if (material.useLogarithmicDepth) {
  73799. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  73800. }
  73801. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  73802. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  73803. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  73804. // Bones
  73805. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  73806. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  73807. }
  73808. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  73809. // Alpha test
  73810. if (material && material.needAlphaTesting()) {
  73811. var alphaTexture = material.getAlphaTestTexture();
  73812. if (alphaTexture) {
  73813. this._effect.setTexture("diffuseSampler", alphaTexture);
  73814. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  73815. }
  73816. }
  73817. engine.setZOffset(-this.zOffset);
  73818. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  73819. engine.setZOffset(0);
  73820. };
  73821. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  73822. var defines = [];
  73823. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  73824. var mesh = subMesh.getMesh();
  73825. var material = subMesh.getMaterial();
  73826. if (material) {
  73827. // Alpha test
  73828. if (material.needAlphaTesting()) {
  73829. defines.push("#define ALPHATEST");
  73830. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73831. attribs.push(BABYLON.VertexBuffer.UVKind);
  73832. defines.push("#define UV1");
  73833. }
  73834. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73835. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73836. defines.push("#define UV2");
  73837. }
  73838. }
  73839. //Logarithmic depth
  73840. if (material.useLogarithmicDepth) {
  73841. defines.push("#define LOGARITHMICDEPTH");
  73842. }
  73843. }
  73844. // Bones
  73845. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73846. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73847. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73848. if (mesh.numBoneInfluencers > 4) {
  73849. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73850. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73851. }
  73852. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73853. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73854. }
  73855. else {
  73856. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73857. }
  73858. // Instances
  73859. if (useInstances) {
  73860. defines.push("#define INSTANCES");
  73861. attribs.push("world0");
  73862. attribs.push("world1");
  73863. attribs.push("world2");
  73864. attribs.push("world3");
  73865. }
  73866. // Get correct effect
  73867. var join = defines.join("\n");
  73868. if (this._cachedDefines !== join) {
  73869. this._cachedDefines = join;
  73870. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  73871. }
  73872. return this._effect.isReady();
  73873. };
  73874. return OutlineRenderer;
  73875. }());
  73876. BABYLON.OutlineRenderer = OutlineRenderer;
  73877. })(BABYLON || (BABYLON = {}));
  73878. //# sourceMappingURL=babylon.outlineRenderer.js.map
  73879. var BABYLON;
  73880. (function (BABYLON) {
  73881. var FaceAdjacencies = /** @class */ (function () {
  73882. function FaceAdjacencies() {
  73883. this.edges = new Array();
  73884. this.edgesConnectedCount = 0;
  73885. }
  73886. return FaceAdjacencies;
  73887. }());
  73888. var EdgesRenderer = /** @class */ (function () {
  73889. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  73890. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  73891. if (epsilon === void 0) { epsilon = 0.95; }
  73892. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  73893. this.edgesWidthScalerForOrthographic = 1000.0;
  73894. this.edgesWidthScalerForPerspective = 50.0;
  73895. this._linesPositions = new Array();
  73896. this._linesNormals = new Array();
  73897. this._linesIndices = new Array();
  73898. this._buffers = {};
  73899. this._checkVerticesInsteadOfIndices = false;
  73900. this._source = source;
  73901. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  73902. this._epsilon = epsilon;
  73903. this._prepareRessources();
  73904. this._generateEdgesLines();
  73905. }
  73906. EdgesRenderer.prototype._prepareRessources = function () {
  73907. if (this._lineShader) {
  73908. return;
  73909. }
  73910. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  73911. attributes: ["position", "normal"],
  73912. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  73913. });
  73914. this._lineShader.disableDepthWrite = true;
  73915. this._lineShader.backFaceCulling = false;
  73916. };
  73917. EdgesRenderer.prototype._rebuild = function () {
  73918. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  73919. if (buffer) {
  73920. buffer._rebuild();
  73921. }
  73922. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  73923. if (buffer) {
  73924. buffer._rebuild();
  73925. }
  73926. var scene = this._source.getScene();
  73927. var engine = scene.getEngine();
  73928. this._ib = engine.createIndexBuffer(this._linesIndices);
  73929. };
  73930. EdgesRenderer.prototype.dispose = function () {
  73931. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  73932. if (buffer) {
  73933. buffer.dispose();
  73934. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  73935. }
  73936. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  73937. if (buffer) {
  73938. buffer.dispose();
  73939. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  73940. }
  73941. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  73942. this._lineShader.dispose();
  73943. };
  73944. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  73945. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  73946. return 0;
  73947. }
  73948. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  73949. return 1;
  73950. }
  73951. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  73952. return 2;
  73953. }
  73954. return -1;
  73955. };
  73956. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  73957. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  73958. return 0;
  73959. }
  73960. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  73961. return 1;
  73962. }
  73963. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  73964. return 2;
  73965. }
  73966. return -1;
  73967. };
  73968. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  73969. var needToCreateLine;
  73970. if (edge === undefined) {
  73971. needToCreateLine = true;
  73972. }
  73973. else {
  73974. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  73975. needToCreateLine = dotProduct < this._epsilon;
  73976. }
  73977. if (needToCreateLine) {
  73978. var offset = this._linesPositions.length / 3;
  73979. var normal = p0.subtract(p1);
  73980. normal.normalize();
  73981. // Positions
  73982. this._linesPositions.push(p0.x);
  73983. this._linesPositions.push(p0.y);
  73984. this._linesPositions.push(p0.z);
  73985. this._linesPositions.push(p0.x);
  73986. this._linesPositions.push(p0.y);
  73987. this._linesPositions.push(p0.z);
  73988. this._linesPositions.push(p1.x);
  73989. this._linesPositions.push(p1.y);
  73990. this._linesPositions.push(p1.z);
  73991. this._linesPositions.push(p1.x);
  73992. this._linesPositions.push(p1.y);
  73993. this._linesPositions.push(p1.z);
  73994. // Normals
  73995. this._linesNormals.push(p1.x);
  73996. this._linesNormals.push(p1.y);
  73997. this._linesNormals.push(p1.z);
  73998. this._linesNormals.push(-1);
  73999. this._linesNormals.push(p1.x);
  74000. this._linesNormals.push(p1.y);
  74001. this._linesNormals.push(p1.z);
  74002. this._linesNormals.push(1);
  74003. this._linesNormals.push(p0.x);
  74004. this._linesNormals.push(p0.y);
  74005. this._linesNormals.push(p0.z);
  74006. this._linesNormals.push(-1);
  74007. this._linesNormals.push(p0.x);
  74008. this._linesNormals.push(p0.y);
  74009. this._linesNormals.push(p0.z);
  74010. this._linesNormals.push(1);
  74011. // Indices
  74012. this._linesIndices.push(offset);
  74013. this._linesIndices.push(offset + 1);
  74014. this._linesIndices.push(offset + 2);
  74015. this._linesIndices.push(offset);
  74016. this._linesIndices.push(offset + 2);
  74017. this._linesIndices.push(offset + 3);
  74018. }
  74019. };
  74020. EdgesRenderer.prototype._generateEdgesLines = function () {
  74021. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  74022. var indices = this._source.getIndices();
  74023. if (!indices || !positions) {
  74024. return;
  74025. }
  74026. // First let's find adjacencies
  74027. var adjacencies = new Array();
  74028. var faceNormals = new Array();
  74029. var index;
  74030. var faceAdjacencies;
  74031. // Prepare faces
  74032. for (index = 0; index < indices.length; index += 3) {
  74033. faceAdjacencies = new FaceAdjacencies();
  74034. var p0Index = indices[index];
  74035. var p1Index = indices[index + 1];
  74036. var p2Index = indices[index + 2];
  74037. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  74038. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  74039. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  74040. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  74041. faceNormal.normalize();
  74042. faceNormals.push(faceNormal);
  74043. adjacencies.push(faceAdjacencies);
  74044. }
  74045. // Scan
  74046. for (index = 0; index < adjacencies.length; index++) {
  74047. faceAdjacencies = adjacencies[index];
  74048. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  74049. var otherFaceAdjacencies = adjacencies[otherIndex];
  74050. if (faceAdjacencies.edgesConnectedCount === 3) {
  74051. break;
  74052. }
  74053. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  74054. continue;
  74055. }
  74056. var otherP0 = indices[otherIndex * 3];
  74057. var otherP1 = indices[otherIndex * 3 + 1];
  74058. var otherP2 = indices[otherIndex * 3 + 2];
  74059. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  74060. var otherEdgeIndex = 0;
  74061. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  74062. continue;
  74063. }
  74064. switch (edgeIndex) {
  74065. case 0:
  74066. if (this._checkVerticesInsteadOfIndices) {
  74067. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  74068. }
  74069. else {
  74070. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  74071. }
  74072. break;
  74073. case 1:
  74074. if (this._checkVerticesInsteadOfIndices) {
  74075. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  74076. }
  74077. else {
  74078. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  74079. }
  74080. break;
  74081. case 2:
  74082. if (this._checkVerticesInsteadOfIndices) {
  74083. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  74084. }
  74085. else {
  74086. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  74087. }
  74088. break;
  74089. }
  74090. if (otherEdgeIndex === -1) {
  74091. continue;
  74092. }
  74093. faceAdjacencies.edges[edgeIndex] = otherIndex;
  74094. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  74095. faceAdjacencies.edgesConnectedCount++;
  74096. otherFaceAdjacencies.edgesConnectedCount++;
  74097. if (faceAdjacencies.edgesConnectedCount === 3) {
  74098. break;
  74099. }
  74100. }
  74101. }
  74102. }
  74103. // Create lines
  74104. for (index = 0; index < adjacencies.length; index++) {
  74105. // 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
  74106. var current = adjacencies[index];
  74107. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  74108. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  74109. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  74110. }
  74111. // Merge into a single mesh
  74112. var engine = this._source.getScene().getEngine();
  74113. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  74114. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  74115. this._ib = engine.createIndexBuffer(this._linesIndices);
  74116. this._indicesCount = this._linesIndices.length;
  74117. };
  74118. EdgesRenderer.prototype.render = function () {
  74119. var scene = this._source.getScene();
  74120. if (!this._lineShader.isReady() || !scene.activeCamera) {
  74121. return;
  74122. }
  74123. var engine = scene.getEngine();
  74124. this._lineShader._preBind();
  74125. // VBOs
  74126. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  74127. scene.resetCachedMaterial();
  74128. this._lineShader.setColor4("color", this._source.edgesColor);
  74129. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  74130. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  74131. }
  74132. else {
  74133. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  74134. }
  74135. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  74136. this._lineShader.bind(this._source.getWorldMatrix());
  74137. // Draw order
  74138. engine.draw(true, 0, this._indicesCount);
  74139. this._lineShader.unbind();
  74140. engine.setDepthWrite(true);
  74141. };
  74142. return EdgesRenderer;
  74143. }());
  74144. BABYLON.EdgesRenderer = EdgesRenderer;
  74145. })(BABYLON || (BABYLON = {}));
  74146. //# sourceMappingURL=babylon.edgesRenderer.js.map
  74147. var BABYLON;
  74148. (function (BABYLON) {
  74149. /**
  74150. * Special Glow Blur post process only blurring the alpha channel
  74151. * It enforces keeping the most luminous color in the color channel.
  74152. */
  74153. var GlowBlurPostProcess = /** @class */ (function (_super) {
  74154. __extends(GlowBlurPostProcess, _super);
  74155. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  74156. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74157. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  74158. _this.direction = direction;
  74159. _this.kernel = kernel;
  74160. _this.onApplyObservable.add(function (effect) {
  74161. effect.setFloat2("screenSize", _this.width, _this.height);
  74162. effect.setVector2("direction", _this.direction);
  74163. effect.setFloat("blurWidth", _this.kernel);
  74164. });
  74165. return _this;
  74166. }
  74167. return GlowBlurPostProcess;
  74168. }(BABYLON.PostProcess));
  74169. /**
  74170. * The highlight layer Helps adding a glow effect around a mesh.
  74171. *
  74172. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  74173. * glowy meshes to your scene.
  74174. *
  74175. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  74176. */
  74177. var HighlightLayer = /** @class */ (function () {
  74178. /**
  74179. * Instantiates a new highlight Layer and references it to the scene..
  74180. * @param name The name of the layer
  74181. * @param scene The scene to use the layer in
  74182. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  74183. */
  74184. function HighlightLayer(name, scene, options) {
  74185. this.name = name;
  74186. this._vertexBuffers = {};
  74187. this._mainTextureDesiredSize = { width: 0, height: 0 };
  74188. this._meshes = {};
  74189. this._maxSize = 0;
  74190. this._shouldRender = false;
  74191. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  74192. this._excludedMeshes = {};
  74193. /**
  74194. * Specifies whether or not the inner glow is ACTIVE in the layer.
  74195. */
  74196. this.innerGlow = true;
  74197. /**
  74198. * Specifies whether or not the outer glow is ACTIVE in the layer.
  74199. */
  74200. this.outerGlow = true;
  74201. /**
  74202. * Specifies wether the highlight layer is enabled or not.
  74203. */
  74204. this.isEnabled = true;
  74205. /**
  74206. * An event triggered when the highlight layer has been disposed.
  74207. * @type {BABYLON.Observable}
  74208. */
  74209. this.onDisposeObservable = new BABYLON.Observable();
  74210. /**
  74211. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  74212. * @type {BABYLON.Observable}
  74213. */
  74214. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  74215. /**
  74216. * An event triggered when the highlight layer is being blurred.
  74217. * @type {BABYLON.Observable}
  74218. */
  74219. this.onBeforeBlurObservable = new BABYLON.Observable();
  74220. /**
  74221. * An event triggered when the highlight layer has been blurred.
  74222. * @type {BABYLON.Observable}
  74223. */
  74224. this.onAfterBlurObservable = new BABYLON.Observable();
  74225. /**
  74226. * An event triggered when the glowing blurred texture is being merged in the scene.
  74227. * @type {BABYLON.Observable}
  74228. */
  74229. this.onBeforeComposeObservable = new BABYLON.Observable();
  74230. /**
  74231. * An event triggered when the glowing blurred texture has been merged in the scene.
  74232. * @type {BABYLON.Observable}
  74233. */
  74234. this.onAfterComposeObservable = new BABYLON.Observable();
  74235. /**
  74236. * An event triggered when the highlight layer changes its size.
  74237. * @type {BABYLON.Observable}
  74238. */
  74239. this.onSizeChangedObservable = new BABYLON.Observable();
  74240. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  74241. var engine = scene.getEngine();
  74242. this._engine = engine;
  74243. this._maxSize = this._engine.getCaps().maxTextureSize;
  74244. this._scene.highlightLayers.push(this);
  74245. // Warn on stencil.
  74246. if (!this._engine.isStencilEnable) {
  74247. 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 }");
  74248. }
  74249. // Adapt options
  74250. this._options = options || {
  74251. mainTextureRatio: 0.5,
  74252. blurTextureSizeRatio: 0.5,
  74253. blurHorizontalSize: 1.0,
  74254. blurVerticalSize: 1.0,
  74255. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  74256. camera: null
  74257. };
  74258. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  74259. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  74260. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  74261. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  74262. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  74263. // VBO
  74264. var vertices = [];
  74265. vertices.push(1, 1);
  74266. vertices.push(-1, 1);
  74267. vertices.push(-1, -1);
  74268. vertices.push(1, -1);
  74269. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  74270. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  74271. this._createIndexBuffer();
  74272. // Effect
  74273. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  74274. // Render target
  74275. this.setMainTextureSize();
  74276. // Create Textures and post processes
  74277. this.createTextureAndPostProcesses();
  74278. }
  74279. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  74280. /**
  74281. * Gets the horizontal size of the blur.
  74282. */
  74283. get: function () {
  74284. return this._horizontalBlurPostprocess.kernel;
  74285. },
  74286. /**
  74287. * Specifies the horizontal size of the blur.
  74288. */
  74289. set: function (value) {
  74290. this._horizontalBlurPostprocess.kernel = value;
  74291. },
  74292. enumerable: true,
  74293. configurable: true
  74294. });
  74295. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  74296. /**
  74297. * Gets the vertical size of the blur.
  74298. */
  74299. get: function () {
  74300. return this._verticalBlurPostprocess.kernel;
  74301. },
  74302. /**
  74303. * Specifies the vertical size of the blur.
  74304. */
  74305. set: function (value) {
  74306. this._verticalBlurPostprocess.kernel = value;
  74307. },
  74308. enumerable: true,
  74309. configurable: true
  74310. });
  74311. Object.defineProperty(HighlightLayer.prototype, "camera", {
  74312. /**
  74313. * Gets the camera attached to the layer.
  74314. */
  74315. get: function () {
  74316. return this._options.camera;
  74317. },
  74318. enumerable: true,
  74319. configurable: true
  74320. });
  74321. HighlightLayer.prototype._createIndexBuffer = function () {
  74322. var engine = this._scene.getEngine();
  74323. // Indices
  74324. var indices = [];
  74325. indices.push(0);
  74326. indices.push(1);
  74327. indices.push(2);
  74328. indices.push(0);
  74329. indices.push(2);
  74330. indices.push(3);
  74331. this._indexBuffer = engine.createIndexBuffer(indices);
  74332. };
  74333. HighlightLayer.prototype._rebuild = function () {
  74334. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74335. if (vb) {
  74336. vb._rebuild();
  74337. }
  74338. this._createIndexBuffer();
  74339. };
  74340. /**
  74341. * Creates the render target textures and post processes used in the highlight layer.
  74342. */
  74343. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  74344. var _this = this;
  74345. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  74346. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  74347. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  74348. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  74349. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  74350. width: this._mainTextureDesiredSize.width,
  74351. height: this._mainTextureDesiredSize.height
  74352. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74353. this._mainTexture.activeCamera = this._options.camera;
  74354. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74355. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74356. this._mainTexture.anisotropicFilteringLevel = 1;
  74357. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74358. this._mainTexture.renderParticles = false;
  74359. this._mainTexture.renderList = null;
  74360. this._mainTexture.ignoreCameraViewport = true;
  74361. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  74362. width: blurTextureWidth,
  74363. height: blurTextureHeight
  74364. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74365. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74366. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74367. this._blurTexture.anisotropicFilteringLevel = 16;
  74368. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  74369. this._blurTexture.renderParticles = false;
  74370. this._blurTexture.ignoreCameraViewport = true;
  74371. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  74372. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  74373. effect.setTexture("textureSampler", _this._mainTexture);
  74374. });
  74375. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  74376. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  74377. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  74378. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  74379. });
  74380. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  74381. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  74382. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  74383. });
  74384. }
  74385. else {
  74386. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  74387. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  74388. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  74389. });
  74390. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  74391. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  74392. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  74393. });
  74394. }
  74395. this._mainTexture.onAfterUnbindObservable.add(function () {
  74396. _this.onBeforeBlurObservable.notifyObservers(_this);
  74397. var internalTexture = _this._blurTexture.getInternalTexture();
  74398. if (internalTexture) {
  74399. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  74400. }
  74401. _this.onAfterBlurObservable.notifyObservers(_this);
  74402. });
  74403. // Custom render function
  74404. var renderSubMesh = function (subMesh) {
  74405. if (!_this._meshes) {
  74406. return;
  74407. }
  74408. var material = subMesh.getMaterial();
  74409. var mesh = subMesh.getRenderingMesh();
  74410. var scene = _this._scene;
  74411. var engine = scene.getEngine();
  74412. if (!material) {
  74413. return;
  74414. }
  74415. // Do not block in blend mode.
  74416. if (material.needAlphaBlendingForMesh(mesh)) {
  74417. return;
  74418. }
  74419. // Culling
  74420. engine.setState(material.backFaceCulling);
  74421. // Managing instances
  74422. var batch = mesh._getInstancesRenderList(subMesh._id);
  74423. if (batch.mustReturn) {
  74424. return;
  74425. }
  74426. // Excluded Mesh
  74427. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  74428. return;
  74429. }
  74430. ;
  74431. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  74432. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  74433. var emissiveTexture = null;
  74434. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  74435. emissiveTexture = material.emissiveTexture;
  74436. }
  74437. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  74438. engine.enableEffect(_this._glowMapGenerationEffect);
  74439. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  74440. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  74441. if (highlightLayerMesh) {
  74442. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  74443. }
  74444. else {
  74445. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  74446. }
  74447. // Alpha test
  74448. if (material && material.needAlphaTesting()) {
  74449. var alphaTexture = material.getAlphaTestTexture();
  74450. if (alphaTexture) {
  74451. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  74452. var textureMatrix = alphaTexture.getTextureMatrix();
  74453. if (textureMatrix) {
  74454. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  74455. }
  74456. }
  74457. }
  74458. // Glow emissive only
  74459. if (emissiveTexture) {
  74460. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  74461. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  74462. }
  74463. // Bones
  74464. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  74465. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  74466. }
  74467. // Draw
  74468. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  74469. }
  74470. else {
  74471. // Need to reset refresh rate of the shadowMap
  74472. _this._mainTexture.resetRefreshCounter();
  74473. }
  74474. };
  74475. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  74476. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  74477. var index;
  74478. var engine = _this._scene.getEngine();
  74479. if (depthOnlySubMeshes.length) {
  74480. engine.setColorWrite(false);
  74481. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  74482. renderSubMesh(depthOnlySubMeshes.data[index]);
  74483. }
  74484. engine.setColorWrite(true);
  74485. }
  74486. for (index = 0; index < opaqueSubMeshes.length; index++) {
  74487. renderSubMesh(opaqueSubMeshes.data[index]);
  74488. }
  74489. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  74490. renderSubMesh(alphaTestSubMeshes.data[index]);
  74491. }
  74492. for (index = 0; index < transparentSubMeshes.length; index++) {
  74493. renderSubMesh(transparentSubMeshes.data[index]);
  74494. }
  74495. };
  74496. this._mainTexture.onClearObservable.add(function (engine) {
  74497. engine.clear(HighlightLayer.neutralColor, true, true, true);
  74498. });
  74499. };
  74500. /**
  74501. * Checks for the readiness of the element composing the layer.
  74502. * @param subMesh the mesh to check for
  74503. * @param useInstances specify wether or not to use instances to render the mesh
  74504. * @param emissiveTexture the associated emissive texture used to generate the glow
  74505. * @return true if ready otherwise, false
  74506. */
  74507. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  74508. var material = subMesh.getMaterial();
  74509. if (!material) {
  74510. return false;
  74511. }
  74512. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  74513. return false;
  74514. }
  74515. var defines = [];
  74516. var attribs = [BABYLON.VertexBuffer.PositionKind];
  74517. var mesh = subMesh.getMesh();
  74518. var uv1 = false;
  74519. var uv2 = false;
  74520. // Alpha test
  74521. if (material && material.needAlphaTesting()) {
  74522. var alphaTexture = material.getAlphaTestTexture();
  74523. if (alphaTexture) {
  74524. defines.push("#define ALPHATEST");
  74525. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  74526. alphaTexture.coordinatesIndex === 1) {
  74527. defines.push("#define DIFFUSEUV2");
  74528. uv2 = true;
  74529. }
  74530. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  74531. defines.push("#define DIFFUSEUV1");
  74532. uv1 = true;
  74533. }
  74534. }
  74535. }
  74536. // Emissive
  74537. if (emissiveTexture) {
  74538. defines.push("#define EMISSIVE");
  74539. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  74540. emissiveTexture.coordinatesIndex === 1) {
  74541. defines.push("#define EMISSIVEUV2");
  74542. uv2 = true;
  74543. }
  74544. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  74545. defines.push("#define EMISSIVEUV1");
  74546. uv1 = true;
  74547. }
  74548. }
  74549. if (uv1) {
  74550. attribs.push(BABYLON.VertexBuffer.UVKind);
  74551. defines.push("#define UV1");
  74552. }
  74553. if (uv2) {
  74554. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  74555. defines.push("#define UV2");
  74556. }
  74557. // Bones
  74558. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  74559. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  74560. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  74561. if (mesh.numBoneInfluencers > 4) {
  74562. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  74563. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  74564. }
  74565. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  74566. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  74567. }
  74568. else {
  74569. defines.push("#define NUM_BONE_INFLUENCERS 0");
  74570. }
  74571. // Instances
  74572. if (useInstances) {
  74573. defines.push("#define INSTANCES");
  74574. attribs.push("world0");
  74575. attribs.push("world1");
  74576. attribs.push("world2");
  74577. attribs.push("world3");
  74578. }
  74579. // Get correct effect
  74580. var join = defines.join("\n");
  74581. if (this._cachedDefines !== join) {
  74582. this._cachedDefines = join;
  74583. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  74584. }
  74585. return this._glowMapGenerationEffect.isReady();
  74586. };
  74587. /**
  74588. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  74589. */
  74590. HighlightLayer.prototype.render = function () {
  74591. var currentEffect = this._glowMapMergeEffect;
  74592. // Check
  74593. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  74594. return;
  74595. var engine = this._scene.getEngine();
  74596. this.onBeforeComposeObservable.notifyObservers(this);
  74597. // Render
  74598. engine.enableEffect(currentEffect);
  74599. engine.setState(false);
  74600. // Cache
  74601. var previousStencilBuffer = engine.getStencilBuffer();
  74602. var previousStencilFunction = engine.getStencilFunction();
  74603. var previousStencilMask = engine.getStencilMask();
  74604. var previousStencilOperationPass = engine.getStencilOperationPass();
  74605. var previousStencilOperationFail = engine.getStencilOperationFail();
  74606. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  74607. var previousAlphaMode = engine.getAlphaMode();
  74608. // Texture
  74609. currentEffect.setTexture("textureSampler", this._blurTexture);
  74610. // VBOs
  74611. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  74612. // Stencil operations
  74613. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  74614. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  74615. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  74616. // Draw order
  74617. engine.setAlphaMode(this._options.alphaBlendingMode);
  74618. engine.setStencilMask(0x00);
  74619. engine.setStencilBuffer(true);
  74620. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  74621. if (this.outerGlow) {
  74622. currentEffect.setFloat("offset", 0);
  74623. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  74624. engine.draw(true, 0, 6);
  74625. }
  74626. if (this.innerGlow) {
  74627. currentEffect.setFloat("offset", 1);
  74628. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  74629. engine.draw(true, 0, 6);
  74630. }
  74631. // Restore Cache
  74632. engine.setStencilFunction(previousStencilFunction);
  74633. engine.setStencilMask(previousStencilMask);
  74634. engine.setAlphaMode(previousAlphaMode);
  74635. engine.setStencilBuffer(previousStencilBuffer);
  74636. engine.setStencilOperationPass(previousStencilOperationPass);
  74637. engine.setStencilOperationFail(previousStencilOperationFail);
  74638. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  74639. engine._stencilState.reset();
  74640. this.onAfterComposeObservable.notifyObservers(this);
  74641. // Handle size changes.
  74642. var size = this._mainTexture.getSize();
  74643. this.setMainTextureSize();
  74644. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  74645. // Recreate RTT and post processes on size change.
  74646. this.onSizeChangedObservable.notifyObservers(this);
  74647. this.disposeTextureAndPostProcesses();
  74648. this.createTextureAndPostProcesses();
  74649. }
  74650. };
  74651. /**
  74652. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  74653. * @param mesh The mesh to exclude from the highlight layer
  74654. */
  74655. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  74656. if (!this._excludedMeshes) {
  74657. return;
  74658. }
  74659. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  74660. if (!meshExcluded) {
  74661. this._excludedMeshes[mesh.uniqueId] = {
  74662. mesh: mesh,
  74663. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  74664. mesh.getEngine().setStencilBuffer(false);
  74665. }),
  74666. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  74667. mesh.getEngine().setStencilBuffer(true);
  74668. }),
  74669. };
  74670. }
  74671. };
  74672. /**
  74673. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  74674. * @param mesh The mesh to highlight
  74675. */
  74676. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  74677. if (!this._excludedMeshes) {
  74678. return;
  74679. }
  74680. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  74681. if (meshExcluded) {
  74682. if (meshExcluded.beforeRender) {
  74683. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  74684. }
  74685. if (meshExcluded.afterRender) {
  74686. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  74687. }
  74688. }
  74689. this._excludedMeshes[mesh.uniqueId] = null;
  74690. };
  74691. /**
  74692. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  74693. * @param mesh The mesh to highlight
  74694. * @param color The color of the highlight
  74695. * @param glowEmissiveOnly Extract the glow from the emissive texture
  74696. */
  74697. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  74698. var _this = this;
  74699. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  74700. if (!this._meshes) {
  74701. return;
  74702. }
  74703. var meshHighlight = this._meshes[mesh.uniqueId];
  74704. if (meshHighlight) {
  74705. meshHighlight.color = color;
  74706. }
  74707. else {
  74708. this._meshes[mesh.uniqueId] = {
  74709. mesh: mesh,
  74710. color: color,
  74711. // Lambda required for capture due to Observable this context
  74712. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  74713. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  74714. _this.defaultStencilReference(mesh);
  74715. }
  74716. else {
  74717. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  74718. }
  74719. }),
  74720. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  74721. glowEmissiveOnly: glowEmissiveOnly
  74722. };
  74723. }
  74724. this._shouldRender = true;
  74725. };
  74726. /**
  74727. * Remove a mesh from the highlight layer in order to make it stop glowing.
  74728. * @param mesh The mesh to highlight
  74729. */
  74730. HighlightLayer.prototype.removeMesh = function (mesh) {
  74731. if (!this._meshes) {
  74732. return;
  74733. }
  74734. var meshHighlight = this._meshes[mesh.uniqueId];
  74735. if (meshHighlight) {
  74736. if (meshHighlight.observerHighlight) {
  74737. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  74738. }
  74739. if (meshHighlight.observerDefault) {
  74740. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  74741. }
  74742. }
  74743. this._meshes[mesh.uniqueId] = null;
  74744. this._shouldRender = false;
  74745. for (var meshHighlightToCheck in this._meshes) {
  74746. if (this._meshes[meshHighlightToCheck]) {
  74747. this._shouldRender = true;
  74748. break;
  74749. }
  74750. }
  74751. };
  74752. /**
  74753. * Returns true if the layer contains information to display, otherwise false.
  74754. */
  74755. HighlightLayer.prototype.shouldRender = function () {
  74756. return this.isEnabled && this._shouldRender;
  74757. };
  74758. /**
  74759. * Sets the main texture desired size which is the closest power of two
  74760. * of the engine canvas size.
  74761. */
  74762. HighlightLayer.prototype.setMainTextureSize = function () {
  74763. if (this._options.mainTextureFixedSize) {
  74764. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  74765. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  74766. }
  74767. else {
  74768. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  74769. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  74770. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  74771. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  74772. }
  74773. };
  74774. /**
  74775. * Force the stencil to the normal expected value for none glowing parts
  74776. */
  74777. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  74778. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  74779. };
  74780. /**
  74781. * Dispose only the render target textures and post process.
  74782. */
  74783. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  74784. this._blurTexture.dispose();
  74785. this._mainTexture.dispose();
  74786. this._downSamplePostprocess.dispose();
  74787. this._horizontalBlurPostprocess.dispose();
  74788. this._verticalBlurPostprocess.dispose();
  74789. };
  74790. /**
  74791. * Dispose the highlight layer and free resources.
  74792. */
  74793. HighlightLayer.prototype.dispose = function () {
  74794. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74795. if (vertexBuffer) {
  74796. vertexBuffer.dispose();
  74797. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  74798. }
  74799. if (this._indexBuffer) {
  74800. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  74801. this._indexBuffer = null;
  74802. }
  74803. // Clean textures and post processes
  74804. this.disposeTextureAndPostProcesses();
  74805. if (this._meshes) {
  74806. // Clean mesh references
  74807. for (var id in this._meshes) {
  74808. var meshHighlight = this._meshes[id];
  74809. if (meshHighlight && meshHighlight.mesh) {
  74810. if (meshHighlight.observerHighlight) {
  74811. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  74812. }
  74813. if (meshHighlight.observerDefault) {
  74814. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  74815. }
  74816. }
  74817. }
  74818. this._meshes = null;
  74819. }
  74820. if (this._excludedMeshes) {
  74821. for (var id in this._excludedMeshes) {
  74822. var meshHighlight = this._excludedMeshes[id];
  74823. if (meshHighlight) {
  74824. if (meshHighlight.beforeRender) {
  74825. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  74826. }
  74827. if (meshHighlight.afterRender) {
  74828. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  74829. }
  74830. }
  74831. }
  74832. this._excludedMeshes = null;
  74833. }
  74834. // Remove from scene
  74835. var index = this._scene.highlightLayers.indexOf(this, 0);
  74836. if (index > -1) {
  74837. this._scene.highlightLayers.splice(index, 1);
  74838. }
  74839. // Callback
  74840. this.onDisposeObservable.notifyObservers(this);
  74841. this.onDisposeObservable.clear();
  74842. this.onBeforeRenderMainTextureObservable.clear();
  74843. this.onBeforeBlurObservable.clear();
  74844. this.onBeforeComposeObservable.clear();
  74845. this.onAfterComposeObservable.clear();
  74846. this.onSizeChangedObservable.clear();
  74847. };
  74848. /**
  74849. * The neutral color used during the preparation of the glow effect.
  74850. * This is black by default as the blend operation is a blend operation.
  74851. */
  74852. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  74853. /**
  74854. * Stencil value used for glowing meshes.
  74855. */
  74856. HighlightLayer.glowingMeshStencilReference = 0x02;
  74857. /**
  74858. * Stencil value used for the other meshes in the scene.
  74859. */
  74860. HighlightLayer.normalMeshStencilReference = 0x01;
  74861. return HighlightLayer;
  74862. }());
  74863. BABYLON.HighlightLayer = HighlightLayer;
  74864. })(BABYLON || (BABYLON = {}));
  74865. //# sourceMappingURL=babylon.highlightlayer.js.map
  74866. var BABYLON;
  74867. (function (BABYLON) {
  74868. var AssetTaskState;
  74869. (function (AssetTaskState) {
  74870. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  74871. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  74872. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  74873. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  74874. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  74875. var AbstractAssetTask = /** @class */ (function () {
  74876. function AbstractAssetTask(name) {
  74877. this.name = name;
  74878. this.isCompleted = false;
  74879. this.taskState = AssetTaskState.INIT;
  74880. }
  74881. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  74882. var _this = this;
  74883. this.taskState = AssetTaskState.RUNNING;
  74884. this.runTask(scene, function () {
  74885. _this.onDoneCallback(onSuccess, onError);
  74886. }, function (msg, exception) {
  74887. _this.onErrorCallback(onError, msg, exception);
  74888. });
  74889. };
  74890. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  74891. throw new Error("runTask is not implemented");
  74892. };
  74893. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  74894. this.taskState = AssetTaskState.ERROR;
  74895. this.errorObject = {
  74896. message: message,
  74897. exception: exception
  74898. };
  74899. if (this.onError) {
  74900. this.onError(this, message, exception);
  74901. }
  74902. onError();
  74903. };
  74904. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  74905. try {
  74906. this.taskState = AssetTaskState.DONE;
  74907. this.isCompleted = true;
  74908. if (this.onSuccess) {
  74909. this.onSuccess(this);
  74910. }
  74911. onSuccess();
  74912. }
  74913. catch (e) {
  74914. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  74915. }
  74916. };
  74917. return AbstractAssetTask;
  74918. }());
  74919. BABYLON.AbstractAssetTask = AbstractAssetTask;
  74920. var AssetsProgressEvent = /** @class */ (function () {
  74921. function AssetsProgressEvent(remainingCount, totalCount, task) {
  74922. this.remainingCount = remainingCount;
  74923. this.totalCount = totalCount;
  74924. this.task = task;
  74925. }
  74926. return AssetsProgressEvent;
  74927. }());
  74928. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  74929. var MeshAssetTask = /** @class */ (function (_super) {
  74930. __extends(MeshAssetTask, _super);
  74931. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  74932. var _this = _super.call(this, name) || this;
  74933. _this.name = name;
  74934. _this.meshesNames = meshesNames;
  74935. _this.rootUrl = rootUrl;
  74936. _this.sceneFilename = sceneFilename;
  74937. return _this;
  74938. }
  74939. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  74940. var _this = this;
  74941. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  74942. _this.loadedMeshes = meshes;
  74943. _this.loadedParticleSystems = particleSystems;
  74944. _this.loadedSkeletons = skeletons;
  74945. onSuccess();
  74946. }, null, function (scene, message, exception) {
  74947. onError(message, exception);
  74948. });
  74949. };
  74950. return MeshAssetTask;
  74951. }(AbstractAssetTask));
  74952. BABYLON.MeshAssetTask = MeshAssetTask;
  74953. var TextFileAssetTask = /** @class */ (function (_super) {
  74954. __extends(TextFileAssetTask, _super);
  74955. function TextFileAssetTask(name, url) {
  74956. var _this = _super.call(this, name) || this;
  74957. _this.name = name;
  74958. _this.url = url;
  74959. return _this;
  74960. }
  74961. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  74962. var _this = this;
  74963. BABYLON.Tools.LoadFile(this.url, function (data) {
  74964. _this.text = data;
  74965. onSuccess();
  74966. }, undefined, scene.database, false, function (request, exception) {
  74967. if (request) {
  74968. onError(request.status + " " + request.statusText, exception);
  74969. }
  74970. });
  74971. };
  74972. return TextFileAssetTask;
  74973. }(AbstractAssetTask));
  74974. BABYLON.TextFileAssetTask = TextFileAssetTask;
  74975. var BinaryFileAssetTask = /** @class */ (function (_super) {
  74976. __extends(BinaryFileAssetTask, _super);
  74977. function BinaryFileAssetTask(name, url) {
  74978. var _this = _super.call(this, name) || this;
  74979. _this.name = name;
  74980. _this.url = url;
  74981. return _this;
  74982. }
  74983. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  74984. var _this = this;
  74985. BABYLON.Tools.LoadFile(this.url, function (data) {
  74986. _this.data = data;
  74987. onSuccess();
  74988. }, undefined, scene.database, true, function (request, exception) {
  74989. if (request) {
  74990. onError(request.status + " " + request.statusText, exception);
  74991. }
  74992. });
  74993. };
  74994. return BinaryFileAssetTask;
  74995. }(AbstractAssetTask));
  74996. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  74997. var ImageAssetTask = /** @class */ (function (_super) {
  74998. __extends(ImageAssetTask, _super);
  74999. function ImageAssetTask(name, url) {
  75000. var _this = _super.call(this, name) || this;
  75001. _this.name = name;
  75002. _this.url = url;
  75003. return _this;
  75004. }
  75005. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  75006. var _this = this;
  75007. var img = new Image();
  75008. BABYLON.Tools.SetCorsBehavior(this.url, img);
  75009. img.onload = function () {
  75010. _this.image = img;
  75011. onSuccess();
  75012. };
  75013. img.onerror = function (err) {
  75014. onError("Error loading image", err);
  75015. };
  75016. img.src = this.url;
  75017. };
  75018. return ImageAssetTask;
  75019. }(AbstractAssetTask));
  75020. BABYLON.ImageAssetTask = ImageAssetTask;
  75021. var TextureAssetTask = /** @class */ (function (_super) {
  75022. __extends(TextureAssetTask, _super);
  75023. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  75024. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  75025. var _this = _super.call(this, name) || this;
  75026. _this.name = name;
  75027. _this.url = url;
  75028. _this.noMipmap = noMipmap;
  75029. _this.invertY = invertY;
  75030. _this.samplingMode = samplingMode;
  75031. return _this;
  75032. }
  75033. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  75034. var onload = function () {
  75035. onSuccess();
  75036. };
  75037. var onerror = function (message, exception) {
  75038. onError(message, exception);
  75039. };
  75040. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  75041. };
  75042. return TextureAssetTask;
  75043. }(AbstractAssetTask));
  75044. BABYLON.TextureAssetTask = TextureAssetTask;
  75045. var CubeTextureAssetTask = /** @class */ (function (_super) {
  75046. __extends(CubeTextureAssetTask, _super);
  75047. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  75048. var _this = _super.call(this, name) || this;
  75049. _this.name = name;
  75050. _this.url = url;
  75051. _this.extensions = extensions;
  75052. _this.noMipmap = noMipmap;
  75053. _this.files = files;
  75054. return _this;
  75055. }
  75056. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  75057. var onload = function () {
  75058. onSuccess();
  75059. };
  75060. var onerror = function (message, exception) {
  75061. onError(message, exception);
  75062. };
  75063. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  75064. };
  75065. return CubeTextureAssetTask;
  75066. }(AbstractAssetTask));
  75067. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  75068. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  75069. __extends(HDRCubeTextureAssetTask, _super);
  75070. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  75071. if (noMipmap === void 0) { noMipmap = false; }
  75072. if (generateHarmonics === void 0) { generateHarmonics = true; }
  75073. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  75074. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  75075. var _this = _super.call(this, name) || this;
  75076. _this.name = name;
  75077. _this.url = url;
  75078. _this.size = size;
  75079. _this.noMipmap = noMipmap;
  75080. _this.generateHarmonics = generateHarmonics;
  75081. _this.useInGammaSpace = useInGammaSpace;
  75082. _this.usePMREMGenerator = usePMREMGenerator;
  75083. return _this;
  75084. }
  75085. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  75086. var onload = function () {
  75087. onSuccess();
  75088. };
  75089. var onerror = function (message, exception) {
  75090. onError(message, exception);
  75091. };
  75092. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  75093. };
  75094. return HDRCubeTextureAssetTask;
  75095. }(AbstractAssetTask));
  75096. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  75097. var AssetsManager = /** @class */ (function () {
  75098. function AssetsManager(scene) {
  75099. this.tasks = new Array();
  75100. this.waitingTasksCount = 0;
  75101. //Observables
  75102. this.onTaskSuccessObservable = new BABYLON.Observable();
  75103. this.onTaskErrorObservable = new BABYLON.Observable();
  75104. this.onTasksDoneObservable = new BABYLON.Observable();
  75105. this.onProgressObservable = new BABYLON.Observable();
  75106. this.useDefaultLoadingScreen = true;
  75107. this._scene = scene;
  75108. }
  75109. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  75110. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  75111. this.tasks.push(task);
  75112. return task;
  75113. };
  75114. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  75115. var task = new TextFileAssetTask(taskName, url);
  75116. this.tasks.push(task);
  75117. return task;
  75118. };
  75119. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  75120. var task = new BinaryFileAssetTask(taskName, url);
  75121. this.tasks.push(task);
  75122. return task;
  75123. };
  75124. AssetsManager.prototype.addImageTask = function (taskName, url) {
  75125. var task = new ImageAssetTask(taskName, url);
  75126. this.tasks.push(task);
  75127. return task;
  75128. };
  75129. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  75130. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  75131. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  75132. this.tasks.push(task);
  75133. return task;
  75134. };
  75135. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  75136. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  75137. this.tasks.push(task);
  75138. return task;
  75139. };
  75140. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  75141. if (noMipmap === void 0) { noMipmap = false; }
  75142. if (generateHarmonics === void 0) { generateHarmonics = true; }
  75143. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  75144. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  75145. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  75146. this.tasks.push(task);
  75147. return task;
  75148. };
  75149. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  75150. this.waitingTasksCount--;
  75151. try {
  75152. if (this.onProgress) {
  75153. this.onProgress(this.waitingTasksCount, this.tasks.length, task);
  75154. }
  75155. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this.waitingTasksCount, this.tasks.length, task));
  75156. }
  75157. catch (e) {
  75158. BABYLON.Tools.Error("Error running progress callbacks.");
  75159. console.log(e);
  75160. }
  75161. if (this.waitingTasksCount === 0) {
  75162. try {
  75163. if (this.onFinish) {
  75164. this.onFinish(this.tasks);
  75165. }
  75166. this.onTasksDoneObservable.notifyObservers(this.tasks);
  75167. }
  75168. catch (e) {
  75169. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  75170. console.log(e);
  75171. }
  75172. this._scene.getEngine().hideLoadingUI();
  75173. }
  75174. };
  75175. AssetsManager.prototype._runTask = function (task) {
  75176. var _this = this;
  75177. var done = function () {
  75178. try {
  75179. if (_this.onTaskSuccess) {
  75180. _this.onTaskSuccess(task);
  75181. }
  75182. _this.onTaskSuccessObservable.notifyObservers(task);
  75183. _this._decreaseWaitingTasksCount(task);
  75184. }
  75185. catch (e) {
  75186. error("Error executing task success callbacks", e);
  75187. }
  75188. };
  75189. var error = function (message, exception) {
  75190. task.errorObject = task.errorObject || {
  75191. message: message,
  75192. exception: exception
  75193. };
  75194. if (_this.onTaskError) {
  75195. _this.onTaskError(task);
  75196. }
  75197. _this.onTaskErrorObservable.notifyObservers(task);
  75198. _this._decreaseWaitingTasksCount(task);
  75199. };
  75200. task.run(this._scene, done, error);
  75201. };
  75202. AssetsManager.prototype.reset = function () {
  75203. this.tasks = new Array();
  75204. return this;
  75205. };
  75206. AssetsManager.prototype.load = function () {
  75207. this.waitingTasksCount = this.tasks.length;
  75208. if (this.waitingTasksCount === 0) {
  75209. if (this.onFinish) {
  75210. this.onFinish(this.tasks);
  75211. }
  75212. this.onTasksDoneObservable.notifyObservers(this.tasks);
  75213. return this;
  75214. }
  75215. if (this.useDefaultLoadingScreen) {
  75216. this._scene.getEngine().displayLoadingUI();
  75217. }
  75218. for (var index = 0; index < this.tasks.length; index++) {
  75219. var task = this.tasks[index];
  75220. this._runTask(task);
  75221. }
  75222. return this;
  75223. };
  75224. return AssetsManager;
  75225. }());
  75226. BABYLON.AssetsManager = AssetsManager;
  75227. })(BABYLON || (BABYLON = {}));
  75228. //# sourceMappingURL=babylon.assetsManager.js.map
  75229. var BABYLON;
  75230. (function (BABYLON) {
  75231. var serializedGeometries = [];
  75232. var serializeGeometry = function (geometry, serializationGeometries) {
  75233. if (serializedGeometries[geometry.id]) {
  75234. return;
  75235. }
  75236. if (geometry.doNotSerialize) {
  75237. return;
  75238. }
  75239. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  75240. serializationGeometries.boxes.push(geometry.serialize());
  75241. }
  75242. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  75243. serializationGeometries.spheres.push(geometry.serialize());
  75244. }
  75245. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  75246. serializationGeometries.cylinders.push(geometry.serialize());
  75247. }
  75248. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  75249. serializationGeometries.toruses.push(geometry.serialize());
  75250. }
  75251. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  75252. serializationGeometries.grounds.push(geometry.serialize());
  75253. }
  75254. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  75255. serializationGeometries.planes.push(geometry.serialize());
  75256. }
  75257. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  75258. serializationGeometries.torusKnots.push(geometry.serialize());
  75259. }
  75260. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  75261. throw new Error("Unknown primitive type");
  75262. }
  75263. else {
  75264. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  75265. }
  75266. serializedGeometries[geometry.id] = true;
  75267. };
  75268. var serializeMesh = function (mesh, serializationScene) {
  75269. var serializationObject = {};
  75270. // Geometry
  75271. var geometry = mesh._geometry;
  75272. if (geometry) {
  75273. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  75274. // 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
  75275. serializeGeometry(geometry, serializationScene.geometries);
  75276. }
  75277. }
  75278. // Custom
  75279. if (mesh.serialize) {
  75280. mesh.serialize(serializationObject);
  75281. }
  75282. return serializationObject;
  75283. };
  75284. var finalizeSingleMesh = function (mesh, serializationObject) {
  75285. //only works if the mesh is already loaded
  75286. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  75287. //serialize material
  75288. if (mesh.material) {
  75289. if (mesh.material instanceof BABYLON.StandardMaterial) {
  75290. serializationObject.materials = serializationObject.materials || [];
  75291. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  75292. serializationObject.materials.push(mesh.material.serialize());
  75293. }
  75294. }
  75295. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  75296. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  75297. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  75298. serializationObject.multiMaterials.push(mesh.material.serialize());
  75299. }
  75300. }
  75301. }
  75302. //serialize geometry
  75303. var geometry = mesh._geometry;
  75304. if (geometry) {
  75305. if (!serializationObject.geometries) {
  75306. serializationObject.geometries = {};
  75307. serializationObject.geometries.boxes = [];
  75308. serializationObject.geometries.spheres = [];
  75309. serializationObject.geometries.cylinders = [];
  75310. serializationObject.geometries.toruses = [];
  75311. serializationObject.geometries.grounds = [];
  75312. serializationObject.geometries.planes = [];
  75313. serializationObject.geometries.torusKnots = [];
  75314. serializationObject.geometries.vertexData = [];
  75315. }
  75316. serializeGeometry(geometry, serializationObject.geometries);
  75317. }
  75318. // Skeletons
  75319. if (mesh.skeleton) {
  75320. serializationObject.skeletons = serializationObject.skeletons || [];
  75321. serializationObject.skeletons.push(mesh.skeleton.serialize());
  75322. }
  75323. //serialize the actual mesh
  75324. serializationObject.meshes = serializationObject.meshes || [];
  75325. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  75326. }
  75327. };
  75328. var SceneSerializer = /** @class */ (function () {
  75329. function SceneSerializer() {
  75330. }
  75331. SceneSerializer.ClearCache = function () {
  75332. serializedGeometries = [];
  75333. };
  75334. SceneSerializer.Serialize = function (scene) {
  75335. var serializationObject = {};
  75336. SceneSerializer.ClearCache();
  75337. // Scene
  75338. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  75339. serializationObject.autoClear = scene.autoClear;
  75340. serializationObject.clearColor = scene.clearColor.asArray();
  75341. serializationObject.ambientColor = scene.ambientColor.asArray();
  75342. serializationObject.gravity = scene.gravity.asArray();
  75343. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  75344. serializationObject.workerCollisions = scene.workerCollisions;
  75345. // Fog
  75346. if (scene.fogMode && scene.fogMode !== 0) {
  75347. serializationObject.fogMode = scene.fogMode;
  75348. serializationObject.fogColor = scene.fogColor.asArray();
  75349. serializationObject.fogStart = scene.fogStart;
  75350. serializationObject.fogEnd = scene.fogEnd;
  75351. serializationObject.fogDensity = scene.fogDensity;
  75352. }
  75353. //Physics
  75354. if (scene.isPhysicsEnabled()) {
  75355. var physicEngine = scene.getPhysicsEngine();
  75356. if (physicEngine) {
  75357. serializationObject.physicsEnabled = true;
  75358. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  75359. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  75360. }
  75361. }
  75362. // Metadata
  75363. if (scene.metadata) {
  75364. serializationObject.metadata = scene.metadata;
  75365. }
  75366. // Morph targets
  75367. serializationObject.morphTargetManagers = [];
  75368. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  75369. var abstractMesh = _a[_i];
  75370. var manager = abstractMesh.morphTargetManager;
  75371. if (manager) {
  75372. serializationObject.morphTargetManagers.push(manager.serialize());
  75373. }
  75374. }
  75375. // Lights
  75376. serializationObject.lights = [];
  75377. var index;
  75378. var light;
  75379. for (index = 0; index < scene.lights.length; index++) {
  75380. light = scene.lights[index];
  75381. if (!light.doNotSerialize) {
  75382. serializationObject.lights.push(light.serialize());
  75383. }
  75384. }
  75385. // Cameras
  75386. serializationObject.cameras = [];
  75387. for (index = 0; index < scene.cameras.length; index++) {
  75388. var camera = scene.cameras[index];
  75389. if (!camera.doNotSerialize) {
  75390. serializationObject.cameras.push(camera.serialize());
  75391. }
  75392. }
  75393. if (scene.activeCamera) {
  75394. serializationObject.activeCameraID = scene.activeCamera.id;
  75395. }
  75396. // Animations
  75397. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  75398. // Materials
  75399. serializationObject.materials = [];
  75400. serializationObject.multiMaterials = [];
  75401. var material;
  75402. for (index = 0; index < scene.materials.length; index++) {
  75403. material = scene.materials[index];
  75404. if (!material.doNotSerialize) {
  75405. serializationObject.materials.push(material.serialize());
  75406. }
  75407. }
  75408. // MultiMaterials
  75409. serializationObject.multiMaterials = [];
  75410. for (index = 0; index < scene.multiMaterials.length; index++) {
  75411. var multiMaterial = scene.multiMaterials[index];
  75412. serializationObject.multiMaterials.push(multiMaterial.serialize());
  75413. }
  75414. // Skeletons
  75415. serializationObject.skeletons = [];
  75416. for (index = 0; index < scene.skeletons.length; index++) {
  75417. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  75418. }
  75419. // Transform nodes
  75420. serializationObject.transformNodes = [];
  75421. for (index = 0; index < scene.transformNodes.length; index++) {
  75422. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  75423. }
  75424. // Geometries
  75425. serializationObject.geometries = {};
  75426. serializationObject.geometries.boxes = [];
  75427. serializationObject.geometries.spheres = [];
  75428. serializationObject.geometries.cylinders = [];
  75429. serializationObject.geometries.toruses = [];
  75430. serializationObject.geometries.grounds = [];
  75431. serializationObject.geometries.planes = [];
  75432. serializationObject.geometries.torusKnots = [];
  75433. serializationObject.geometries.vertexData = [];
  75434. serializedGeometries = [];
  75435. var geometries = scene.getGeometries();
  75436. for (index = 0; index < geometries.length; index++) {
  75437. var geometry = geometries[index];
  75438. if (geometry.isReady()) {
  75439. serializeGeometry(geometry, serializationObject.geometries);
  75440. }
  75441. }
  75442. // Meshes
  75443. serializationObject.meshes = [];
  75444. for (index = 0; index < scene.meshes.length; index++) {
  75445. var abstractMesh = scene.meshes[index];
  75446. if (abstractMesh instanceof BABYLON.Mesh) {
  75447. var mesh = abstractMesh;
  75448. if (!mesh.doNotSerialize) {
  75449. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  75450. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  75451. }
  75452. }
  75453. }
  75454. }
  75455. // Particles Systems
  75456. serializationObject.particleSystems = [];
  75457. for (index = 0; index < scene.particleSystems.length; index++) {
  75458. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  75459. }
  75460. // Lens flares
  75461. serializationObject.lensFlareSystems = [];
  75462. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  75463. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  75464. }
  75465. // Shadows
  75466. serializationObject.shadowGenerators = [];
  75467. for (index = 0; index < scene.lights.length; index++) {
  75468. light = scene.lights[index];
  75469. var shadowGenerator = light.getShadowGenerator();
  75470. if (shadowGenerator) {
  75471. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  75472. }
  75473. }
  75474. // Action Manager
  75475. if (scene.actionManager) {
  75476. serializationObject.actions = scene.actionManager.serialize("scene");
  75477. }
  75478. // Audio
  75479. serializationObject.sounds = [];
  75480. for (index = 0; index < scene.soundTracks.length; index++) {
  75481. var soundtrack = scene.soundTracks[index];
  75482. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  75483. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  75484. }
  75485. }
  75486. return serializationObject;
  75487. };
  75488. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  75489. if (withParents === void 0) { withParents = false; }
  75490. if (withChildren === void 0) { withChildren = false; }
  75491. var serializationObject = {};
  75492. SceneSerializer.ClearCache();
  75493. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  75494. if (withParents || withChildren) {
  75495. //deliberate for loop! not for each, appended should be processed as well.
  75496. for (var i = 0; i < toSerialize.length; ++i) {
  75497. if (withChildren) {
  75498. toSerialize[i].getDescendants().forEach(function (node) {
  75499. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  75500. toSerialize.push(node);
  75501. }
  75502. });
  75503. }
  75504. //make sure the array doesn't contain the object already
  75505. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  75506. toSerialize.push(toSerialize[i].parent);
  75507. }
  75508. }
  75509. }
  75510. toSerialize.forEach(function (mesh) {
  75511. finalizeSingleMesh(mesh, serializationObject);
  75512. });
  75513. return serializationObject;
  75514. };
  75515. return SceneSerializer;
  75516. }());
  75517. BABYLON.SceneSerializer = SceneSerializer;
  75518. })(BABYLON || (BABYLON = {}));
  75519. //# sourceMappingURL=babylon.sceneSerializer.js.map
  75520. var BABYLON;
  75521. (function (BABYLON) {
  75522. var ReflectionProbe = /** @class */ (function () {
  75523. function ReflectionProbe(name, size, scene, generateMipMaps) {
  75524. if (generateMipMaps === void 0) { generateMipMaps = true; }
  75525. var _this = this;
  75526. this.name = name;
  75527. this._viewMatrix = BABYLON.Matrix.Identity();
  75528. this._target = BABYLON.Vector3.Zero();
  75529. this._add = BABYLON.Vector3.Zero();
  75530. this.invertYAxis = false;
  75531. this.position = BABYLON.Vector3.Zero();
  75532. this._scene = scene;
  75533. this._scene.reflectionProbes.push(this);
  75534. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  75535. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  75536. switch (faceIndex) {
  75537. case 0:
  75538. _this._add.copyFromFloats(1, 0, 0);
  75539. break;
  75540. case 1:
  75541. _this._add.copyFromFloats(-1, 0, 0);
  75542. break;
  75543. case 2:
  75544. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  75545. break;
  75546. case 3:
  75547. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  75548. break;
  75549. case 4:
  75550. _this._add.copyFromFloats(0, 0, 1);
  75551. break;
  75552. case 5:
  75553. _this._add.copyFromFloats(0, 0, -1);
  75554. break;
  75555. }
  75556. if (_this._attachedMesh) {
  75557. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  75558. }
  75559. _this.position.addToRef(_this._add, _this._target);
  75560. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  75561. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  75562. scene._forcedViewPosition = _this.position;
  75563. });
  75564. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  75565. scene._forcedViewPosition = null;
  75566. scene.updateTransformMatrix(true);
  75567. });
  75568. if (scene.activeCamera) {
  75569. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75570. }
  75571. }
  75572. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  75573. get: function () {
  75574. return this._renderTargetTexture.samples;
  75575. },
  75576. set: function (value) {
  75577. this._renderTargetTexture.samples = value;
  75578. },
  75579. enumerable: true,
  75580. configurable: true
  75581. });
  75582. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  75583. get: function () {
  75584. return this._renderTargetTexture.refreshRate;
  75585. },
  75586. set: function (value) {
  75587. this._renderTargetTexture.refreshRate = value;
  75588. },
  75589. enumerable: true,
  75590. configurable: true
  75591. });
  75592. ReflectionProbe.prototype.getScene = function () {
  75593. return this._scene;
  75594. };
  75595. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  75596. get: function () {
  75597. return this._renderTargetTexture;
  75598. },
  75599. enumerable: true,
  75600. configurable: true
  75601. });
  75602. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  75603. get: function () {
  75604. return this._renderTargetTexture.renderList;
  75605. },
  75606. enumerable: true,
  75607. configurable: true
  75608. });
  75609. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  75610. this._attachedMesh = mesh;
  75611. };
  75612. /**
  75613. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  75614. *
  75615. * @param renderingGroupId The rendering group id corresponding to its index
  75616. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  75617. */
  75618. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  75619. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  75620. };
  75621. ReflectionProbe.prototype.dispose = function () {
  75622. var index = this._scene.reflectionProbes.indexOf(this);
  75623. if (index !== -1) {
  75624. // Remove from the scene if found
  75625. this._scene.reflectionProbes.splice(index, 1);
  75626. }
  75627. if (this._renderTargetTexture) {
  75628. this._renderTargetTexture.dispose();
  75629. this._renderTargetTexture = null;
  75630. }
  75631. };
  75632. return ReflectionProbe;
  75633. }());
  75634. BABYLON.ReflectionProbe = ReflectionProbe;
  75635. })(BABYLON || (BABYLON = {}));
  75636. //# sourceMappingURL=babylon.reflectionProbe.js.map
  75637. var BABYLON;
  75638. (function (BABYLON) {
  75639. var Layer = /** @class */ (function () {
  75640. function Layer(name, imgUrl, scene, isBackground, color) {
  75641. this.name = name;
  75642. this.scale = new BABYLON.Vector2(1, 1);
  75643. this.offset = new BABYLON.Vector2(0, 0);
  75644. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  75645. this.layerMask = 0x0FFFFFFF;
  75646. this._vertexBuffers = {};
  75647. // Events
  75648. /**
  75649. * An event triggered when the layer is disposed.
  75650. * @type {BABYLON.Observable}
  75651. */
  75652. this.onDisposeObservable = new BABYLON.Observable();
  75653. /**
  75654. * An event triggered before rendering the scene
  75655. * @type {BABYLON.Observable}
  75656. */
  75657. this.onBeforeRenderObservable = new BABYLON.Observable();
  75658. /**
  75659. * An event triggered after rendering the scene
  75660. * @type {BABYLON.Observable}
  75661. */
  75662. this.onAfterRenderObservable = new BABYLON.Observable();
  75663. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  75664. this.isBackground = isBackground === undefined ? true : isBackground;
  75665. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  75666. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  75667. this._scene.layers.push(this);
  75668. var engine = this._scene.getEngine();
  75669. // VBO
  75670. var vertices = [];
  75671. vertices.push(1, 1);
  75672. vertices.push(-1, 1);
  75673. vertices.push(-1, -1);
  75674. vertices.push(1, -1);
  75675. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  75676. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  75677. this._createIndexBuffer();
  75678. // Effects
  75679. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  75680. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  75681. }
  75682. Object.defineProperty(Layer.prototype, "onDispose", {
  75683. set: function (callback) {
  75684. if (this._onDisposeObserver) {
  75685. this.onDisposeObservable.remove(this._onDisposeObserver);
  75686. }
  75687. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  75688. },
  75689. enumerable: true,
  75690. configurable: true
  75691. });
  75692. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  75693. set: function (callback) {
  75694. if (this._onBeforeRenderObserver) {
  75695. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  75696. }
  75697. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  75698. },
  75699. enumerable: true,
  75700. configurable: true
  75701. });
  75702. Object.defineProperty(Layer.prototype, "onAfterRender", {
  75703. set: function (callback) {
  75704. if (this._onAfterRenderObserver) {
  75705. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  75706. }
  75707. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  75708. },
  75709. enumerable: true,
  75710. configurable: true
  75711. });
  75712. Layer.prototype._createIndexBuffer = function () {
  75713. var engine = this._scene.getEngine();
  75714. // Indices
  75715. var indices = [];
  75716. indices.push(0);
  75717. indices.push(1);
  75718. indices.push(2);
  75719. indices.push(0);
  75720. indices.push(2);
  75721. indices.push(3);
  75722. this._indexBuffer = engine.createIndexBuffer(indices);
  75723. };
  75724. Layer.prototype._rebuild = function () {
  75725. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75726. if (vb) {
  75727. vb._rebuild();
  75728. }
  75729. this._createIndexBuffer();
  75730. };
  75731. Layer.prototype.render = function () {
  75732. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  75733. // Check
  75734. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  75735. return;
  75736. var engine = this._scene.getEngine();
  75737. this.onBeforeRenderObservable.notifyObservers(this);
  75738. // Render
  75739. engine.enableEffect(currentEffect);
  75740. engine.setState(false);
  75741. // Texture
  75742. currentEffect.setTexture("textureSampler", this.texture);
  75743. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  75744. // Color
  75745. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  75746. // Scale / offset
  75747. currentEffect.setVector2("offset", this.offset);
  75748. currentEffect.setVector2("scale", this.scale);
  75749. // VBOs
  75750. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  75751. // Draw order
  75752. if (!this.alphaTest) {
  75753. engine.setAlphaMode(this.alphaBlendingMode);
  75754. engine.draw(true, 0, 6);
  75755. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  75756. }
  75757. else {
  75758. engine.draw(true, 0, 6);
  75759. }
  75760. this.onAfterRenderObservable.notifyObservers(this);
  75761. };
  75762. Layer.prototype.dispose = function () {
  75763. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75764. if (vertexBuffer) {
  75765. vertexBuffer.dispose();
  75766. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  75767. }
  75768. if (this._indexBuffer) {
  75769. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  75770. this._indexBuffer = null;
  75771. }
  75772. if (this.texture) {
  75773. this.texture.dispose();
  75774. this.texture = null;
  75775. }
  75776. // Remove from scene
  75777. var index = this._scene.layers.indexOf(this);
  75778. this._scene.layers.splice(index, 1);
  75779. // Callback
  75780. this.onDisposeObservable.notifyObservers(this);
  75781. this.onDisposeObservable.clear();
  75782. this.onAfterRenderObservable.clear();
  75783. this.onBeforeRenderObservable.clear();
  75784. };
  75785. return Layer;
  75786. }());
  75787. BABYLON.Layer = Layer;
  75788. })(BABYLON || (BABYLON = {}));
  75789. //# sourceMappingURL=babylon.layer.js.map
  75790. var BABYLON;
  75791. (function (BABYLON) {
  75792. var TextureTools = /** @class */ (function () {
  75793. function TextureTools() {
  75794. }
  75795. /**
  75796. * Uses the GPU to create a copy texture rescaled at a given size
  75797. * @param texture Texture to copy from
  75798. * @param width Desired width
  75799. * @param height Desired height
  75800. * @return Generated texture
  75801. */
  75802. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  75803. if (useBilinearMode === void 0) { useBilinearMode = true; }
  75804. var scene = texture.getScene();
  75805. var engine = scene.getEngine();
  75806. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  75807. rtt.wrapU = texture.wrapU;
  75808. rtt.wrapV = texture.wrapV;
  75809. rtt.uOffset = texture.uOffset;
  75810. rtt.vOffset = texture.vOffset;
  75811. rtt.uScale = texture.uScale;
  75812. rtt.vScale = texture.vScale;
  75813. rtt.uAng = texture.uAng;
  75814. rtt.vAng = texture.vAng;
  75815. rtt.wAng = texture.wAng;
  75816. rtt.coordinatesIndex = texture.coordinatesIndex;
  75817. rtt.level = texture.level;
  75818. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  75819. rtt._texture.isReady = false;
  75820. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75821. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75822. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  75823. passPostProcess.getEffect().executeWhenCompiled(function () {
  75824. passPostProcess.onApply = function (effect) {
  75825. effect.setTexture("textureSampler", texture);
  75826. };
  75827. var internalTexture = rtt.getInternalTexture();
  75828. if (internalTexture) {
  75829. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  75830. engine.unBindFramebuffer(internalTexture);
  75831. rtt.disposeFramebufferObjects();
  75832. passPostProcess.dispose();
  75833. internalTexture.isReady = true;
  75834. }
  75835. });
  75836. return rtt;
  75837. };
  75838. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  75839. if (!scene._environmentBRDFTexture) {
  75840. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  75841. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75842. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75843. scene._environmentBRDFTexture = texture;
  75844. }
  75845. return scene._environmentBRDFTexture;
  75846. };
  75847. 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=";
  75848. return TextureTools;
  75849. }());
  75850. BABYLON.TextureTools = TextureTools;
  75851. })(BABYLON || (BABYLON = {}));
  75852. //# sourceMappingURL=babylon.textureTools.js.map
  75853. var BABYLON;
  75854. (function (BABYLON) {
  75855. var FramingBehavior = /** @class */ (function () {
  75856. function FramingBehavior() {
  75857. this._mode = FramingBehavior.FitFrustumSidesMode;
  75858. this._radiusScale = 1.0;
  75859. this._positionScale = 0.5;
  75860. this._defaultElevation = 0.3;
  75861. this._elevationReturnTime = 1500;
  75862. this._elevationReturnWaitTime = 1000;
  75863. this._zoomStopsAnimation = false;
  75864. this._framingTime = 1500;
  75865. this._isPointerDown = false;
  75866. this._lastInteractionTime = -Infinity;
  75867. // Framing control
  75868. this._animatables = new Array();
  75869. this._betaIsAnimating = false;
  75870. }
  75871. Object.defineProperty(FramingBehavior.prototype, "name", {
  75872. get: function () {
  75873. return "Framing";
  75874. },
  75875. enumerable: true,
  75876. configurable: true
  75877. });
  75878. Object.defineProperty(FramingBehavior.prototype, "mode", {
  75879. /**
  75880. * Gets current mode used by the behavior.
  75881. */
  75882. get: function () {
  75883. return this._mode;
  75884. },
  75885. /**
  75886. * Sets the current mode used by the behavior
  75887. */
  75888. set: function (mode) {
  75889. this._mode = mode;
  75890. },
  75891. enumerable: true,
  75892. configurable: true
  75893. });
  75894. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  75895. /**
  75896. * Gets the scale applied to the radius
  75897. */
  75898. get: function () {
  75899. return this._radiusScale;
  75900. },
  75901. /**
  75902. * Sets the scale applied to the radius (1 by default)
  75903. */
  75904. set: function (radius) {
  75905. this._radiusScale = radius;
  75906. },
  75907. enumerable: true,
  75908. configurable: true
  75909. });
  75910. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  75911. /**
  75912. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  75913. */
  75914. get: function () {
  75915. return this._positionScale;
  75916. },
  75917. /**
  75918. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  75919. */
  75920. set: function (scale) {
  75921. this._positionScale = scale;
  75922. },
  75923. enumerable: true,
  75924. configurable: true
  75925. });
  75926. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  75927. /**
  75928. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  75929. * behaviour is triggered, in radians.
  75930. */
  75931. get: function () {
  75932. return this._defaultElevation;
  75933. },
  75934. /**
  75935. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  75936. * behaviour is triggered, in radians.
  75937. */
  75938. set: function (elevation) {
  75939. this._defaultElevation = elevation;
  75940. },
  75941. enumerable: true,
  75942. configurable: true
  75943. });
  75944. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  75945. /**
  75946. * Gets the time (in milliseconds) taken to return to the default beta position.
  75947. * Negative value indicates camera should not return to default.
  75948. */
  75949. get: function () {
  75950. return this._elevationReturnTime;
  75951. },
  75952. /**
  75953. * Sets the time (in milliseconds) taken to return to the default beta position.
  75954. * Negative value indicates camera should not return to default.
  75955. */
  75956. set: function (speed) {
  75957. this._elevationReturnTime = speed;
  75958. },
  75959. enumerable: true,
  75960. configurable: true
  75961. });
  75962. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  75963. /**
  75964. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  75965. */
  75966. get: function () {
  75967. return this._elevationReturnWaitTime;
  75968. },
  75969. /**
  75970. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  75971. */
  75972. set: function (time) {
  75973. this._elevationReturnWaitTime = time;
  75974. },
  75975. enumerable: true,
  75976. configurable: true
  75977. });
  75978. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  75979. /**
  75980. * Gets the flag that indicates if user zooming should stop animation.
  75981. */
  75982. get: function () {
  75983. return this._zoomStopsAnimation;
  75984. },
  75985. /**
  75986. * Sets the flag that indicates if user zooming should stop animation.
  75987. */
  75988. set: function (flag) {
  75989. this._zoomStopsAnimation = flag;
  75990. },
  75991. enumerable: true,
  75992. configurable: true
  75993. });
  75994. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  75995. /**
  75996. * Gets the transition time when framing the mesh, in milliseconds
  75997. */
  75998. get: function () {
  75999. return this._framingTime;
  76000. },
  76001. /**
  76002. * Sets the transition time when framing the mesh, in milliseconds
  76003. */
  76004. set: function (time) {
  76005. this._framingTime = time;
  76006. },
  76007. enumerable: true,
  76008. configurable: true
  76009. });
  76010. FramingBehavior.prototype.init = function () {
  76011. // Do notihng
  76012. };
  76013. FramingBehavior.prototype.attach = function (camera) {
  76014. var _this = this;
  76015. this._attachedCamera = camera;
  76016. var scene = this._attachedCamera.getScene();
  76017. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  76018. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  76019. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  76020. _this._isPointerDown = true;
  76021. return;
  76022. }
  76023. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  76024. _this._isPointerDown = false;
  76025. }
  76026. });
  76027. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  76028. if (mesh) {
  76029. _this.zoomOnMesh(mesh);
  76030. }
  76031. });
  76032. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  76033. // Stop the animation if there is user interaction and the animation should stop for this interaction
  76034. _this._applyUserInteraction();
  76035. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  76036. // back to the default position after a given timeout
  76037. _this._maintainCameraAboveGround();
  76038. });
  76039. };
  76040. FramingBehavior.prototype.detach = function () {
  76041. if (!this._attachedCamera) {
  76042. return;
  76043. }
  76044. var scene = this._attachedCamera.getScene();
  76045. if (this._onPrePointerObservableObserver) {
  76046. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  76047. }
  76048. if (this._onAfterCheckInputsObserver) {
  76049. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  76050. }
  76051. if (this._onMeshTargetChangedObserver) {
  76052. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  76053. }
  76054. this._attachedCamera = null;
  76055. };
  76056. /**
  76057. * Targets the given mesh and updates zoom level accordingly.
  76058. * @param mesh The mesh to target.
  76059. * @param radius Optional. If a cached radius position already exists, overrides default.
  76060. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  76061. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  76062. * @param onAnimationEnd Callback triggered at the end of the framing animation
  76063. */
  76064. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  76065. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  76066. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  76067. mesh.computeWorldMatrix(true);
  76068. var boundingBox = mesh.getBoundingInfo().boundingBox;
  76069. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  76070. };
  76071. /**
  76072. * Targets the given mesh with its children and updates zoom level accordingly.
  76073. * @param mesh The mesh to target.
  76074. * @param radius Optional. If a cached radius position already exists, overrides default.
  76075. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  76076. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  76077. * @param onAnimationEnd Callback triggered at the end of the framing animation
  76078. */
  76079. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  76080. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  76081. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  76082. mesh.computeWorldMatrix(true);
  76083. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  76084. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  76085. };
  76086. /**
  76087. * Targets the given meshes with their children and updates zoom level accordingly.
  76088. * @param meshes The mesh to target.
  76089. * @param radius Optional. If a cached radius position already exists, overrides default.
  76090. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  76091. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  76092. * @param onAnimationEnd Callback triggered at the end of the framing animation
  76093. */
  76094. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  76095. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  76096. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  76097. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  76098. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  76099. for (var i = 0; i < meshes.length; i++) {
  76100. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  76101. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  76102. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  76103. }
  76104. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  76105. };
  76106. /**
  76107. * Targets the given mesh and updates zoom level accordingly.
  76108. * @param mesh The mesh to target.
  76109. * @param radius Optional. If a cached radius position already exists, overrides default.
  76110. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  76111. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  76112. * @param onAnimationEnd Callback triggered at the end of the framing animation
  76113. */
  76114. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  76115. var _this = this;
  76116. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  76117. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  76118. var zoomTarget;
  76119. if (!this._attachedCamera) {
  76120. return;
  76121. }
  76122. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  76123. var bottom = minimumWorld.y;
  76124. var top = maximumWorld.y;
  76125. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  76126. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  76127. if (focusOnOriginXZ) {
  76128. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  76129. }
  76130. else {
  76131. var centerWorld = minimumWorld.add(radiusWorld);
  76132. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  76133. }
  76134. if (!this._vectorTransition) {
  76135. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  76136. }
  76137. this._betaIsAnimating = true;
  76138. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  76139. if (animatable) {
  76140. this._animatables.push(animatable);
  76141. }
  76142. // sets the radius and lower radius bounds
  76143. // Small delta ensures camera is not always at lower zoom limit.
  76144. var radius = 0;
  76145. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  76146. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  76147. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  76148. radius = position;
  76149. }
  76150. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  76151. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  76152. if (this._attachedCamera.lowerRadiusLimit === null) {
  76153. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  76154. }
  76155. }
  76156. // Set sensibilities
  76157. var extend = maximumWorld.subtract(minimumWorld).length();
  76158. this._attachedCamera.panningSensibility = 5000 / extend;
  76159. this._attachedCamera.wheelPrecision = 100 / radius;
  76160. // transition to new radius
  76161. if (!this._radiusTransition) {
  76162. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  76163. }
  76164. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  76165. if (onAnimationEnd) {
  76166. onAnimationEnd();
  76167. }
  76168. if (_this._attachedCamera) {
  76169. _this._attachedCamera.storeState();
  76170. }
  76171. });
  76172. if (animatable) {
  76173. this._animatables.push(animatable);
  76174. }
  76175. };
  76176. /**
  76177. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  76178. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  76179. * frustum width.
  76180. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  76181. * to fully enclose the mesh in the viewing frustum.
  76182. */
  76183. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  76184. var size = maximumWorld.subtract(minimumWorld);
  76185. var boxVectorGlobalDiagonal = size.length();
  76186. var frustumSlope = this._getFrustumSlope();
  76187. // Formula for setting distance
  76188. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  76189. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  76190. // Horizon distance
  76191. var radius = radiusWithoutFraming * this._radiusScale;
  76192. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  76193. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  76194. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  76195. var camera = this._attachedCamera;
  76196. if (!camera) {
  76197. return 0;
  76198. }
  76199. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  76200. // Don't exceed the requested limit
  76201. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  76202. }
  76203. // Don't exceed the upper radius limit
  76204. if (camera.upperRadiusLimit) {
  76205. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  76206. }
  76207. return distance;
  76208. };
  76209. /**
  76210. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  76211. * is automatically returned to its default position (expected to be above ground plane).
  76212. */
  76213. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  76214. var _this = this;
  76215. if (this._elevationReturnTime < 0) {
  76216. return;
  76217. }
  76218. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  76219. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  76220. var limitBeta = Math.PI * 0.5;
  76221. // Bring the camera back up if below the ground plane
  76222. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  76223. this._betaIsAnimating = true;
  76224. //Transition to new position
  76225. this.stopAllAnimations();
  76226. if (!this._betaTransition) {
  76227. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  76228. }
  76229. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  76230. _this._clearAnimationLocks();
  76231. _this.stopAllAnimations();
  76232. });
  76233. if (animatabe) {
  76234. this._animatables.push(animatabe);
  76235. }
  76236. }
  76237. };
  76238. /**
  76239. * Returns the frustum slope based on the canvas ratio and camera FOV
  76240. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  76241. */
  76242. FramingBehavior.prototype._getFrustumSlope = function () {
  76243. // Calculate the viewport ratio
  76244. // Aspect Ratio is Height/Width.
  76245. var camera = this._attachedCamera;
  76246. if (!camera) {
  76247. return BABYLON.Vector2.Zero();
  76248. }
  76249. var engine = camera.getScene().getEngine();
  76250. var aspectRatio = engine.getAspectRatio(camera);
  76251. // Camera FOV is the vertical field of view (top-bottom) in radians.
  76252. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  76253. var frustumSlopeY = Math.tan(camera.fov / 2);
  76254. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  76255. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  76256. // along the forward vector.
  76257. var frustumSlopeX = frustumSlopeY * aspectRatio;
  76258. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  76259. };
  76260. /**
  76261. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  76262. */
  76263. FramingBehavior.prototype._clearAnimationLocks = function () {
  76264. this._betaIsAnimating = false;
  76265. };
  76266. /**
  76267. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  76268. */
  76269. FramingBehavior.prototype._applyUserInteraction = function () {
  76270. if (this.isUserIsMoving) {
  76271. this._lastInteractionTime = BABYLON.Tools.Now;
  76272. this.stopAllAnimations();
  76273. this._clearAnimationLocks();
  76274. }
  76275. };
  76276. /**
  76277. * Stops and removes all animations that have been applied to the camera
  76278. */
  76279. FramingBehavior.prototype.stopAllAnimations = function () {
  76280. if (this._attachedCamera) {
  76281. this._attachedCamera.animations = [];
  76282. }
  76283. while (this._animatables.length) {
  76284. if (this._animatables[0]) {
  76285. this._animatables[0].onAnimationEnd = null;
  76286. this._animatables[0].stop();
  76287. }
  76288. this._animatables.shift();
  76289. }
  76290. };
  76291. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  76292. /**
  76293. * Gets a value indicating if the user is moving the camera
  76294. */
  76295. get: function () {
  76296. if (!this._attachedCamera) {
  76297. return false;
  76298. }
  76299. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  76300. this._attachedCamera.inertialBetaOffset !== 0 ||
  76301. this._attachedCamera.inertialRadiusOffset !== 0 ||
  76302. this._attachedCamera.inertialPanningX !== 0 ||
  76303. this._attachedCamera.inertialPanningY !== 0 ||
  76304. this._isPointerDown;
  76305. },
  76306. enumerable: true,
  76307. configurable: true
  76308. });
  76309. /**
  76310. * The easing function used by animations
  76311. */
  76312. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  76313. /**
  76314. * The easing mode used by animations
  76315. */
  76316. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  76317. // Statics
  76318. /**
  76319. * The camera can move all the way towards the mesh.
  76320. */
  76321. FramingBehavior.IgnoreBoundsSizeMode = 0;
  76322. /**
  76323. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  76324. */
  76325. FramingBehavior.FitFrustumSidesMode = 1;
  76326. return FramingBehavior;
  76327. }());
  76328. BABYLON.FramingBehavior = FramingBehavior;
  76329. })(BABYLON || (BABYLON = {}));
  76330. //# sourceMappingURL=babylon.framingBehavior.js.map
  76331. var BABYLON;
  76332. (function (BABYLON) {
  76333. /**
  76334. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  76335. */
  76336. var BouncingBehavior = /** @class */ (function () {
  76337. function BouncingBehavior() {
  76338. /**
  76339. * The duration of the animation, in milliseconds
  76340. */
  76341. this.transitionDuration = 450;
  76342. /**
  76343. * Length of the distance animated by the transition when lower radius is reached
  76344. */
  76345. this.lowerRadiusTransitionRange = 2;
  76346. /**
  76347. * Length of the distance animated by the transition when upper radius is reached
  76348. */
  76349. this.upperRadiusTransitionRange = -2;
  76350. this._autoTransitionRange = false;
  76351. // Animations
  76352. this._radiusIsAnimating = false;
  76353. this._radiusBounceTransition = null;
  76354. this._animatables = new Array();
  76355. }
  76356. Object.defineProperty(BouncingBehavior.prototype, "name", {
  76357. get: function () {
  76358. return "Bouncing";
  76359. },
  76360. enumerable: true,
  76361. configurable: true
  76362. });
  76363. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  76364. /**
  76365. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  76366. */
  76367. get: function () {
  76368. return this._autoTransitionRange;
  76369. },
  76370. /**
  76371. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  76372. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  76373. */
  76374. set: function (value) {
  76375. var _this = this;
  76376. if (this._autoTransitionRange === value) {
  76377. return;
  76378. }
  76379. this._autoTransitionRange = value;
  76380. var camera = this._attachedCamera;
  76381. if (!camera) {
  76382. return;
  76383. }
  76384. if (value) {
  76385. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  76386. if (!mesh) {
  76387. return;
  76388. }
  76389. mesh.computeWorldMatrix(true);
  76390. var diagonal = mesh.getBoundingInfo().diagonalLength;
  76391. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  76392. _this.upperRadiusTransitionRange = diagonal * 0.05;
  76393. });
  76394. }
  76395. else if (this._onMeshTargetChangedObserver) {
  76396. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  76397. }
  76398. },
  76399. enumerable: true,
  76400. configurable: true
  76401. });
  76402. BouncingBehavior.prototype.init = function () {
  76403. // Do notihng
  76404. };
  76405. BouncingBehavior.prototype.attach = function (camera) {
  76406. var _this = this;
  76407. this._attachedCamera = camera;
  76408. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  76409. if (!_this._attachedCamera) {
  76410. return;
  76411. }
  76412. // Add the bounce animation to the lower radius limit
  76413. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  76414. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  76415. }
  76416. // Add the bounce animation to the upper radius limit
  76417. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  76418. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  76419. }
  76420. });
  76421. };
  76422. BouncingBehavior.prototype.detach = function () {
  76423. if (!this._attachedCamera) {
  76424. return;
  76425. }
  76426. if (this._onAfterCheckInputsObserver) {
  76427. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  76428. }
  76429. if (this._onMeshTargetChangedObserver) {
  76430. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  76431. }
  76432. this._attachedCamera = null;
  76433. };
  76434. /**
  76435. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  76436. * @param radiusLimit The limit to check against.
  76437. * @return Bool to indicate if at limit.
  76438. */
  76439. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  76440. if (!this._attachedCamera) {
  76441. return false;
  76442. }
  76443. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  76444. return true;
  76445. }
  76446. return false;
  76447. };
  76448. /**
  76449. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  76450. * @param radiusDelta The delta by which to animate to. Can be negative.
  76451. */
  76452. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  76453. var _this = this;
  76454. if (!this._attachedCamera) {
  76455. return;
  76456. }
  76457. if (!this._radiusBounceTransition) {
  76458. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  76459. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  76460. }
  76461. // Prevent zoom until bounce has completed
  76462. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  76463. this._attachedCamera.wheelPrecision = Infinity;
  76464. this._attachedCamera.inertialRadiusOffset = 0;
  76465. // Animate to the radius limit
  76466. this.stopAllAnimations();
  76467. this._radiusIsAnimating = true;
  76468. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  76469. if (animatable) {
  76470. this._animatables.push(animatable);
  76471. }
  76472. };
  76473. /**
  76474. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  76475. */
  76476. BouncingBehavior.prototype._clearAnimationLocks = function () {
  76477. this._radiusIsAnimating = false;
  76478. if (this._attachedCamera) {
  76479. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  76480. }
  76481. };
  76482. /**
  76483. * Stops and removes all animations that have been applied to the camera
  76484. */
  76485. BouncingBehavior.prototype.stopAllAnimations = function () {
  76486. if (this._attachedCamera) {
  76487. this._attachedCamera.animations = [];
  76488. }
  76489. while (this._animatables.length) {
  76490. this._animatables[0].onAnimationEnd = null;
  76491. this._animatables[0].stop();
  76492. this._animatables.shift();
  76493. }
  76494. };
  76495. /**
  76496. * The easing function used by animations
  76497. */
  76498. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  76499. /**
  76500. * The easing mode used by animations
  76501. */
  76502. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  76503. return BouncingBehavior;
  76504. }());
  76505. BABYLON.BouncingBehavior = BouncingBehavior;
  76506. })(BABYLON || (BABYLON = {}));
  76507. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  76508. var BABYLON;
  76509. (function (BABYLON) {
  76510. var AutoRotationBehavior = /** @class */ (function () {
  76511. function AutoRotationBehavior() {
  76512. this._zoomStopsAnimation = false;
  76513. this._idleRotationSpeed = 0.05;
  76514. this._idleRotationWaitTime = 2000;
  76515. this._idleRotationSpinupTime = 2000;
  76516. this._isPointerDown = false;
  76517. this._lastFrameTime = null;
  76518. this._lastInteractionTime = -Infinity;
  76519. this._cameraRotationSpeed = 0;
  76520. this._lastFrameRadius = 0;
  76521. }
  76522. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  76523. get: function () {
  76524. return "AutoRotation";
  76525. },
  76526. enumerable: true,
  76527. configurable: true
  76528. });
  76529. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  76530. /**
  76531. * Gets the flag that indicates if user zooming should stop animation.
  76532. */
  76533. get: function () {
  76534. return this._zoomStopsAnimation;
  76535. },
  76536. /**
  76537. * Sets the flag that indicates if user zooming should stop animation.
  76538. */
  76539. set: function (flag) {
  76540. this._zoomStopsAnimation = flag;
  76541. },
  76542. enumerable: true,
  76543. configurable: true
  76544. });
  76545. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  76546. /**
  76547. * Gets the default speed at which the camera rotates around the model.
  76548. */
  76549. get: function () {
  76550. return this._idleRotationSpeed;
  76551. },
  76552. /**
  76553. * Sets the default speed at which the camera rotates around the model.
  76554. */
  76555. set: function (speed) {
  76556. this._idleRotationSpeed = speed;
  76557. },
  76558. enumerable: true,
  76559. configurable: true
  76560. });
  76561. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  76562. /**
  76563. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  76564. */
  76565. get: function () {
  76566. return this._idleRotationWaitTime;
  76567. },
  76568. /**
  76569. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  76570. */
  76571. set: function (time) {
  76572. this._idleRotationWaitTime = time;
  76573. },
  76574. enumerable: true,
  76575. configurable: true
  76576. });
  76577. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  76578. /**
  76579. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  76580. */
  76581. get: function () {
  76582. return this._idleRotationSpinupTime;
  76583. },
  76584. /**
  76585. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  76586. */
  76587. set: function (time) {
  76588. this._idleRotationSpinupTime = time;
  76589. },
  76590. enumerable: true,
  76591. configurable: true
  76592. });
  76593. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  76594. /**
  76595. * Gets a value indicating if the camera is currently rotating because of this behavior
  76596. */
  76597. get: function () {
  76598. return Math.abs(this._cameraRotationSpeed) > 0;
  76599. },
  76600. enumerable: true,
  76601. configurable: true
  76602. });
  76603. AutoRotationBehavior.prototype.init = function () {
  76604. // Do notihng
  76605. };
  76606. AutoRotationBehavior.prototype.attach = function (camera) {
  76607. var _this = this;
  76608. this._attachedCamera = camera;
  76609. var scene = this._attachedCamera.getScene();
  76610. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  76611. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  76612. _this._isPointerDown = true;
  76613. return;
  76614. }
  76615. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  76616. _this._isPointerDown = false;
  76617. }
  76618. });
  76619. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  76620. var now = BABYLON.Tools.Now;
  76621. var dt = 0;
  76622. if (_this._lastFrameTime != null) {
  76623. dt = now - _this._lastFrameTime;
  76624. }
  76625. _this._lastFrameTime = now;
  76626. // Stop the animation if there is user interaction and the animation should stop for this interaction
  76627. _this._applyUserInteraction();
  76628. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  76629. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  76630. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  76631. // Step camera rotation by rotation speed
  76632. if (_this._attachedCamera) {
  76633. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  76634. }
  76635. });
  76636. };
  76637. AutoRotationBehavior.prototype.detach = function () {
  76638. if (!this._attachedCamera) {
  76639. return;
  76640. }
  76641. var scene = this._attachedCamera.getScene();
  76642. if (this._onPrePointerObservableObserver) {
  76643. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  76644. }
  76645. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  76646. this._attachedCamera = null;
  76647. };
  76648. /**
  76649. * Returns true if user is scrolling.
  76650. * @return true if user is scrolling.
  76651. */
  76652. AutoRotationBehavior.prototype._userIsZooming = function () {
  76653. if (!this._attachedCamera) {
  76654. return false;
  76655. }
  76656. return this._attachedCamera.inertialRadiusOffset !== 0;
  76657. };
  76658. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  76659. if (!this._attachedCamera) {
  76660. return false;
  76661. }
  76662. var zoomHasHitLimit = false;
  76663. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  76664. zoomHasHitLimit = true;
  76665. }
  76666. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  76667. this._lastFrameRadius = this._attachedCamera.radius;
  76668. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  76669. };
  76670. /**
  76671. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  76672. */
  76673. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  76674. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  76675. this._lastInteractionTime = BABYLON.Tools.Now;
  76676. }
  76677. };
  76678. // Tools
  76679. AutoRotationBehavior.prototype._userIsMoving = function () {
  76680. if (!this._attachedCamera) {
  76681. return false;
  76682. }
  76683. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  76684. this._attachedCamera.inertialBetaOffset !== 0 ||
  76685. this._attachedCamera.inertialRadiusOffset !== 0 ||
  76686. this._attachedCamera.inertialPanningX !== 0 ||
  76687. this._attachedCamera.inertialPanningY !== 0 ||
  76688. this._isPointerDown;
  76689. };
  76690. return AutoRotationBehavior;
  76691. }());
  76692. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  76693. })(BABYLON || (BABYLON = {}));
  76694. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  76695. var BABYLON;
  76696. (function (BABYLON) {
  76697. /**
  76698. * This class can be used to get instrumentation data from a Babylon engine
  76699. */
  76700. var EngineInstrumentation = /** @class */ (function () {
  76701. function EngineInstrumentation(engine) {
  76702. this.engine = engine;
  76703. this._captureGPUFrameTime = false;
  76704. this._gpuFrameTime = new BABYLON.PerfCounter();
  76705. this._captureShaderCompilationTime = false;
  76706. this._shaderCompilationTime = new BABYLON.PerfCounter();
  76707. // Observers
  76708. this._onBeginFrameObserver = null;
  76709. this._onEndFrameObserver = null;
  76710. this._onBeforeShaderCompilationObserver = null;
  76711. this._onAfterShaderCompilationObserver = null;
  76712. }
  76713. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  76714. // Properties
  76715. /**
  76716. * Gets the perf counter used for GPU frame time
  76717. */
  76718. get: function () {
  76719. return this._gpuFrameTime;
  76720. },
  76721. enumerable: true,
  76722. configurable: true
  76723. });
  76724. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  76725. /**
  76726. * Gets the GPU frame time capture status
  76727. */
  76728. get: function () {
  76729. return this._captureGPUFrameTime;
  76730. },
  76731. /**
  76732. * Enable or disable the GPU frame time capture
  76733. */
  76734. set: function (value) {
  76735. var _this = this;
  76736. if (value === this._captureGPUFrameTime) {
  76737. return;
  76738. }
  76739. this._captureGPUFrameTime = value;
  76740. if (value) {
  76741. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  76742. if (!_this._gpuFrameTimeToken) {
  76743. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  76744. }
  76745. });
  76746. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  76747. if (!_this._gpuFrameTimeToken) {
  76748. return;
  76749. }
  76750. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  76751. if (time > -1) {
  76752. _this._gpuFrameTimeToken = null;
  76753. _this._gpuFrameTime.fetchNewFrame();
  76754. _this._gpuFrameTime.addCount(time, true);
  76755. }
  76756. });
  76757. }
  76758. else {
  76759. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  76760. this._onBeginFrameObserver = null;
  76761. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  76762. this._onEndFrameObserver = null;
  76763. }
  76764. },
  76765. enumerable: true,
  76766. configurable: true
  76767. });
  76768. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  76769. /**
  76770. * Gets the perf counter used for shader compilation time
  76771. */
  76772. get: function () {
  76773. return this._shaderCompilationTime;
  76774. },
  76775. enumerable: true,
  76776. configurable: true
  76777. });
  76778. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  76779. /**
  76780. * Gets the shader compilation time capture status
  76781. */
  76782. get: function () {
  76783. return this._captureShaderCompilationTime;
  76784. },
  76785. /**
  76786. * Enable or disable the shader compilation time capture
  76787. */
  76788. set: function (value) {
  76789. var _this = this;
  76790. if (value === this._captureShaderCompilationTime) {
  76791. return;
  76792. }
  76793. this._captureShaderCompilationTime = value;
  76794. if (value) {
  76795. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  76796. _this._shaderCompilationTime.fetchNewFrame();
  76797. _this._shaderCompilationTime.beginMonitoring();
  76798. });
  76799. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  76800. _this._shaderCompilationTime.endMonitoring();
  76801. });
  76802. }
  76803. else {
  76804. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  76805. this._onBeforeShaderCompilationObserver = null;
  76806. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  76807. this._onAfterShaderCompilationObserver = null;
  76808. }
  76809. },
  76810. enumerable: true,
  76811. configurable: true
  76812. });
  76813. EngineInstrumentation.prototype.dispose = function () {
  76814. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  76815. this._onBeginFrameObserver = null;
  76816. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  76817. this._onEndFrameObserver = null;
  76818. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  76819. this._onBeforeShaderCompilationObserver = null;
  76820. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  76821. this._onAfterShaderCompilationObserver = null;
  76822. this.engine = null;
  76823. };
  76824. return EngineInstrumentation;
  76825. }());
  76826. BABYLON.EngineInstrumentation = EngineInstrumentation;
  76827. })(BABYLON || (BABYLON = {}));
  76828. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  76829. var BABYLON;
  76830. (function (BABYLON) {
  76831. /**
  76832. * This class can be used to get instrumentation data from a Babylon engine
  76833. */
  76834. var SceneInstrumentation = /** @class */ (function () {
  76835. function SceneInstrumentation(scene) {
  76836. var _this = this;
  76837. this.scene = scene;
  76838. this._captureActiveMeshesEvaluationTime = false;
  76839. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  76840. this._captureRenderTargetsRenderTime = false;
  76841. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  76842. this._captureFrameTime = false;
  76843. this._frameTime = new BABYLON.PerfCounter();
  76844. this._captureRenderTime = false;
  76845. this._renderTime = new BABYLON.PerfCounter();
  76846. this._captureInterFrameTime = false;
  76847. this._interFrameTime = new BABYLON.PerfCounter();
  76848. this._captureParticlesRenderTime = false;
  76849. this._particlesRenderTime = new BABYLON.PerfCounter();
  76850. this._captureSpritesRenderTime = false;
  76851. this._spritesRenderTime = new BABYLON.PerfCounter();
  76852. this._capturePhysicsTime = false;
  76853. this._physicsTime = new BABYLON.PerfCounter();
  76854. this._captureAnimationsTime = false;
  76855. this._animationsTime = new BABYLON.PerfCounter();
  76856. // Observers
  76857. this._onBeforeActiveMeshesEvaluationObserver = null;
  76858. this._onAfterActiveMeshesEvaluationObserver = null;
  76859. this._onBeforeRenderTargetsRenderObserver = null;
  76860. this._onAfterRenderTargetsRenderObserver = null;
  76861. this._onAfterRenderObserver = null;
  76862. this._onBeforeDrawPhaseObserver = null;
  76863. this._onAfterDrawPhaseObserver = null;
  76864. this._onBeforeAnimationsObserver = null;
  76865. this._onBeforeParticlesRenderingObserver = null;
  76866. this._onAfterParticlesRenderingObserver = null;
  76867. this._onBeforeSpritesRenderingObserver = null;
  76868. this._onAfterSpritesRenderingObserver = null;
  76869. this._onBeforePhysicsObserver = null;
  76870. this._onAfterPhysicsObserver = null;
  76871. this._onAfterAnimationsObserver = null;
  76872. // Before render
  76873. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  76874. if (_this._captureActiveMeshesEvaluationTime) {
  76875. _this._activeMeshesEvaluationTime.fetchNewFrame();
  76876. }
  76877. if (_this._captureRenderTargetsRenderTime) {
  76878. _this._renderTargetsRenderTime.fetchNewFrame();
  76879. }
  76880. if (_this._captureFrameTime) {
  76881. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  76882. _this._frameTime.beginMonitoring();
  76883. }
  76884. if (_this._captureInterFrameTime) {
  76885. _this._interFrameTime.endMonitoring();
  76886. }
  76887. if (_this._captureParticlesRenderTime) {
  76888. _this._particlesRenderTime.fetchNewFrame();
  76889. }
  76890. if (_this._captureSpritesRenderTime) {
  76891. _this._spritesRenderTime.fetchNewFrame();
  76892. }
  76893. if (_this._captureAnimationsTime) {
  76894. _this._animationsTime.beginMonitoring();
  76895. }
  76896. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  76897. });
  76898. // After render
  76899. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  76900. if (_this._captureFrameTime) {
  76901. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  76902. _this._frameTime.endMonitoring();
  76903. }
  76904. if (_this._captureRenderTime) {
  76905. _this._renderTime.endMonitoring(false);
  76906. }
  76907. if (_this._captureInterFrameTime) {
  76908. _this._interFrameTime.beginMonitoring();
  76909. }
  76910. });
  76911. }
  76912. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  76913. // Properties
  76914. /**
  76915. * Gets the perf counter used for active meshes evaluation time
  76916. */
  76917. get: function () {
  76918. return this._activeMeshesEvaluationTime;
  76919. },
  76920. enumerable: true,
  76921. configurable: true
  76922. });
  76923. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  76924. /**
  76925. * Gets the active meshes evaluation time capture status
  76926. */
  76927. get: function () {
  76928. return this._captureActiveMeshesEvaluationTime;
  76929. },
  76930. /**
  76931. * Enable or disable the active meshes evaluation time capture
  76932. */
  76933. set: function (value) {
  76934. var _this = this;
  76935. if (value === this._captureActiveMeshesEvaluationTime) {
  76936. return;
  76937. }
  76938. this._captureActiveMeshesEvaluationTime = value;
  76939. if (value) {
  76940. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  76941. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  76942. _this._activeMeshesEvaluationTime.beginMonitoring();
  76943. });
  76944. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  76945. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  76946. _this._activeMeshesEvaluationTime.endMonitoring();
  76947. });
  76948. }
  76949. else {
  76950. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  76951. this._onBeforeActiveMeshesEvaluationObserver = null;
  76952. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  76953. this._onAfterActiveMeshesEvaluationObserver = null;
  76954. }
  76955. },
  76956. enumerable: true,
  76957. configurable: true
  76958. });
  76959. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  76960. /**
  76961. * Gets the perf counter used for render targets render time
  76962. */
  76963. get: function () {
  76964. return this._renderTargetsRenderTime;
  76965. },
  76966. enumerable: true,
  76967. configurable: true
  76968. });
  76969. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  76970. /**
  76971. * Gets the render targets render time capture status
  76972. */
  76973. get: function () {
  76974. return this._captureRenderTargetsRenderTime;
  76975. },
  76976. /**
  76977. * Enable or disable the render targets render time capture
  76978. */
  76979. set: function (value) {
  76980. var _this = this;
  76981. if (value === this._captureRenderTargetsRenderTime) {
  76982. return;
  76983. }
  76984. this._captureRenderTargetsRenderTime = value;
  76985. if (value) {
  76986. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  76987. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  76988. _this._renderTargetsRenderTime.beginMonitoring();
  76989. });
  76990. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  76991. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  76992. _this._renderTargetsRenderTime.endMonitoring(false);
  76993. });
  76994. }
  76995. else {
  76996. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  76997. this._onBeforeRenderTargetsRenderObserver = null;
  76998. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  76999. this._onAfterRenderTargetsRenderObserver = null;
  77000. }
  77001. },
  77002. enumerable: true,
  77003. configurable: true
  77004. });
  77005. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  77006. /**
  77007. * Gets the perf counter used for particles render time
  77008. */
  77009. get: function () {
  77010. return this._particlesRenderTime;
  77011. },
  77012. enumerable: true,
  77013. configurable: true
  77014. });
  77015. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  77016. /**
  77017. * Gets the particles render time capture status
  77018. */
  77019. get: function () {
  77020. return this._captureParticlesRenderTime;
  77021. },
  77022. /**
  77023. * Enable or disable the particles render time capture
  77024. */
  77025. set: function (value) {
  77026. var _this = this;
  77027. if (value === this._captureParticlesRenderTime) {
  77028. return;
  77029. }
  77030. this._captureParticlesRenderTime = value;
  77031. if (value) {
  77032. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  77033. BABYLON.Tools.StartPerformanceCounter("Particles");
  77034. _this._particlesRenderTime.beginMonitoring();
  77035. });
  77036. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  77037. BABYLON.Tools.EndPerformanceCounter("Particles");
  77038. _this._particlesRenderTime.endMonitoring(false);
  77039. });
  77040. }
  77041. else {
  77042. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  77043. this._onBeforeParticlesRenderingObserver = null;
  77044. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  77045. this._onAfterParticlesRenderingObserver = null;
  77046. }
  77047. },
  77048. enumerable: true,
  77049. configurable: true
  77050. });
  77051. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  77052. /**
  77053. * Gets the perf counter used for sprites render time
  77054. */
  77055. get: function () {
  77056. return this._spritesRenderTime;
  77057. },
  77058. enumerable: true,
  77059. configurable: true
  77060. });
  77061. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  77062. /**
  77063. * Gets the sprites render time capture status
  77064. */
  77065. get: function () {
  77066. return this._captureSpritesRenderTime;
  77067. },
  77068. /**
  77069. * Enable or disable the sprites render time capture
  77070. */
  77071. set: function (value) {
  77072. var _this = this;
  77073. if (value === this._captureSpritesRenderTime) {
  77074. return;
  77075. }
  77076. this._captureSpritesRenderTime = value;
  77077. if (value) {
  77078. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  77079. BABYLON.Tools.StartPerformanceCounter("Sprites");
  77080. _this._spritesRenderTime.beginMonitoring();
  77081. });
  77082. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  77083. BABYLON.Tools.EndPerformanceCounter("Sprites");
  77084. _this._spritesRenderTime.endMonitoring(false);
  77085. });
  77086. }
  77087. else {
  77088. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  77089. this._onBeforeSpritesRenderingObserver = null;
  77090. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  77091. this._onAfterSpritesRenderingObserver = null;
  77092. }
  77093. },
  77094. enumerable: true,
  77095. configurable: true
  77096. });
  77097. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  77098. /**
  77099. * Gets the perf counter used for physics time
  77100. */
  77101. get: function () {
  77102. return this._physicsTime;
  77103. },
  77104. enumerable: true,
  77105. configurable: true
  77106. });
  77107. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  77108. /**
  77109. * Gets the physics time capture status
  77110. */
  77111. get: function () {
  77112. return this._capturePhysicsTime;
  77113. },
  77114. /**
  77115. * Enable or disable the physics time capture
  77116. */
  77117. set: function (value) {
  77118. var _this = this;
  77119. if (value === this._capturePhysicsTime) {
  77120. return;
  77121. }
  77122. this._capturePhysicsTime = value;
  77123. if (value) {
  77124. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  77125. BABYLON.Tools.StartPerformanceCounter("Physics");
  77126. _this._physicsTime.beginMonitoring();
  77127. });
  77128. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  77129. BABYLON.Tools.EndPerformanceCounter("Physics");
  77130. _this._physicsTime.endMonitoring();
  77131. });
  77132. }
  77133. else {
  77134. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  77135. this._onBeforePhysicsObserver = null;
  77136. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  77137. this._onAfterPhysicsObserver = null;
  77138. }
  77139. },
  77140. enumerable: true,
  77141. configurable: true
  77142. });
  77143. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  77144. /**
  77145. * Gets the perf counter used for animations time
  77146. */
  77147. get: function () {
  77148. return this._animationsTime;
  77149. },
  77150. enumerable: true,
  77151. configurable: true
  77152. });
  77153. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  77154. /**
  77155. * Gets the animations time capture status
  77156. */
  77157. get: function () {
  77158. return this._captureAnimationsTime;
  77159. },
  77160. /**
  77161. * Enable or disable the animations time capture
  77162. */
  77163. set: function (value) {
  77164. var _this = this;
  77165. if (value === this._captureAnimationsTime) {
  77166. return;
  77167. }
  77168. this._captureAnimationsTime = value;
  77169. if (value) {
  77170. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  77171. _this._animationsTime.endMonitoring();
  77172. });
  77173. }
  77174. else {
  77175. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  77176. this._onAfterAnimationsObserver = null;
  77177. }
  77178. },
  77179. enumerable: true,
  77180. configurable: true
  77181. });
  77182. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  77183. /**
  77184. * Gets the perf counter used for frame time capture
  77185. */
  77186. get: function () {
  77187. return this._frameTime;
  77188. },
  77189. enumerable: true,
  77190. configurable: true
  77191. });
  77192. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  77193. /**
  77194. * Gets the frame time capture status
  77195. */
  77196. get: function () {
  77197. return this._captureFrameTime;
  77198. },
  77199. /**
  77200. * Enable or disable the frame time capture
  77201. */
  77202. set: function (value) {
  77203. this._captureFrameTime = value;
  77204. },
  77205. enumerable: true,
  77206. configurable: true
  77207. });
  77208. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  77209. /**
  77210. * Gets the perf counter used for inter-frames time capture
  77211. */
  77212. get: function () {
  77213. return this._interFrameTime;
  77214. },
  77215. enumerable: true,
  77216. configurable: true
  77217. });
  77218. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  77219. /**
  77220. * Gets the inter-frames time capture status
  77221. */
  77222. get: function () {
  77223. return this._captureInterFrameTime;
  77224. },
  77225. /**
  77226. * Enable or disable the inter-frames time capture
  77227. */
  77228. set: function (value) {
  77229. this._captureInterFrameTime = value;
  77230. },
  77231. enumerable: true,
  77232. configurable: true
  77233. });
  77234. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  77235. /**
  77236. * Gets the perf counter used for render time capture
  77237. */
  77238. get: function () {
  77239. return this._renderTime;
  77240. },
  77241. enumerable: true,
  77242. configurable: true
  77243. });
  77244. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  77245. /**
  77246. * Gets the render time capture status
  77247. */
  77248. get: function () {
  77249. return this._captureRenderTime;
  77250. },
  77251. /**
  77252. * Enable or disable the render time capture
  77253. */
  77254. set: function (value) {
  77255. var _this = this;
  77256. if (value === this._captureRenderTime) {
  77257. return;
  77258. }
  77259. this._captureRenderTime = value;
  77260. if (value) {
  77261. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  77262. _this._renderTime.beginMonitoring();
  77263. BABYLON.Tools.StartPerformanceCounter("Main render");
  77264. });
  77265. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  77266. _this._renderTime.endMonitoring(false);
  77267. BABYLON.Tools.EndPerformanceCounter("Main render");
  77268. });
  77269. }
  77270. else {
  77271. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  77272. this._onBeforeDrawPhaseObserver = null;
  77273. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  77274. this._onAfterDrawPhaseObserver = null;
  77275. }
  77276. },
  77277. enumerable: true,
  77278. configurable: true
  77279. });
  77280. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  77281. /**
  77282. * Gets the perf counter used for frame time capture
  77283. */
  77284. get: function () {
  77285. return this.scene.getEngine()._drawCalls;
  77286. },
  77287. enumerable: true,
  77288. configurable: true
  77289. });
  77290. SceneInstrumentation.prototype.dispose = function () {
  77291. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  77292. this._onAfterRenderObserver = null;
  77293. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  77294. this._onBeforeActiveMeshesEvaluationObserver = null;
  77295. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  77296. this._onAfterActiveMeshesEvaluationObserver = null;
  77297. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  77298. this._onBeforeRenderTargetsRenderObserver = null;
  77299. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  77300. this._onAfterRenderTargetsRenderObserver = null;
  77301. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  77302. this._onBeforeAnimationsObserver = null;
  77303. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  77304. this._onBeforeParticlesRenderingObserver = null;
  77305. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  77306. this._onAfterParticlesRenderingObserver = null;
  77307. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  77308. this._onBeforeSpritesRenderingObserver = null;
  77309. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  77310. this._onAfterSpritesRenderingObserver = null;
  77311. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  77312. this._onBeforeDrawPhaseObserver = null;
  77313. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  77314. this._onAfterDrawPhaseObserver = null;
  77315. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  77316. this._onBeforePhysicsObserver = null;
  77317. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  77318. this._onAfterPhysicsObserver = null;
  77319. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  77320. this._onAfterAnimationsObserver = null;
  77321. this.scene = null;
  77322. };
  77323. return SceneInstrumentation;
  77324. }());
  77325. BABYLON.SceneInstrumentation = SceneInstrumentation;
  77326. })(BABYLON || (BABYLON = {}));
  77327. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  77328. var BABYLON;
  77329. (function (BABYLON) {
  77330. var _TimeToken = /** @class */ (function () {
  77331. function _TimeToken() {
  77332. this._timeElapsedQueryEnded = false;
  77333. }
  77334. return _TimeToken;
  77335. }());
  77336. BABYLON._TimeToken = _TimeToken;
  77337. })(BABYLON || (BABYLON = {}));
  77338. //# sourceMappingURL=babylon.timeToken.js.map
  77339. var BABYLON;
  77340. (function (BABYLON) {
  77341. /**
  77342. * Background material defines definition.
  77343. */
  77344. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  77345. __extends(BackgroundMaterialDefines, _super);
  77346. /**
  77347. * Constructor of the defines.
  77348. */
  77349. function BackgroundMaterialDefines() {
  77350. var _this = _super.call(this) || this;
  77351. /**
  77352. * True if the diffuse texture is in use.
  77353. */
  77354. _this.DIFFUSE = false;
  77355. /**
  77356. * The direct UV channel to use.
  77357. */
  77358. _this.DIFFUSEDIRECTUV = 0;
  77359. /**
  77360. * True if the diffuse texture is in gamma space.
  77361. */
  77362. _this.GAMMADIFFUSE = false;
  77363. /**
  77364. * True if the diffuse texture has opacity in the alpha channel.
  77365. */
  77366. _this.DIFFUSEHASALPHA = false;
  77367. /**
  77368. * True if you want the material to fade to transparent at grazing angle.
  77369. */
  77370. _this.OPACITYFRESNEL = false;
  77371. /**
  77372. * True if an extra blur needs to be added in the reflection.
  77373. */
  77374. _this.REFLECTIONBLUR = false;
  77375. /**
  77376. * True if you want the material to fade to reflection at grazing angle.
  77377. */
  77378. _this.REFLECTIONFRESNEL = false;
  77379. /**
  77380. * True if you want the material to falloff as far as you move away from the scene center.
  77381. */
  77382. _this.REFLECTIONFALLOFF = false;
  77383. /**
  77384. * False if the current Webgl implementation does not support the texture lod extension.
  77385. */
  77386. _this.TEXTURELODSUPPORT = false;
  77387. /**
  77388. * True to ensure the data are premultiplied.
  77389. */
  77390. _this.PREMULTIPLYALPHA = false;
  77391. /**
  77392. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  77393. */
  77394. _this.USERGBCOLOR = false;
  77395. /**
  77396. * True to add noise in order to reduce the banding effect.
  77397. */
  77398. _this.NOISE = false;
  77399. // Image Processing Configuration.
  77400. _this.IMAGEPROCESSING = false;
  77401. _this.VIGNETTE = false;
  77402. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  77403. _this.VIGNETTEBLENDMODEOPAQUE = false;
  77404. _this.TONEMAPPING = false;
  77405. _this.CONTRAST = false;
  77406. _this.COLORCURVES = false;
  77407. _this.COLORGRADING = false;
  77408. _this.COLORGRADING3D = false;
  77409. _this.SAMPLER3DGREENDEPTH = false;
  77410. _this.SAMPLER3DBGRMAP = false;
  77411. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  77412. _this.EXPOSURE = false;
  77413. // Reflection.
  77414. _this.REFLECTION = false;
  77415. _this.REFLECTIONMAP_3D = false;
  77416. _this.REFLECTIONMAP_SPHERICAL = false;
  77417. _this.REFLECTIONMAP_PLANAR = false;
  77418. _this.REFLECTIONMAP_CUBIC = false;
  77419. _this.REFLECTIONMAP_PROJECTION = false;
  77420. _this.REFLECTIONMAP_SKYBOX = false;
  77421. _this.REFLECTIONMAP_EXPLICIT = false;
  77422. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  77423. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  77424. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  77425. _this.INVERTCUBICMAP = false;
  77426. _this.REFLECTIONMAP_OPPOSITEZ = false;
  77427. _this.LODINREFLECTIONALPHA = false;
  77428. _this.GAMMAREFLECTION = false;
  77429. // Default BJS.
  77430. _this.MAINUV1 = false;
  77431. _this.MAINUV2 = false;
  77432. _this.UV1 = false;
  77433. _this.UV2 = false;
  77434. _this.CLIPPLANE = false;
  77435. _this.POINTSIZE = false;
  77436. _this.FOG = false;
  77437. _this.NORMAL = false;
  77438. _this.NUM_BONE_INFLUENCERS = 0;
  77439. _this.BonesPerMesh = 0;
  77440. _this.INSTANCES = false;
  77441. _this.SHADOWFLOAT = false;
  77442. _this.rebuild();
  77443. return _this;
  77444. }
  77445. return BackgroundMaterialDefines;
  77446. }(BABYLON.MaterialDefines));
  77447. /**
  77448. * Background material used to create an efficient environement around your scene.
  77449. */
  77450. var BackgroundMaterial = /** @class */ (function (_super) {
  77451. __extends(BackgroundMaterial, _super);
  77452. /**
  77453. * constructor
  77454. * @param name The name of the material
  77455. * @param scene The scene to add the material to
  77456. */
  77457. function BackgroundMaterial(name, scene) {
  77458. var _this = _super.call(this, name, scene) || this;
  77459. _this.primaryColor = BABYLON.Color3.White();
  77460. _this.primaryLevel = 1;
  77461. _this.secondaryColor = BABYLON.Color3.Gray();
  77462. _this.secondaryLevel = 1;
  77463. _this.tertiaryColor = BABYLON.Color3.Black();
  77464. _this.tertiaryLevel = 1;
  77465. _this.reflectionTexture = null;
  77466. _this.reflectionBlur = 0;
  77467. _this.diffuseTexture = null;
  77468. /**
  77469. * Specify the list of lights casting shadow on the material.
  77470. * All scene shadow lights will be included if null.
  77471. */
  77472. _this._shadowLights = null;
  77473. _this.shadowLights = null;
  77474. _this.shadowBlurScale = 1;
  77475. _this.shadowLevel = 0;
  77476. _this.sceneCenter = BABYLON.Vector3.Zero();
  77477. _this.opacityFresnel = true;
  77478. _this.reflectionFresnel = false;
  77479. _this.reflectionFalloffDistance = 0.0;
  77480. _this.reflectionAmount = 1.0;
  77481. _this.reflectionReflectance0 = 0.05;
  77482. _this.reflectionReflectance90 = 0.5;
  77483. _this.useRGBColor = true;
  77484. _this.enableNoise = false;
  77485. /**
  77486. * Number of Simultaneous lights allowed on the material.
  77487. */
  77488. _this._maxSimultaneousLights = 4;
  77489. _this.maxSimultaneousLights = 4;
  77490. /**
  77491. * Keep track of the image processing observer to allow dispose and replace.
  77492. */
  77493. _this._imageProcessingObserver = null;
  77494. // Temp values kept as cache in the material.
  77495. _this._renderTargets = new BABYLON.SmartArray(16);
  77496. _this._reflectionControls = BABYLON.Vector4.Zero();
  77497. // Setup the default processing configuration to the scene.
  77498. _this._attachImageProcessingConfiguration(null);
  77499. _this.getRenderTargetTextures = function () {
  77500. _this._renderTargets.reset();
  77501. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  77502. _this._renderTargets.push(_this._diffuseTexture);
  77503. }
  77504. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  77505. _this._renderTargets.push(_this._reflectionTexture);
  77506. }
  77507. return _this._renderTargets;
  77508. };
  77509. return _this;
  77510. }
  77511. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  77512. /**
  77513. * Sets the reflection reflectance fresnel values according to the default standard
  77514. * empirically know to work well :-)
  77515. */
  77516. set: function (value) {
  77517. var reflectionWeight = value;
  77518. if (reflectionWeight < 0.5) {
  77519. reflectionWeight = reflectionWeight * 2.0;
  77520. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 * reflectionWeight;
  77521. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 * reflectionWeight;
  77522. }
  77523. else {
  77524. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  77525. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 + (1.0 - BackgroundMaterial.standardReflectance0) * reflectionWeight;
  77526. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 + (1.0 - BackgroundMaterial.standardReflectance90) * reflectionWeight;
  77527. }
  77528. },
  77529. enumerable: true,
  77530. configurable: true
  77531. });
  77532. /**
  77533. * Attaches a new image processing configuration to the PBR Material.
  77534. * @param configuration (if null the scene configuration will be use)
  77535. */
  77536. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  77537. var _this = this;
  77538. if (configuration === this._imageProcessingConfiguration) {
  77539. return;
  77540. }
  77541. // Detaches observer.
  77542. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77543. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77544. }
  77545. // Pick the scene configuration if needed.
  77546. if (!configuration) {
  77547. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  77548. }
  77549. else {
  77550. this._imageProcessingConfiguration = configuration;
  77551. }
  77552. // Attaches observer.
  77553. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  77554. _this._markAllSubMeshesAsImageProcessingDirty();
  77555. });
  77556. };
  77557. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  77558. /**
  77559. * Gets the image processing configuration used either in this material.
  77560. */
  77561. get: function () {
  77562. return this._imageProcessingConfiguration;
  77563. },
  77564. /**
  77565. * Sets the Default image processing configuration used either in the this material.
  77566. *
  77567. * If sets to null, the scene one is in use.
  77568. */
  77569. set: function (value) {
  77570. this._attachImageProcessingConfiguration(value);
  77571. // Ensure the effect will be rebuilt.
  77572. this._markAllSubMeshesAsTexturesDirty();
  77573. },
  77574. enumerable: true,
  77575. configurable: true
  77576. });
  77577. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  77578. /**
  77579. * Gets wether the color curves effect is enabled.
  77580. */
  77581. get: function () {
  77582. return this.imageProcessingConfiguration.colorCurvesEnabled;
  77583. },
  77584. /**
  77585. * Sets wether the color curves effect is enabled.
  77586. */
  77587. set: function (value) {
  77588. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  77589. },
  77590. enumerable: true,
  77591. configurable: true
  77592. });
  77593. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  77594. /**
  77595. * Gets wether the color grading effect is enabled.
  77596. */
  77597. get: function () {
  77598. return this.imageProcessingConfiguration.colorGradingEnabled;
  77599. },
  77600. /**
  77601. * Gets wether the color grading effect is enabled.
  77602. */
  77603. set: function (value) {
  77604. this.imageProcessingConfiguration.colorGradingEnabled = value;
  77605. },
  77606. enumerable: true,
  77607. configurable: true
  77608. });
  77609. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  77610. /**
  77611. * Gets wether tonemapping is enabled or not.
  77612. */
  77613. get: function () {
  77614. return this._imageProcessingConfiguration.toneMappingEnabled;
  77615. },
  77616. /**
  77617. * Sets wether tonemapping is enabled or not
  77618. */
  77619. set: function (value) {
  77620. this._imageProcessingConfiguration.toneMappingEnabled = value;
  77621. },
  77622. enumerable: true,
  77623. configurable: true
  77624. });
  77625. ;
  77626. ;
  77627. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  77628. /**
  77629. * The camera exposure used on this material.
  77630. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  77631. * This corresponds to a photographic exposure.
  77632. */
  77633. get: function () {
  77634. return this._imageProcessingConfiguration.exposure;
  77635. },
  77636. /**
  77637. * The camera exposure used on this material.
  77638. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  77639. * This corresponds to a photographic exposure.
  77640. */
  77641. set: function (value) {
  77642. this._imageProcessingConfiguration.exposure = value;
  77643. },
  77644. enumerable: true,
  77645. configurable: true
  77646. });
  77647. ;
  77648. ;
  77649. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  77650. /**
  77651. * Gets The camera contrast used on this material.
  77652. */
  77653. get: function () {
  77654. return this._imageProcessingConfiguration.contrast;
  77655. },
  77656. /**
  77657. * Sets The camera contrast used on this material.
  77658. */
  77659. set: function (value) {
  77660. this._imageProcessingConfiguration.contrast = value;
  77661. },
  77662. enumerable: true,
  77663. configurable: true
  77664. });
  77665. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  77666. /**
  77667. * Gets the Color Grading 2D Lookup Texture.
  77668. */
  77669. get: function () {
  77670. return this._imageProcessingConfiguration.colorGradingTexture;
  77671. },
  77672. /**
  77673. * Sets the Color Grading 2D Lookup Texture.
  77674. */
  77675. set: function (value) {
  77676. this.imageProcessingConfiguration.colorGradingTexture = value;
  77677. },
  77678. enumerable: true,
  77679. configurable: true
  77680. });
  77681. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  77682. /**
  77683. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  77684. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  77685. * 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;
  77686. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  77687. */
  77688. get: function () {
  77689. return this.imageProcessingConfiguration.colorCurves;
  77690. },
  77691. /**
  77692. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  77693. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  77694. * 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;
  77695. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  77696. */
  77697. set: function (value) {
  77698. this.imageProcessingConfiguration.colorCurves = value;
  77699. },
  77700. enumerable: true,
  77701. configurable: true
  77702. });
  77703. /**
  77704. * The entire material has been created in order to prevent overdraw.
  77705. * @returns false
  77706. */
  77707. BackgroundMaterial.prototype.needAlphaTesting = function () {
  77708. return true;
  77709. };
  77710. /**
  77711. * The entire material has been created in order to prevent overdraw.
  77712. * @returns true if blending is enable
  77713. */
  77714. BackgroundMaterial.prototype.needAlphaBlending = function () {
  77715. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  77716. };
  77717. /**
  77718. * Checks wether the material is ready to be rendered for a given mesh.
  77719. * @param mesh The mesh to render
  77720. * @param subMesh The submesh to check against
  77721. * @param useInstances Specify wether or not the material is used with instances
  77722. */
  77723. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  77724. var _this = this;
  77725. if (useInstances === void 0) { useInstances = false; }
  77726. if (subMesh.effect && this.isFrozen) {
  77727. if (this._wasPreviouslyReady) {
  77728. return true;
  77729. }
  77730. }
  77731. if (!subMesh._materialDefines) {
  77732. subMesh._materialDefines = new BackgroundMaterialDefines();
  77733. }
  77734. var scene = this.getScene();
  77735. var defines = subMesh._materialDefines;
  77736. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  77737. if (defines._renderId === scene.getRenderId()) {
  77738. return true;
  77739. }
  77740. }
  77741. var engine = scene.getEngine();
  77742. // Lights
  77743. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  77744. defines._needNormals = true;
  77745. // Textures
  77746. if (defines._areTexturesDirty) {
  77747. defines._needUVs = false;
  77748. if (scene.texturesEnabled) {
  77749. if (scene.getEngine().getCaps().textureLOD) {
  77750. defines.TEXTURELODSUPPORT = true;
  77751. }
  77752. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  77753. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  77754. return false;
  77755. }
  77756. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  77757. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  77758. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  77759. defines.OPACITYFRESNEL = this._opacityFresnel;
  77760. }
  77761. else {
  77762. defines.DIFFUSE = false;
  77763. defines.DIFFUSEHASALPHA = false;
  77764. defines.GAMMADIFFUSE = false;
  77765. defines.OPACITYFRESNEL = false;
  77766. }
  77767. var reflectionTexture = this._reflectionTexture;
  77768. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  77769. if (!reflectionTexture.isReadyOrNotBlocking()) {
  77770. return false;
  77771. }
  77772. defines.REFLECTION = true;
  77773. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  77774. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  77775. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  77776. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  77777. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  77778. defines.INVERTCUBICMAP = true;
  77779. }
  77780. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  77781. switch (reflectionTexture.coordinatesMode) {
  77782. case BABYLON.Texture.CUBIC_MODE:
  77783. case BABYLON.Texture.INVCUBIC_MODE:
  77784. defines.REFLECTIONMAP_CUBIC = true;
  77785. break;
  77786. case BABYLON.Texture.EXPLICIT_MODE:
  77787. defines.REFLECTIONMAP_EXPLICIT = true;
  77788. break;
  77789. case BABYLON.Texture.PLANAR_MODE:
  77790. defines.REFLECTIONMAP_PLANAR = true;
  77791. break;
  77792. case BABYLON.Texture.PROJECTION_MODE:
  77793. defines.REFLECTIONMAP_PROJECTION = true;
  77794. break;
  77795. case BABYLON.Texture.SKYBOX_MODE:
  77796. defines.REFLECTIONMAP_SKYBOX = true;
  77797. break;
  77798. case BABYLON.Texture.SPHERICAL_MODE:
  77799. defines.REFLECTIONMAP_SPHERICAL = true;
  77800. break;
  77801. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  77802. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  77803. break;
  77804. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  77805. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  77806. break;
  77807. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  77808. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  77809. break;
  77810. }
  77811. if (this.reflectionFresnel) {
  77812. defines.REFLECTIONFRESNEL = true;
  77813. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  77814. this._reflectionControls.x = this.reflectionAmount;
  77815. this._reflectionControls.y = this.reflectionReflectance0;
  77816. this._reflectionControls.z = this.reflectionReflectance90;
  77817. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  77818. }
  77819. else {
  77820. defines.REFLECTIONFRESNEL = false;
  77821. defines.REFLECTIONFALLOFF = false;
  77822. }
  77823. }
  77824. else {
  77825. defines.REFLECTION = false;
  77826. defines.REFLECTIONFALLOFF = false;
  77827. defines.REFLECTIONBLUR = false;
  77828. defines.REFLECTIONMAP_3D = false;
  77829. defines.REFLECTIONMAP_SPHERICAL = false;
  77830. defines.REFLECTIONMAP_PLANAR = false;
  77831. defines.REFLECTIONMAP_CUBIC = false;
  77832. defines.REFLECTIONMAP_PROJECTION = false;
  77833. defines.REFLECTIONMAP_SKYBOX = false;
  77834. defines.REFLECTIONMAP_EXPLICIT = false;
  77835. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  77836. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  77837. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  77838. defines.INVERTCUBICMAP = false;
  77839. defines.REFLECTIONMAP_OPPOSITEZ = false;
  77840. defines.LODINREFLECTIONALPHA = false;
  77841. defines.GAMMAREFLECTION = false;
  77842. }
  77843. }
  77844. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  77845. defines.USERGBCOLOR = this._useRGBColor;
  77846. defines.NOISE = this._enableNoise;
  77847. }
  77848. if (defines._areImageProcessingDirty) {
  77849. if (!this._imageProcessingConfiguration.isReady()) {
  77850. return false;
  77851. }
  77852. this._imageProcessingConfiguration.prepareDefines(defines);
  77853. }
  77854. // Misc.
  77855. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, defines);
  77856. // Values that need to be evaluated on every frame
  77857. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, false);
  77858. // Attribs
  77859. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  77860. if (mesh) {
  77861. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  77862. mesh.createNormals(true);
  77863. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  77864. }
  77865. }
  77866. }
  77867. // Get correct effect
  77868. if (defines.isDirty) {
  77869. defines.markAsProcessed();
  77870. scene.resetCachedMaterial();
  77871. // Fallbacks
  77872. var fallbacks = new BABYLON.EffectFallbacks();
  77873. if (defines.FOG) {
  77874. fallbacks.addFallback(0, "FOG");
  77875. }
  77876. if (defines.POINTSIZE) {
  77877. fallbacks.addFallback(1, "POINTSIZE");
  77878. }
  77879. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  77880. if (defines.NUM_BONE_INFLUENCERS > 0) {
  77881. fallbacks.addCPUSkinningFallback(0, mesh);
  77882. }
  77883. //Attributes
  77884. var attribs = [BABYLON.VertexBuffer.PositionKind];
  77885. if (defines.NORMAL) {
  77886. attribs.push(BABYLON.VertexBuffer.NormalKind);
  77887. }
  77888. if (defines.UV1) {
  77889. attribs.push(BABYLON.VertexBuffer.UVKind);
  77890. }
  77891. if (defines.UV2) {
  77892. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77893. }
  77894. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  77895. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  77896. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  77897. "vFogInfos", "vFogColor", "pointSize",
  77898. "vClipPlane", "mBones",
  77899. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  77900. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  77901. "shadowLevel", "alpha",
  77902. "vBackgroundCenter", "vReflectionControl",
  77903. "vDiffuseInfos", "diffuseMatrix",
  77904. ];
  77905. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  77906. var uniformBuffers = ["Material", "Scene"];
  77907. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  77908. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  77909. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  77910. uniformsNames: uniforms,
  77911. uniformBuffersNames: uniformBuffers,
  77912. samplers: samplers,
  77913. defines: defines,
  77914. maxSimultaneousLights: this._maxSimultaneousLights
  77915. });
  77916. var onCompiled = function (effect) {
  77917. if (_this.onCompiled) {
  77918. _this.onCompiled(effect);
  77919. }
  77920. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  77921. };
  77922. var join = defines.toString();
  77923. subMesh.setEffect(scene.getEngine().createEffect("background", {
  77924. attributes: attribs,
  77925. uniformsNames: uniforms,
  77926. uniformBuffersNames: uniformBuffers,
  77927. samplers: samplers,
  77928. defines: join,
  77929. fallbacks: fallbacks,
  77930. onCompiled: onCompiled,
  77931. onError: this.onError,
  77932. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  77933. }, engine), defines);
  77934. this.buildUniformLayout();
  77935. }
  77936. if (!subMesh.effect || !subMesh.effect.isReady()) {
  77937. return false;
  77938. }
  77939. defines._renderId = scene.getRenderId();
  77940. this._wasPreviouslyReady = true;
  77941. return true;
  77942. };
  77943. /**
  77944. * Build the uniform buffer used in the material.
  77945. */
  77946. BackgroundMaterial.prototype.buildUniformLayout = function () {
  77947. // Order is important !
  77948. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  77949. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  77950. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  77951. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  77952. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  77953. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  77954. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  77955. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  77956. this._uniformBuffer.addUniform("pointSize", 1);
  77957. this._uniformBuffer.addUniform("shadowLevel", 1);
  77958. this._uniformBuffer.addUniform("alpha", 1);
  77959. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  77960. this._uniformBuffer.addUniform("vReflectionControl", 4);
  77961. this._uniformBuffer.create();
  77962. };
  77963. /**
  77964. * Unbind the material.
  77965. */
  77966. BackgroundMaterial.prototype.unbind = function () {
  77967. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  77968. this._uniformBuffer.setTexture("diffuseSampler", null);
  77969. }
  77970. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  77971. this._uniformBuffer.setTexture("reflectionSampler", null);
  77972. }
  77973. _super.prototype.unbind.call(this);
  77974. };
  77975. /**
  77976. * Bind only the world matrix to the material.
  77977. * @param world The world matrix to bind.
  77978. */
  77979. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  77980. this._activeEffect.setMatrix("world", world);
  77981. };
  77982. /**
  77983. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  77984. * @param world The world matrix to bind.
  77985. * @param subMesh The submesh to bind for.
  77986. */
  77987. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  77988. var scene = this.getScene();
  77989. var defines = subMesh._materialDefines;
  77990. if (!defines) {
  77991. return;
  77992. }
  77993. var effect = subMesh.effect;
  77994. if (!effect) {
  77995. return;
  77996. }
  77997. this._activeEffect = effect;
  77998. // Matrices
  77999. this.bindOnlyWorldMatrix(world);
  78000. // Bones
  78001. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  78002. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  78003. if (mustRebind) {
  78004. this._uniformBuffer.bindToEffect(effect, "Material");
  78005. this.bindViewProjection(effect);
  78006. var reflectionTexture = this._reflectionTexture;
  78007. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  78008. // Texture uniforms
  78009. if (scene.texturesEnabled) {
  78010. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  78011. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  78012. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  78013. }
  78014. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  78015. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  78016. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  78017. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  78018. }
  78019. }
  78020. if (this.shadowLevel > 0) {
  78021. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  78022. }
  78023. this._uniformBuffer.updateFloat("alpha", this.alpha);
  78024. // Point size
  78025. if (this.pointsCloud) {
  78026. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  78027. }
  78028. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  78029. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  78030. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  78031. }
  78032. // Textures
  78033. if (scene.texturesEnabled) {
  78034. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  78035. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  78036. }
  78037. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  78038. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  78039. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  78040. }
  78041. else if (!defines.REFLECTIONBLUR) {
  78042. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  78043. }
  78044. else {
  78045. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  78046. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  78047. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  78048. }
  78049. if (defines.REFLECTIONFRESNEL) {
  78050. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  78051. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  78052. }
  78053. }
  78054. }
  78055. // Clip plane
  78056. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  78057. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  78058. }
  78059. if (mustRebind || !this.isFrozen) {
  78060. if (scene.lightsEnabled) {
  78061. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  78062. }
  78063. // View
  78064. this.bindView(effect);
  78065. // Fog
  78066. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  78067. // image processing
  78068. this._imageProcessingConfiguration.bind(this._activeEffect);
  78069. }
  78070. this._uniformBuffer.update();
  78071. this._afterBind(mesh);
  78072. };
  78073. /**
  78074. * Dispose the material.
  78075. * @forceDisposeEffect Force disposal of the associated effect.
  78076. * @forceDisposeTextures Force disposal of the associated textures.
  78077. */
  78078. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  78079. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  78080. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  78081. if (forceDisposeTextures) {
  78082. if (this.diffuseTexture) {
  78083. this.diffuseTexture.dispose();
  78084. }
  78085. if (this.reflectionTexture) {
  78086. this.reflectionTexture.dispose();
  78087. }
  78088. }
  78089. this._renderTargets.dispose();
  78090. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  78091. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  78092. }
  78093. _super.prototype.dispose.call(this, forceDisposeEffect);
  78094. };
  78095. /**
  78096. * Clones the material.
  78097. * @name The cloned name.
  78098. * @returns The cloned material.
  78099. */
  78100. BackgroundMaterial.prototype.clone = function (name) {
  78101. var _this = this;
  78102. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  78103. };
  78104. /**
  78105. * Serializes the current material to its JSON representation.
  78106. * @returns The JSON representation.
  78107. */
  78108. BackgroundMaterial.prototype.serialize = function () {
  78109. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  78110. serializationObject.customType = "BABYLON.BackgroundMaterial";
  78111. return serializationObject;
  78112. };
  78113. /**
  78114. * Gets the class name of the material
  78115. * @returns "BackgroundMaterial"
  78116. */
  78117. BackgroundMaterial.prototype.getClassName = function () {
  78118. return "BackgroundMaterial";
  78119. };
  78120. /**
  78121. * Parse a JSON input to create back a background material.
  78122. * @param source
  78123. * @param scene
  78124. * @param rootUrl
  78125. * @returns the instantiated BackgroundMaterial.
  78126. */
  78127. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  78128. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  78129. };
  78130. /**
  78131. * Standard reflectance value at parallel view angle.
  78132. */
  78133. BackgroundMaterial.standardReflectance0 = 0.05;
  78134. /**
  78135. * Standard reflectance value at grazing angle.
  78136. */
  78137. BackgroundMaterial.standardReflectance90 = 0.5;
  78138. __decorate([
  78139. BABYLON.serializeAsColor3()
  78140. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  78141. __decorate([
  78142. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  78143. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  78144. __decorate([
  78145. BABYLON.serialize()
  78146. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  78147. __decorate([
  78148. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  78149. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  78150. __decorate([
  78151. BABYLON.serializeAsColor3()
  78152. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  78153. __decorate([
  78154. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  78155. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  78156. __decorate([
  78157. BABYLON.serialize()
  78158. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  78159. __decorate([
  78160. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  78161. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  78162. __decorate([
  78163. BABYLON.serializeAsColor3()
  78164. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  78165. __decorate([
  78166. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  78167. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  78168. __decorate([
  78169. BABYLON.serialize()
  78170. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  78171. __decorate([
  78172. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  78173. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  78174. __decorate([
  78175. BABYLON.serializeAsTexture()
  78176. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  78177. __decorate([
  78178. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78179. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  78180. __decorate([
  78181. BABYLON.serialize()
  78182. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  78183. __decorate([
  78184. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78185. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  78186. __decorate([
  78187. BABYLON.serializeAsTexture()
  78188. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  78189. __decorate([
  78190. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78191. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  78192. __decorate([
  78193. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78194. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  78195. __decorate([
  78196. BABYLON.serialize()
  78197. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  78198. __decorate([
  78199. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78200. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  78201. __decorate([
  78202. BABYLON.serialize()
  78203. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  78204. __decorate([
  78205. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78206. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  78207. __decorate([
  78208. BABYLON.serializeAsVector3()
  78209. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  78210. __decorate([
  78211. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78212. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  78213. __decorate([
  78214. BABYLON.serialize()
  78215. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  78216. __decorate([
  78217. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78218. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  78219. __decorate([
  78220. BABYLON.serialize()
  78221. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  78222. __decorate([
  78223. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78224. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  78225. __decorate([
  78226. BABYLON.serialize()
  78227. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  78228. __decorate([
  78229. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78230. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  78231. __decorate([
  78232. BABYLON.serialize()
  78233. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  78234. __decorate([
  78235. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78236. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  78237. __decorate([
  78238. BABYLON.serialize()
  78239. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  78240. __decorate([
  78241. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78242. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  78243. __decorate([
  78244. BABYLON.serialize()
  78245. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  78246. __decorate([
  78247. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78248. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  78249. __decorate([
  78250. BABYLON.serialize()
  78251. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  78252. __decorate([
  78253. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78254. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  78255. __decorate([
  78256. BABYLON.serialize()
  78257. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  78258. __decorate([
  78259. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78260. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  78261. __decorate([
  78262. BABYLON.serialize()
  78263. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  78264. __decorate([
  78265. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78266. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  78267. __decorate([
  78268. BABYLON.serializeAsImageProcessingConfiguration()
  78269. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  78270. return BackgroundMaterial;
  78271. }(BABYLON.PushMaterial));
  78272. BABYLON.BackgroundMaterial = BackgroundMaterial;
  78273. })(BABYLON || (BABYLON = {}));
  78274. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  78275. var __assign = (this && this.__assign) || Object.assign || function(t) {
  78276. for (var s, i = 1, n = arguments.length; i < n; i++) {
  78277. s = arguments[i];
  78278. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  78279. t[p] = s[p];
  78280. }
  78281. return t;
  78282. };
  78283. var BABYLON;
  78284. (function (BABYLON) {
  78285. /**
  78286. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  78287. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  78288. * It also helps with the default setup of your imageProcessing configuration.
  78289. */
  78290. var EnvironmentHelper = /** @class */ (function () {
  78291. /**
  78292. * constructor
  78293. * @param options
  78294. * @param scene The scene to add the material to
  78295. */
  78296. function EnvironmentHelper(options, scene) {
  78297. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  78298. this._scene = scene;
  78299. this._setupBackground();
  78300. this._setupImageProcessing();
  78301. }
  78302. /**
  78303. * Creates the default options for the helper.
  78304. */
  78305. EnvironmentHelper._getDefaultOptions = function () {
  78306. return {
  78307. createGround: true,
  78308. groundSize: 15,
  78309. groundTexture: this._groundTextureCDNUrl,
  78310. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  78311. groundOpacity: 0.9,
  78312. enableGroundShadow: true,
  78313. groundShadowLevel: 0.5,
  78314. enableGroundMirror: false,
  78315. groundMirrorSizeRatio: 0.3,
  78316. groundMirrorBlurKernel: 64,
  78317. groundMirrorAmount: 1,
  78318. groundMirrorFresnelWeight: 1,
  78319. groundMirrorFallOffDistance: 0,
  78320. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  78321. createSkybox: true,
  78322. skyboxSize: 20,
  78323. skyboxTexture: this._skyboxTextureCDNUrl,
  78324. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  78325. backgroundYRotation: 0,
  78326. sizeAuto: true,
  78327. rootPosition: BABYLON.Vector3.Zero(),
  78328. setupImageProcessing: true,
  78329. environmentTexture: this._environmentTextureCDNUrl,
  78330. cameraExposure: 0.8,
  78331. cameraContrast: 1.2,
  78332. toneMappingEnabled: true,
  78333. };
  78334. };
  78335. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  78336. /**
  78337. * Gets the root mesh created by the helper.
  78338. */
  78339. get: function () {
  78340. return this._rootMesh;
  78341. },
  78342. enumerable: true,
  78343. configurable: true
  78344. });
  78345. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  78346. /**
  78347. * Gets the skybox created by the helper.
  78348. */
  78349. get: function () {
  78350. return this._skybox;
  78351. },
  78352. enumerable: true,
  78353. configurable: true
  78354. });
  78355. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  78356. /**
  78357. * Gets the skybox texture created by the helper.
  78358. */
  78359. get: function () {
  78360. return this._skyboxTexture;
  78361. },
  78362. enumerable: true,
  78363. configurable: true
  78364. });
  78365. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  78366. /**
  78367. * Gets the skybox material created by the helper.
  78368. */
  78369. get: function () {
  78370. return this._skyboxMaterial;
  78371. },
  78372. enumerable: true,
  78373. configurable: true
  78374. });
  78375. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  78376. /**
  78377. * Gets the ground mesh created by the helper.
  78378. */
  78379. get: function () {
  78380. return this._ground;
  78381. },
  78382. enumerable: true,
  78383. configurable: true
  78384. });
  78385. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  78386. /**
  78387. * Gets the ground texture created by the helper.
  78388. */
  78389. get: function () {
  78390. return this._groundTexture;
  78391. },
  78392. enumerable: true,
  78393. configurable: true
  78394. });
  78395. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  78396. /**
  78397. * Gets the ground mirror created by the helper.
  78398. */
  78399. get: function () {
  78400. return this._groundMirror;
  78401. },
  78402. enumerable: true,
  78403. configurable: true
  78404. });
  78405. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  78406. /**
  78407. * Gets the ground mirror render list to helps pushing the meshes
  78408. * you wish in the ground reflection.
  78409. */
  78410. get: function () {
  78411. if (this._groundMirror) {
  78412. return this._groundMirror.renderList;
  78413. }
  78414. return null;
  78415. },
  78416. enumerable: true,
  78417. configurable: true
  78418. });
  78419. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  78420. /**
  78421. * Gets the ground material created by the helper.
  78422. */
  78423. get: function () {
  78424. return this._groundMaterial;
  78425. },
  78426. enumerable: true,
  78427. configurable: true
  78428. });
  78429. /**
  78430. * Updates the background according to the new options
  78431. * @param options
  78432. */
  78433. EnvironmentHelper.prototype.updateOptions = function (options) {
  78434. var newOptions = __assign({}, this._options, options);
  78435. if (this._ground && !newOptions.createGround) {
  78436. this._ground.dispose();
  78437. this._ground = null;
  78438. }
  78439. if (this._groundMaterial && !newOptions.createGround) {
  78440. this._groundMaterial.dispose();
  78441. this._groundMaterial = null;
  78442. }
  78443. if (this._options.groundTexture && !newOptions.groundTexture && this._groundTexture) {
  78444. this._groundTexture.dispose();
  78445. this._groundTexture = null;
  78446. }
  78447. if (this._skybox && !newOptions.createSkybox) {
  78448. this._skybox.dispose();
  78449. this._skybox = null;
  78450. }
  78451. if (this._skyboxMaterial && !newOptions.createSkybox) {
  78452. this._skyboxMaterial.dispose();
  78453. this._skyboxMaterial = null;
  78454. }
  78455. if (this._options.skyboxTexture && !newOptions.skyboxTexture && this._skyboxTexture) {
  78456. this._skyboxTexture.dispose();
  78457. this._skyboxTexture = null;
  78458. }
  78459. if (this._groundMirror && !newOptions.enableGroundMirror) {
  78460. this._groundMirror.dispose();
  78461. this._groundMirror = null;
  78462. }
  78463. if (this._options.environmentTexture && !newOptions.environmentTexture && this._scene.environmentTexture) {
  78464. this._scene.environmentTexture.dispose();
  78465. }
  78466. this._options = newOptions;
  78467. this._setupBackground();
  78468. this._setupImageProcessing();
  78469. };
  78470. /**
  78471. * Sets the primary color of all the available elements.
  78472. * @param color
  78473. */
  78474. EnvironmentHelper.prototype.setMainColor = function (color) {
  78475. if (this.groundMaterial) {
  78476. this.groundMaterial.primaryColor = color;
  78477. }
  78478. if (this.skyboxMaterial) {
  78479. this.skyboxMaterial.primaryColor = color;
  78480. }
  78481. if (this.groundMirror) {
  78482. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  78483. }
  78484. };
  78485. /**
  78486. * Setup the image processing according to the specified options.
  78487. */
  78488. EnvironmentHelper.prototype._setupImageProcessing = function () {
  78489. if (this._options.setupImageProcessing) {
  78490. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  78491. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  78492. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  78493. this._setupEnvironmentTexture();
  78494. }
  78495. };
  78496. /**
  78497. * Setup the environment texture according to the specified options.
  78498. */
  78499. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  78500. if (this._scene.environmentTexture) {
  78501. return;
  78502. }
  78503. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  78504. this._scene.environmentTexture = this._options.environmentTexture;
  78505. return;
  78506. }
  78507. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  78508. this._scene.environmentTexture = environmentTexture;
  78509. };
  78510. /**
  78511. * Setup the background according to the specified options.
  78512. */
  78513. EnvironmentHelper.prototype._setupBackground = function () {
  78514. if (!this._rootMesh) {
  78515. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  78516. }
  78517. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  78518. var sceneSize = this._getSceneSize();
  78519. if (this._options.createGround) {
  78520. this._setupGround(sceneSize);
  78521. this._setupGroundMaterial();
  78522. this._setupGroundDiffuseTexture();
  78523. if (this._options.enableGroundMirror) {
  78524. this._setupGroundMirrorTexture(sceneSize);
  78525. }
  78526. this._setupMirrorInGroundMaterial();
  78527. }
  78528. if (this._options.createSkybox) {
  78529. this._setupSkybox(sceneSize);
  78530. this._setupSkyboxMaterial();
  78531. this._setupSkyboxReflectionTexture();
  78532. }
  78533. this._rootMesh.position.x = sceneSize.rootPosition.x;
  78534. this._rootMesh.position.z = sceneSize.rootPosition.z;
  78535. this._rootMesh.position.y = sceneSize.rootPosition.y;
  78536. };
  78537. /**
  78538. * Get the scene sizes according to the setup.
  78539. */
  78540. EnvironmentHelper.prototype._getSceneSize = function () {
  78541. var groundSize = this._options.groundSize;
  78542. var skyboxSize = this._options.skyboxSize;
  78543. var rootPosition = this._options.rootPosition;
  78544. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  78545. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  78546. }
  78547. var sceneExtends = this._scene.getWorldExtends();
  78548. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  78549. var bias = 0.0001;
  78550. if (this._options.sizeAuto) {
  78551. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  78552. this._scene.activeCamera.upperRadiusLimit) {
  78553. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  78554. }
  78555. if (this._scene.activeCamera) {
  78556. bias = (this._scene.activeCamera.maxZ - this._scene.activeCamera.minZ) / 10000;
  78557. }
  78558. var sceneDiagonalLenght = sceneDiagonal.length();
  78559. if (sceneDiagonalLenght > groundSize) {
  78560. groundSize = sceneDiagonalLenght * 2;
  78561. }
  78562. // 10 % bigger.
  78563. groundSize *= 1.1;
  78564. skyboxSize *= 1.5;
  78565. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  78566. rootPosition.y = sceneExtends.min.y - bias;
  78567. }
  78568. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  78569. };
  78570. /**
  78571. * Setup the ground according to the specified options.
  78572. */
  78573. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  78574. var _this = this;
  78575. if (!this._ground) {
  78576. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  78577. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  78578. this._ground.parent = this._rootMesh;
  78579. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  78580. }
  78581. this._ground.receiveShadows = this._options.enableGroundShadow;
  78582. };
  78583. /**
  78584. * Setup the ground material according to the specified options.
  78585. */
  78586. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  78587. if (!this._groundMaterial) {
  78588. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  78589. }
  78590. this._groundMaterial.alpha = this._options.groundOpacity;
  78591. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  78592. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  78593. this._groundMaterial.primaryLevel = 1;
  78594. this._groundMaterial.primaryColor = this._options.groundColor;
  78595. this._groundMaterial.secondaryLevel = 0;
  78596. this._groundMaterial.tertiaryLevel = 0;
  78597. this._groundMaterial.useRGBColor = false;
  78598. this._groundMaterial.enableNoise = true;
  78599. if (this._ground) {
  78600. this._ground.material = this._groundMaterial;
  78601. }
  78602. };
  78603. /**
  78604. * Setup the ground diffuse texture according to the specified options.
  78605. */
  78606. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  78607. if (!this._groundMaterial) {
  78608. return;
  78609. }
  78610. if (this._groundTexture) {
  78611. return;
  78612. }
  78613. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  78614. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  78615. return;
  78616. }
  78617. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  78618. diffuseTexture.gammaSpace = false;
  78619. diffuseTexture.hasAlpha = true;
  78620. this._groundMaterial.diffuseTexture = diffuseTexture;
  78621. };
  78622. /**
  78623. * Setup the ground mirror texture according to the specified options.
  78624. */
  78625. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  78626. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78627. if (!this._groundMirror) {
  78628. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  78629. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  78630. this._groundMirror.anisotropicFilteringLevel = 1;
  78631. this._groundMirror.wrapU = wrapping;
  78632. this._groundMirror.wrapV = wrapping;
  78633. this._groundMirror.gammaSpace = false;
  78634. if (this._groundMirror.renderList) {
  78635. for (var i = 0; i < this._scene.meshes.length; i++) {
  78636. var mesh = this._scene.meshes[i];
  78637. if (mesh !== this._ground &&
  78638. mesh !== this._skybox &&
  78639. mesh !== this._rootMesh) {
  78640. this._groundMirror.renderList.push(mesh);
  78641. }
  78642. }
  78643. }
  78644. }
  78645. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  78646. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  78647. };
  78648. /**
  78649. * Setup the ground to receive the mirror texture.
  78650. */
  78651. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  78652. if (this._groundMaterial) {
  78653. this._groundMaterial.reflectionTexture = this._groundMirror;
  78654. this._groundMaterial.reflectionFresnel = true;
  78655. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  78656. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  78657. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  78658. }
  78659. };
  78660. /**
  78661. * Setup the skybox according to the specified options.
  78662. */
  78663. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  78664. var _this = this;
  78665. if (!this._skybox) {
  78666. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  78667. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  78668. }
  78669. this._skybox.parent = this._rootMesh;
  78670. };
  78671. /**
  78672. * Setup the skybox material according to the specified options.
  78673. */
  78674. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  78675. if (!this._skybox) {
  78676. return;
  78677. }
  78678. if (!this._skyboxMaterial) {
  78679. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  78680. }
  78681. this._skyboxMaterial.useRGBColor = false;
  78682. this._skyboxMaterial.primaryLevel = 1;
  78683. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  78684. this._skyboxMaterial.secondaryLevel = 0;
  78685. this._skyboxMaterial.tertiaryLevel = 0;
  78686. this._skyboxMaterial.enableNoise = true;
  78687. this._skybox.material = this._skyboxMaterial;
  78688. };
  78689. /**
  78690. * Setup the skybox reflection texture according to the specified options.
  78691. */
  78692. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  78693. if (!this._skyboxMaterial) {
  78694. return;
  78695. }
  78696. if (this._skyboxTexture) {
  78697. return;
  78698. }
  78699. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  78700. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  78701. return;
  78702. }
  78703. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  78704. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  78705. this._skyboxTexture.gammaSpace = false;
  78706. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  78707. };
  78708. /**
  78709. * Dispose all the elements created by the Helper.
  78710. */
  78711. EnvironmentHelper.prototype.dispose = function () {
  78712. if (this._groundMaterial) {
  78713. this._groundMaterial.dispose(true, true);
  78714. }
  78715. if (this._skyboxMaterial) {
  78716. this._skyboxMaterial.dispose(true, true);
  78717. }
  78718. this._rootMesh.dispose(false);
  78719. };
  78720. /**
  78721. * Default ground texture URL.
  78722. */
  78723. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  78724. /**
  78725. * Default skybox texture URL.
  78726. */
  78727. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  78728. /**
  78729. * Default environment texture URL.
  78730. */
  78731. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  78732. return EnvironmentHelper;
  78733. }());
  78734. BABYLON.EnvironmentHelper = EnvironmentHelper;
  78735. })(BABYLON || (BABYLON = {}));
  78736. //# sourceMappingURL=babylon.environmentHelper.js.map
  78737. 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}"};
  78738. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nvec3 dither(vec2 seed,vec3 color) {\nfloat rand=getRand(seed);\ncolor.rgb+=mix(-0.5/255.0,0.5/255.0,rand);\nreturn color;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*KERNEL_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*KERNEL_WEIGHT{X};\n#endif","kernelBlurFragment2":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*KERNEL_DEP_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*KERNEL_DEP_WEIGHT{X};\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  78739. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  78740. var BABYLON;
  78741. (function (BABYLON) {
  78742. var GridMaterialDefines = /** @class */ (function (_super) {
  78743. __extends(GridMaterialDefines, _super);
  78744. function GridMaterialDefines() {
  78745. var _this = _super.call(this) || this;
  78746. _this.TRANSPARENT = false;
  78747. _this.FOG = false;
  78748. _this.PREMULTIPLYALPHA = false;
  78749. _this.rebuild();
  78750. return _this;
  78751. }
  78752. return GridMaterialDefines;
  78753. }(BABYLON.MaterialDefines));
  78754. /**
  78755. * The grid materials allows you to wrap any shape with a grid.
  78756. * Colors are customizable.
  78757. */
  78758. var GridMaterial = /** @class */ (function (_super) {
  78759. __extends(GridMaterial, _super);
  78760. /**
  78761. * constructor
  78762. * @param name The name given to the material in order to identify it afterwards.
  78763. * @param scene The scene the material is used in.
  78764. */
  78765. function GridMaterial(name, scene) {
  78766. var _this = _super.call(this, name, scene) || this;
  78767. /**
  78768. * Main color of the grid (e.g. between lines)
  78769. */
  78770. _this.mainColor = BABYLON.Color3.Black();
  78771. /**
  78772. * Color of the grid lines.
  78773. */
  78774. _this.lineColor = BABYLON.Color3.Teal();
  78775. /**
  78776. * The scale of the grid compared to unit.
  78777. */
  78778. _this.gridRatio = 1.0;
  78779. /**
  78780. * Allows setting an offset for the grid lines.
  78781. */
  78782. _this.gridOffset = BABYLON.Vector3.Zero();
  78783. /**
  78784. * The frequency of thicker lines.
  78785. */
  78786. _this.majorUnitFrequency = 10;
  78787. /**
  78788. * The visibility of minor units in the grid.
  78789. */
  78790. _this.minorUnitVisibility = 0.33;
  78791. /**
  78792. * The grid opacity outside of the lines.
  78793. */
  78794. _this.opacity = 1.0;
  78795. /**
  78796. * Determine RBG output is premultiplied by alpha value.
  78797. */
  78798. _this.preMultiplyAlpha = false;
  78799. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  78800. return _this;
  78801. }
  78802. /**
  78803. * Returns wehter or not the grid requires alpha blending.
  78804. */
  78805. GridMaterial.prototype.needAlphaBlending = function () {
  78806. return this.opacity < 1.0;
  78807. };
  78808. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  78809. return this.needAlphaBlending();
  78810. };
  78811. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  78812. if (this.isFrozen) {
  78813. if (this._wasPreviouslyReady && subMesh.effect) {
  78814. return true;
  78815. }
  78816. }
  78817. if (!subMesh._materialDefines) {
  78818. subMesh._materialDefines = new GridMaterialDefines();
  78819. }
  78820. var defines = subMesh._materialDefines;
  78821. var scene = this.getScene();
  78822. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  78823. if (this._renderId === scene.getRenderId()) {
  78824. return true;
  78825. }
  78826. }
  78827. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  78828. defines.TRANSPARENT = !defines.TRANSPARENT;
  78829. defines.markAsUnprocessed();
  78830. }
  78831. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  78832. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  78833. defines.markAsUnprocessed();
  78834. }
  78835. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines);
  78836. // Get correct effect
  78837. if (defines.isDirty) {
  78838. defines.markAsProcessed();
  78839. scene.resetCachedMaterial();
  78840. // Attributes
  78841. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  78842. // Defines
  78843. var join = defines.toString();
  78844. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  78845. }
  78846. if (!subMesh.effect || !subMesh.effect.isReady()) {
  78847. return false;
  78848. }
  78849. this._renderId = scene.getRenderId();
  78850. this._wasPreviouslyReady = true;
  78851. return true;
  78852. };
  78853. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  78854. var scene = this.getScene();
  78855. var defines = subMesh._materialDefines;
  78856. if (!defines) {
  78857. return;
  78858. }
  78859. var effect = subMesh.effect;
  78860. if (!effect) {
  78861. return;
  78862. }
  78863. this._activeEffect = effect;
  78864. // Matrices
  78865. this.bindOnlyWorldMatrix(world);
  78866. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  78867. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  78868. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  78869. // Uniforms
  78870. if (this._mustRebind(scene, effect)) {
  78871. this._activeEffect.setColor3("mainColor", this.mainColor);
  78872. this._activeEffect.setColor3("lineColor", this.lineColor);
  78873. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  78874. this._gridControl.x = this.gridRatio;
  78875. this._gridControl.y = Math.round(this.majorUnitFrequency);
  78876. this._gridControl.z = this.minorUnitVisibility;
  78877. this._gridControl.w = this.opacity;
  78878. this._activeEffect.setVector4("gridControl", this._gridControl);
  78879. }
  78880. // Fog
  78881. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  78882. this._afterBind(mesh, this._activeEffect);
  78883. };
  78884. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  78885. _super.prototype.dispose.call(this, forceDisposeEffect);
  78886. };
  78887. GridMaterial.prototype.clone = function (name) {
  78888. var _this = this;
  78889. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  78890. };
  78891. GridMaterial.prototype.serialize = function () {
  78892. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  78893. serializationObject.customType = "BABYLON.GridMaterial";
  78894. return serializationObject;
  78895. };
  78896. GridMaterial.prototype.getClassName = function () {
  78897. return "GridMaterial";
  78898. };
  78899. GridMaterial.Parse = function (source, scene, rootUrl) {
  78900. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  78901. };
  78902. __decorate([
  78903. BABYLON.serializeAsColor3()
  78904. ], GridMaterial.prototype, "mainColor", void 0);
  78905. __decorate([
  78906. BABYLON.serializeAsColor3()
  78907. ], GridMaterial.prototype, "lineColor", void 0);
  78908. __decorate([
  78909. BABYLON.serialize()
  78910. ], GridMaterial.prototype, "gridRatio", void 0);
  78911. __decorate([
  78912. BABYLON.serializeAsColor3()
  78913. ], GridMaterial.prototype, "gridOffset", void 0);
  78914. __decorate([
  78915. BABYLON.serialize()
  78916. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  78917. __decorate([
  78918. BABYLON.serialize()
  78919. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  78920. __decorate([
  78921. BABYLON.serialize()
  78922. ], GridMaterial.prototype, "opacity", void 0);
  78923. __decorate([
  78924. BABYLON.serialize()
  78925. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  78926. return GridMaterial;
  78927. }(BABYLON.PushMaterial));
  78928. BABYLON.GridMaterial = GridMaterial;
  78929. })(BABYLON || (BABYLON = {}));
  78930. //# sourceMappingURL=babylon.gridmaterial.js.map
  78931. 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}";
  78932. 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}";
  78933. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  78934. var BABYLON;
  78935. (function (BABYLON) {
  78936. var GLTFLoaderCoordinateSystemMode;
  78937. (function (GLTFLoaderCoordinateSystemMode) {
  78938. // Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene (scene.useRightHandedSystem).
  78939. // NOTE: When scene.useRightHandedSystem is false, an additional transform will be added to the root to transform the data from right-handed to left-handed.
  78940. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  78941. // The glTF right-handed data is not transformed in any form and is loaded directly.
  78942. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["PASS_THROUGH"] = 1] = "PASS_THROUGH";
  78943. // Sets the useRightHandedSystem flag on the scene.
  78944. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 2] = "FORCE_RIGHT_HANDED";
  78945. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  78946. var GLTFFileLoader = /** @class */ (function () {
  78947. function GLTFFileLoader() {
  78948. // V2 options
  78949. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  78950. this.compileMaterials = false;
  78951. this.compileShadowGenerators = false;
  78952. this.useClipPlane = false;
  78953. this.name = "gltf";
  78954. this.extensions = {
  78955. ".gltf": { isBinary: false },
  78956. ".glb": { isBinary: true }
  78957. };
  78958. }
  78959. GLTFFileLoader.prototype.dispose = function () {
  78960. if (this._loader) {
  78961. this._loader.dispose();
  78962. }
  78963. };
  78964. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  78965. try {
  78966. var loaderData = GLTFFileLoader._parse(data);
  78967. if (this.onParsed) {
  78968. this.onParsed(loaderData);
  78969. }
  78970. this._loader = this._getLoader(loaderData);
  78971. this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  78972. }
  78973. catch (e) {
  78974. onError(e.message);
  78975. }
  78976. };
  78977. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  78978. try {
  78979. var loaderData = GLTFFileLoader._parse(data);
  78980. if (this.onParsed) {
  78981. this.onParsed(loaderData);
  78982. }
  78983. this._loader = this._getLoader(loaderData);
  78984. this._loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  78985. }
  78986. catch (e) {
  78987. onError(e.message);
  78988. }
  78989. };
  78990. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  78991. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  78992. };
  78993. GLTFFileLoader.prototype.createPlugin = function () {
  78994. return new GLTFFileLoader();
  78995. };
  78996. GLTFFileLoader._parse = function (data) {
  78997. if (data instanceof ArrayBuffer) {
  78998. return GLTFFileLoader._parseBinary(data);
  78999. }
  79000. return {
  79001. json: JSON.parse(data),
  79002. bin: null
  79003. };
  79004. };
  79005. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  79006. var loaderVersion = { major: 2, minor: 0 };
  79007. var asset = loaderData.json.asset || {};
  79008. var version = GLTFFileLoader._parseVersion(asset.version);
  79009. if (!version) {
  79010. throw new Error("Invalid version: " + asset.version);
  79011. }
  79012. if (asset.minVersion !== undefined) {
  79013. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  79014. if (!minVersion) {
  79015. throw new Error("Invalid minimum version: " + asset.minVersion);
  79016. }
  79017. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  79018. throw new Error("Incompatible minimum version: " + asset.minVersion);
  79019. }
  79020. }
  79021. var createLoaders = {
  79022. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  79023. 2: GLTFFileLoader.CreateGLTFLoaderV2
  79024. };
  79025. var createLoader = createLoaders[version.major];
  79026. if (!createLoader) {
  79027. throw new Error("Unsupported version: " + asset.version);
  79028. }
  79029. return createLoader(this);
  79030. };
  79031. GLTFFileLoader._parseBinary = function (data) {
  79032. var Binary = {
  79033. Magic: 0x46546C67
  79034. };
  79035. var binaryReader = new BinaryReader(data);
  79036. var magic = binaryReader.readUint32();
  79037. if (magic !== Binary.Magic) {
  79038. throw new Error("Unexpected magic: " + magic);
  79039. }
  79040. var version = binaryReader.readUint32();
  79041. switch (version) {
  79042. case 1: return GLTFFileLoader._parseV1(binaryReader);
  79043. case 2: return GLTFFileLoader._parseV2(binaryReader);
  79044. }
  79045. throw new Error("Unsupported version: " + version);
  79046. };
  79047. GLTFFileLoader._parseV1 = function (binaryReader) {
  79048. var ContentFormat = {
  79049. JSON: 0
  79050. };
  79051. var length = binaryReader.readUint32();
  79052. if (length != binaryReader.getLength()) {
  79053. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  79054. }
  79055. var contentLength = binaryReader.readUint32();
  79056. var contentFormat = binaryReader.readUint32();
  79057. var content;
  79058. switch (contentFormat) {
  79059. case ContentFormat.JSON: {
  79060. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  79061. break;
  79062. }
  79063. default: {
  79064. throw new Error("Unexpected content format: " + contentFormat);
  79065. }
  79066. }
  79067. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  79068. var body = binaryReader.readUint8Array(bytesRemaining);
  79069. return {
  79070. json: content,
  79071. bin: body
  79072. };
  79073. };
  79074. GLTFFileLoader._parseV2 = function (binaryReader) {
  79075. var ChunkFormat = {
  79076. JSON: 0x4E4F534A,
  79077. BIN: 0x004E4942
  79078. };
  79079. var length = binaryReader.readUint32();
  79080. if (length !== binaryReader.getLength()) {
  79081. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  79082. }
  79083. // JSON chunk
  79084. var chunkLength = binaryReader.readUint32();
  79085. var chunkFormat = binaryReader.readUint32();
  79086. if (chunkFormat !== ChunkFormat.JSON) {
  79087. throw new Error("First chunk format is not JSON");
  79088. }
  79089. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  79090. // Look for BIN chunk
  79091. var bin = null;
  79092. while (binaryReader.getPosition() < binaryReader.getLength()) {
  79093. var chunkLength_1 = binaryReader.readUint32();
  79094. var chunkFormat_1 = binaryReader.readUint32();
  79095. switch (chunkFormat_1) {
  79096. case ChunkFormat.JSON: {
  79097. throw new Error("Unexpected JSON chunk");
  79098. }
  79099. case ChunkFormat.BIN: {
  79100. bin = binaryReader.readUint8Array(chunkLength_1);
  79101. break;
  79102. }
  79103. default: {
  79104. // ignore unrecognized chunkFormat
  79105. binaryReader.skipBytes(chunkLength_1);
  79106. break;
  79107. }
  79108. }
  79109. }
  79110. return {
  79111. json: json,
  79112. bin: bin
  79113. };
  79114. };
  79115. GLTFFileLoader._parseVersion = function (version) {
  79116. if (version === "1.0" || version === "1.0.1") {
  79117. return {
  79118. major: 1,
  79119. minor: 0
  79120. };
  79121. }
  79122. var match = (version + "").match(/^(\d+)\.(\d+)/);
  79123. if (!match) {
  79124. return null;
  79125. }
  79126. return {
  79127. major: parseInt(match[1]),
  79128. minor: parseInt(match[2])
  79129. };
  79130. };
  79131. GLTFFileLoader._compareVersion = function (a, b) {
  79132. if (a.major > b.major)
  79133. return 1;
  79134. if (a.major < b.major)
  79135. return -1;
  79136. if (a.minor > b.minor)
  79137. return 1;
  79138. if (a.minor < b.minor)
  79139. return -1;
  79140. return 0;
  79141. };
  79142. GLTFFileLoader._decodeBufferToText = function (buffer) {
  79143. var result = "";
  79144. var length = buffer.byteLength;
  79145. for (var i = 0; i < length; i++) {
  79146. result += String.fromCharCode(buffer[i]);
  79147. }
  79148. return result;
  79149. };
  79150. // V1 options
  79151. GLTFFileLoader.HomogeneousCoordinates = false;
  79152. GLTFFileLoader.IncrementalLoading = true;
  79153. return GLTFFileLoader;
  79154. }());
  79155. BABYLON.GLTFFileLoader = GLTFFileLoader;
  79156. var BinaryReader = /** @class */ (function () {
  79157. function BinaryReader(arrayBuffer) {
  79158. this._arrayBuffer = arrayBuffer;
  79159. this._dataView = new DataView(arrayBuffer);
  79160. this._byteOffset = 0;
  79161. }
  79162. BinaryReader.prototype.getPosition = function () {
  79163. return this._byteOffset;
  79164. };
  79165. BinaryReader.prototype.getLength = function () {
  79166. return this._arrayBuffer.byteLength;
  79167. };
  79168. BinaryReader.prototype.readUint32 = function () {
  79169. var value = this._dataView.getUint32(this._byteOffset, true);
  79170. this._byteOffset += 4;
  79171. return value;
  79172. };
  79173. BinaryReader.prototype.readUint8Array = function (length) {
  79174. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  79175. this._byteOffset += length;
  79176. return value;
  79177. };
  79178. BinaryReader.prototype.skipBytes = function (length) {
  79179. this._byteOffset += length;
  79180. };
  79181. return BinaryReader;
  79182. }());
  79183. if (BABYLON.SceneLoader) {
  79184. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  79185. }
  79186. })(BABYLON || (BABYLON = {}));
  79187. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  79188. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  79189. var BABYLON;
  79190. (function (BABYLON) {
  79191. var GLTF1;
  79192. (function (GLTF1) {
  79193. /**
  79194. * Enums
  79195. */
  79196. var EComponentType;
  79197. (function (EComponentType) {
  79198. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  79199. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  79200. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  79201. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  79202. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  79203. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  79204. var EShaderType;
  79205. (function (EShaderType) {
  79206. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  79207. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  79208. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  79209. var EParameterType;
  79210. (function (EParameterType) {
  79211. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  79212. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  79213. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  79214. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  79215. EParameterType[EParameterType["INT"] = 5124] = "INT";
  79216. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  79217. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  79218. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  79219. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  79220. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  79221. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  79222. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  79223. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  79224. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  79225. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  79226. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  79227. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  79228. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  79229. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  79230. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  79231. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  79232. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  79233. var ETextureWrapMode;
  79234. (function (ETextureWrapMode) {
  79235. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  79236. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  79237. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  79238. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  79239. var ETextureFilterType;
  79240. (function (ETextureFilterType) {
  79241. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  79242. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  79243. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  79244. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  79245. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  79246. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  79247. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  79248. var ETextureFormat;
  79249. (function (ETextureFormat) {
  79250. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  79251. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  79252. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  79253. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  79254. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  79255. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  79256. var ECullingType;
  79257. (function (ECullingType) {
  79258. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  79259. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  79260. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  79261. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  79262. var EBlendingFunction;
  79263. (function (EBlendingFunction) {
  79264. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  79265. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  79266. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  79267. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  79268. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  79269. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  79270. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  79271. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  79272. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  79273. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  79274. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  79275. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  79276. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  79277. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  79278. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  79279. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  79280. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  79281. })(BABYLON || (BABYLON = {}));
  79282. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  79283. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  79284. var BABYLON;
  79285. (function (BABYLON) {
  79286. var GLTF1;
  79287. (function (GLTF1) {
  79288. /**
  79289. * Tokenizer. Used for shaders compatibility
  79290. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  79291. */
  79292. var ETokenType;
  79293. (function (ETokenType) {
  79294. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  79295. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  79296. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  79297. })(ETokenType || (ETokenType = {}));
  79298. var Tokenizer = /** @class */ (function () {
  79299. function Tokenizer(toParse) {
  79300. this._pos = 0;
  79301. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  79302. this._toParse = toParse;
  79303. this._maxPos = toParse.length;
  79304. }
  79305. Tokenizer.prototype.getNextToken = function () {
  79306. if (this.isEnd())
  79307. return ETokenType.END_OF_INPUT;
  79308. this.currentString = this.read();
  79309. this.currentToken = ETokenType.UNKNOWN;
  79310. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  79311. this.currentToken = ETokenType.IDENTIFIER;
  79312. this.currentIdentifier = this.currentString;
  79313. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  79314. this.currentIdentifier += this.currentString;
  79315. this.forward();
  79316. }
  79317. }
  79318. return this.currentToken;
  79319. };
  79320. Tokenizer.prototype.peek = function () {
  79321. return this._toParse[this._pos];
  79322. };
  79323. Tokenizer.prototype.read = function () {
  79324. return this._toParse[this._pos++];
  79325. };
  79326. Tokenizer.prototype.forward = function () {
  79327. this._pos++;
  79328. };
  79329. Tokenizer.prototype.isEnd = function () {
  79330. return this._pos >= this._maxPos;
  79331. };
  79332. return Tokenizer;
  79333. }());
  79334. /**
  79335. * Values
  79336. */
  79337. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  79338. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  79339. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  79340. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  79341. /**
  79342. * Parse
  79343. */
  79344. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  79345. for (var buf in parsedBuffers) {
  79346. var parsedBuffer = parsedBuffers[buf];
  79347. gltfRuntime.buffers[buf] = parsedBuffer;
  79348. gltfRuntime.buffersCount++;
  79349. }
  79350. };
  79351. var parseShaders = function (parsedShaders, gltfRuntime) {
  79352. for (var sha in parsedShaders) {
  79353. var parsedShader = parsedShaders[sha];
  79354. gltfRuntime.shaders[sha] = parsedShader;
  79355. gltfRuntime.shaderscount++;
  79356. }
  79357. };
  79358. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  79359. for (var object in parsedObjects) {
  79360. var parsedObject = parsedObjects[object];
  79361. gltfRuntime[runtimeProperty][object] = parsedObject;
  79362. }
  79363. };
  79364. /**
  79365. * Utils
  79366. */
  79367. var normalizeUVs = function (buffer) {
  79368. if (!buffer) {
  79369. return;
  79370. }
  79371. for (var i = 0; i < buffer.length / 2; i++) {
  79372. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  79373. }
  79374. };
  79375. var getAttribute = function (attributeParameter) {
  79376. if (attributeParameter.semantic === "NORMAL") {
  79377. return "normal";
  79378. }
  79379. else if (attributeParameter.semantic === "POSITION") {
  79380. return "position";
  79381. }
  79382. else if (attributeParameter.semantic === "JOINT") {
  79383. return "matricesIndices";
  79384. }
  79385. else if (attributeParameter.semantic === "WEIGHT") {
  79386. return "matricesWeights";
  79387. }
  79388. else if (attributeParameter.semantic === "COLOR") {
  79389. return "color";
  79390. }
  79391. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  79392. var channel = Number(attributeParameter.semantic.split("_")[1]);
  79393. return "uv" + (channel === 0 ? "" : channel + 1);
  79394. }
  79395. return null;
  79396. };
  79397. /**
  79398. * Loads and creates animations
  79399. */
  79400. var loadAnimations = function (gltfRuntime) {
  79401. for (var anim in gltfRuntime.animations) {
  79402. var animation = gltfRuntime.animations[anim];
  79403. if (!animation.channels || !animation.samplers) {
  79404. continue;
  79405. }
  79406. var lastAnimation = null;
  79407. for (var i = 0; i < animation.channels.length; i++) {
  79408. // Get parameters and load buffers
  79409. var channel = animation.channels[i];
  79410. var sampler = animation.samplers[channel.sampler];
  79411. if (!sampler) {
  79412. continue;
  79413. }
  79414. var inputData = null;
  79415. var outputData = null;
  79416. if (animation.parameters) {
  79417. inputData = animation.parameters[sampler.input];
  79418. outputData = animation.parameters[sampler.output];
  79419. }
  79420. else {
  79421. inputData = sampler.input;
  79422. outputData = sampler.output;
  79423. }
  79424. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  79425. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  79426. var targetID = channel.target.id;
  79427. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  79428. if (targetNode === null) {
  79429. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  79430. }
  79431. if (targetNode === null) {
  79432. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  79433. continue;
  79434. }
  79435. var isBone = targetNode instanceof BABYLON.Bone;
  79436. // Get target path (position, rotation or scaling)
  79437. var targetPath = channel.target.path;
  79438. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  79439. if (targetPathIndex !== -1) {
  79440. targetPath = babylonAnimationPaths[targetPathIndex];
  79441. }
  79442. // Determine animation type
  79443. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  79444. if (!isBone) {
  79445. if (targetPath === "rotationQuaternion") {
  79446. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  79447. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  79448. }
  79449. else {
  79450. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  79451. }
  79452. }
  79453. // Create animation and key frames
  79454. var babylonAnimation = null;
  79455. var keys = [];
  79456. var arrayOffset = 0;
  79457. var modifyKey = false;
  79458. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  79459. babylonAnimation = lastAnimation;
  79460. modifyKey = true;
  79461. }
  79462. if (!modifyKey) {
  79463. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  79464. }
  79465. // For each frame
  79466. for (var j = 0; j < bufferInput.length; j++) {
  79467. var value = null;
  79468. if (targetPath === "rotationQuaternion") {
  79469. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  79470. arrayOffset += 4;
  79471. }
  79472. else {
  79473. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  79474. arrayOffset += 3;
  79475. }
  79476. if (isBone) {
  79477. var bone = targetNode;
  79478. var translation = BABYLON.Vector3.Zero();
  79479. var rotationQuaternion = new BABYLON.Quaternion();
  79480. var scaling = BABYLON.Vector3.Zero();
  79481. // Warning on decompose
  79482. var mat = bone.getBaseMatrix();
  79483. if (modifyKey && lastAnimation) {
  79484. mat = lastAnimation.getKeys()[j].value;
  79485. }
  79486. mat.decompose(scaling, rotationQuaternion, translation);
  79487. if (targetPath === "position") {
  79488. translation = value;
  79489. }
  79490. else if (targetPath === "rotationQuaternion") {
  79491. rotationQuaternion = value;
  79492. }
  79493. else {
  79494. scaling = value;
  79495. }
  79496. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  79497. }
  79498. if (!modifyKey) {
  79499. keys.push({
  79500. frame: bufferInput[j],
  79501. value: value
  79502. });
  79503. }
  79504. else if (lastAnimation) {
  79505. lastAnimation.getKeys()[j].value = value;
  79506. }
  79507. }
  79508. // Finish
  79509. if (!modifyKey && babylonAnimation) {
  79510. babylonAnimation.setKeys(keys);
  79511. targetNode.animations.push(babylonAnimation);
  79512. }
  79513. lastAnimation = babylonAnimation;
  79514. gltfRuntime.scene.stopAnimation(targetNode);
  79515. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  79516. }
  79517. }
  79518. };
  79519. /**
  79520. * Returns the bones transformation matrix
  79521. */
  79522. var configureBoneTransformation = function (node) {
  79523. var mat = null;
  79524. if (node.translation || node.rotation || node.scale) {
  79525. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  79526. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  79527. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  79528. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  79529. }
  79530. else {
  79531. mat = BABYLON.Matrix.FromArray(node.matrix);
  79532. }
  79533. return mat;
  79534. };
  79535. /**
  79536. * Returns the parent bone
  79537. */
  79538. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  79539. // Try to find
  79540. for (var i = 0; i < newSkeleton.bones.length; i++) {
  79541. if (newSkeleton.bones[i].name === jointName) {
  79542. return newSkeleton.bones[i];
  79543. }
  79544. }
  79545. // Not found, search in gltf nodes
  79546. var nodes = gltfRuntime.nodes;
  79547. for (var nde in nodes) {
  79548. var node = nodes[nde];
  79549. if (!node.jointName) {
  79550. continue;
  79551. }
  79552. var children = node.children;
  79553. for (var i = 0; i < children.length; i++) {
  79554. var child = gltfRuntime.nodes[children[i]];
  79555. if (!child.jointName) {
  79556. continue;
  79557. }
  79558. if (child.jointName === jointName) {
  79559. var mat = configureBoneTransformation(node);
  79560. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  79561. bone.id = nde;
  79562. return bone;
  79563. }
  79564. }
  79565. }
  79566. return null;
  79567. };
  79568. /**
  79569. * Returns the appropriate root node
  79570. */
  79571. var getNodeToRoot = function (nodesToRoot, id) {
  79572. for (var i = 0; i < nodesToRoot.length; i++) {
  79573. var nodeToRoot = nodesToRoot[i];
  79574. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  79575. var child = nodeToRoot.node.children[j];
  79576. if (child === id) {
  79577. return nodeToRoot.bone;
  79578. }
  79579. }
  79580. }
  79581. return null;
  79582. };
  79583. /**
  79584. * Returns the node with the joint name
  79585. */
  79586. var getJointNode = function (gltfRuntime, jointName) {
  79587. var nodes = gltfRuntime.nodes;
  79588. var node = nodes[jointName];
  79589. if (node) {
  79590. return {
  79591. node: node,
  79592. id: jointName
  79593. };
  79594. }
  79595. for (var nde in nodes) {
  79596. node = nodes[nde];
  79597. if (node.jointName === jointName) {
  79598. return {
  79599. node: node,
  79600. id: nde
  79601. };
  79602. }
  79603. }
  79604. return null;
  79605. };
  79606. /**
  79607. * Checks if a nodes is in joints
  79608. */
  79609. var nodeIsInJoints = function (skins, id) {
  79610. for (var i = 0; i < skins.jointNames.length; i++) {
  79611. if (skins.jointNames[i] === id) {
  79612. return true;
  79613. }
  79614. }
  79615. return false;
  79616. };
  79617. /**
  79618. * Fills the nodes to root for bones and builds hierarchy
  79619. */
  79620. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  79621. // Creates nodes for root
  79622. for (var nde in gltfRuntime.nodes) {
  79623. var node = gltfRuntime.nodes[nde];
  79624. var id = nde;
  79625. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  79626. continue;
  79627. }
  79628. // Create node to root bone
  79629. var mat = configureBoneTransformation(node);
  79630. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  79631. bone.id = id;
  79632. nodesToRoot.push({ bone: bone, node: node, id: id });
  79633. }
  79634. // Parenting
  79635. for (var i = 0; i < nodesToRoot.length; i++) {
  79636. var nodeToRoot = nodesToRoot[i];
  79637. var children = nodeToRoot.node.children;
  79638. for (var j = 0; j < children.length; j++) {
  79639. var child = null;
  79640. for (var k = 0; k < nodesToRoot.length; k++) {
  79641. if (nodesToRoot[k].id === children[j]) {
  79642. child = nodesToRoot[k];
  79643. break;
  79644. }
  79645. }
  79646. if (child) {
  79647. child.bone._parent = nodeToRoot.bone;
  79648. nodeToRoot.bone.children.push(child.bone);
  79649. }
  79650. }
  79651. }
  79652. };
  79653. /**
  79654. * Imports a skeleton
  79655. */
  79656. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  79657. if (!newSkeleton) {
  79658. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  79659. }
  79660. if (!skins.babylonSkeleton) {
  79661. return newSkeleton;
  79662. }
  79663. // Find the root bones
  79664. var nodesToRoot = [];
  79665. var nodesToRootToAdd = [];
  79666. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  79667. newSkeleton.bones = [];
  79668. // Joints
  79669. for (var i = 0; i < skins.jointNames.length; i++) {
  79670. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  79671. if (!jointNode) {
  79672. continue;
  79673. }
  79674. var node = jointNode.node;
  79675. if (!node) {
  79676. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  79677. continue;
  79678. }
  79679. var id = jointNode.id;
  79680. // Optimize, if the bone already exists...
  79681. var existingBone = gltfRuntime.scene.getBoneByID(id);
  79682. if (existingBone) {
  79683. newSkeleton.bones.push(existingBone);
  79684. continue;
  79685. }
  79686. // Search for parent bone
  79687. var foundBone = false;
  79688. var parentBone = null;
  79689. for (var j = 0; j < i; j++) {
  79690. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  79691. if (!jointNode_1) {
  79692. continue;
  79693. }
  79694. var joint = jointNode_1.node;
  79695. if (!joint) {
  79696. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  79697. continue;
  79698. }
  79699. var children = joint.children;
  79700. if (!children) {
  79701. continue;
  79702. }
  79703. foundBone = false;
  79704. for (var k = 0; k < children.length; k++) {
  79705. if (children[k] === id) {
  79706. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  79707. foundBone = true;
  79708. break;
  79709. }
  79710. }
  79711. if (foundBone) {
  79712. break;
  79713. }
  79714. }
  79715. // Create bone
  79716. var mat = configureBoneTransformation(node);
  79717. if (!parentBone && nodesToRoot.length > 0) {
  79718. parentBone = getNodeToRoot(nodesToRoot, id);
  79719. if (parentBone) {
  79720. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  79721. nodesToRootToAdd.push(parentBone);
  79722. }
  79723. }
  79724. }
  79725. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  79726. bone.id = id;
  79727. }
  79728. // Polish
  79729. var bones = newSkeleton.bones;
  79730. newSkeleton.bones = [];
  79731. for (var i = 0; i < skins.jointNames.length; i++) {
  79732. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  79733. if (!jointNode) {
  79734. continue;
  79735. }
  79736. for (var j = 0; j < bones.length; j++) {
  79737. if (bones[j].id === jointNode.id) {
  79738. newSkeleton.bones.push(bones[j]);
  79739. break;
  79740. }
  79741. }
  79742. }
  79743. newSkeleton.prepare();
  79744. // Finish
  79745. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  79746. newSkeleton.bones.push(nodesToRootToAdd[i]);
  79747. }
  79748. return newSkeleton;
  79749. };
  79750. /**
  79751. * Imports a mesh and its geometries
  79752. */
  79753. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  79754. if (!newMesh) {
  79755. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  79756. newMesh.id = id;
  79757. }
  79758. if (!node.babylonNode) {
  79759. return newMesh;
  79760. }
  79761. var subMaterials = [];
  79762. var vertexData = new BABYLON.VertexData();
  79763. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  79764. var verticesStarts = new Array();
  79765. var verticesCounts = new Array();
  79766. var indexStarts = new Array();
  79767. var indexCounts = new Array();
  79768. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  79769. var meshID = meshes[meshIndex];
  79770. var mesh = gltfRuntime.meshes[meshID];
  79771. if (!mesh) {
  79772. continue;
  79773. }
  79774. // Positions, normals and UVs
  79775. for (var i = 0; i < mesh.primitives.length; i++) {
  79776. // Temporary vertex data
  79777. var tempVertexData = new BABYLON.VertexData();
  79778. var primitive = mesh.primitives[i];
  79779. if (primitive.mode !== 4) {
  79780. // continue;
  79781. }
  79782. var attributes = primitive.attributes;
  79783. var accessor = null;
  79784. var buffer = null;
  79785. // Set positions, normal and uvs
  79786. for (var semantic in attributes) {
  79787. // Link accessor and buffer view
  79788. accessor = gltfRuntime.accessors[attributes[semantic]];
  79789. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  79790. if (semantic === "NORMAL") {
  79791. tempVertexData.normals = new Float32Array(buffer.length);
  79792. tempVertexData.normals.set(buffer);
  79793. }
  79794. else if (semantic === "POSITION") {
  79795. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  79796. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  79797. for (var j = 0; j < buffer.length; j += 4) {
  79798. tempVertexData.positions[j] = buffer[j];
  79799. tempVertexData.positions[j + 1] = buffer[j + 1];
  79800. tempVertexData.positions[j + 2] = buffer[j + 2];
  79801. }
  79802. }
  79803. else {
  79804. tempVertexData.positions = new Float32Array(buffer.length);
  79805. tempVertexData.positions.set(buffer);
  79806. }
  79807. verticesCounts.push(tempVertexData.positions.length);
  79808. }
  79809. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  79810. var channel = Number(semantic.split("_")[1]);
  79811. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  79812. var uvs = new Float32Array(buffer.length);
  79813. uvs.set(buffer);
  79814. normalizeUVs(uvs);
  79815. tempVertexData.set(uvs, uvKind);
  79816. }
  79817. else if (semantic === "JOINT") {
  79818. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  79819. tempVertexData.matricesIndices.set(buffer);
  79820. }
  79821. else if (semantic === "WEIGHT") {
  79822. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  79823. tempVertexData.matricesWeights.set(buffer);
  79824. }
  79825. else if (semantic === "COLOR") {
  79826. tempVertexData.colors = new Float32Array(buffer.length);
  79827. tempVertexData.colors.set(buffer);
  79828. }
  79829. }
  79830. // Indices
  79831. accessor = gltfRuntime.accessors[primitive.indices];
  79832. if (accessor) {
  79833. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  79834. tempVertexData.indices = new Int32Array(buffer.length);
  79835. tempVertexData.indices.set(buffer);
  79836. indexCounts.push(tempVertexData.indices.length);
  79837. }
  79838. else {
  79839. // Set indices on the fly
  79840. var indices = [];
  79841. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  79842. indices.push(j);
  79843. }
  79844. tempVertexData.indices = new Int32Array(indices);
  79845. indexCounts.push(tempVertexData.indices.length);
  79846. }
  79847. vertexData.merge(tempVertexData);
  79848. // Sub material
  79849. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  79850. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  79851. // Update vertices start and index start
  79852. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  79853. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  79854. }
  79855. }
  79856. var material;
  79857. if (subMaterials.length > 1) {
  79858. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  79859. material.subMaterials = subMaterials;
  79860. }
  79861. else {
  79862. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  79863. }
  79864. if (subMaterials.length === 1) {
  79865. material = subMaterials[0];
  79866. }
  79867. if (!newMesh.material) {
  79868. newMesh.material = material;
  79869. }
  79870. // Apply geometry
  79871. geometry.setAllVerticesData(vertexData, false);
  79872. newMesh.computeWorldMatrix(true);
  79873. // Apply submeshes
  79874. newMesh.subMeshes = [];
  79875. var index = 0;
  79876. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  79877. var meshID = meshes[meshIndex];
  79878. var mesh = gltfRuntime.meshes[meshID];
  79879. if (!mesh) {
  79880. continue;
  79881. }
  79882. for (var i = 0; i < mesh.primitives.length; i++) {
  79883. if (mesh.primitives[i].mode !== 4) {
  79884. //continue;
  79885. }
  79886. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  79887. index++;
  79888. }
  79889. }
  79890. // Finish
  79891. return newMesh;
  79892. };
  79893. /**
  79894. * Configure node transformation from position, rotation and scaling
  79895. */
  79896. var configureNode = function (newNode, position, rotation, scaling) {
  79897. if (newNode.position) {
  79898. newNode.position = position;
  79899. }
  79900. if (newNode.rotationQuaternion || newNode.rotation) {
  79901. newNode.rotationQuaternion = rotation;
  79902. }
  79903. if (newNode.scaling) {
  79904. newNode.scaling = scaling;
  79905. }
  79906. };
  79907. /**
  79908. * Configures node from transformation matrix
  79909. */
  79910. var configureNodeFromMatrix = function (newNode, node, parent) {
  79911. if (node.matrix) {
  79912. var position = new BABYLON.Vector3(0, 0, 0);
  79913. var rotation = new BABYLON.Quaternion();
  79914. var scaling = new BABYLON.Vector3(0, 0, 0);
  79915. var mat = BABYLON.Matrix.FromArray(node.matrix);
  79916. mat.decompose(scaling, rotation, position);
  79917. configureNode(newNode, position, rotation, scaling);
  79918. }
  79919. else if (node.translation && node.rotation && node.scale) {
  79920. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  79921. }
  79922. newNode.computeWorldMatrix(true);
  79923. };
  79924. /**
  79925. * Imports a node
  79926. */
  79927. var importNode = function (gltfRuntime, node, id, parent) {
  79928. var lastNode = null;
  79929. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  79930. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  79931. return null;
  79932. }
  79933. }
  79934. // Meshes
  79935. if (node.skin) {
  79936. if (node.meshes) {
  79937. var skin = gltfRuntime.skins[node.skin];
  79938. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  79939. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  79940. if (newMesh.skeleton === null) {
  79941. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  79942. if (!skin.babylonSkeleton) {
  79943. skin.babylonSkeleton = newMesh.skeleton;
  79944. }
  79945. }
  79946. lastNode = newMesh;
  79947. }
  79948. }
  79949. else if (node.meshes) {
  79950. /**
  79951. * Improve meshes property
  79952. */
  79953. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  79954. lastNode = newMesh;
  79955. }
  79956. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  79957. var light = gltfRuntime.lights[node.light];
  79958. if (light) {
  79959. if (light.type === "ambient") {
  79960. var ambienLight = light[light.type];
  79961. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  79962. hemiLight.name = node.name || "";
  79963. if (ambienLight.color) {
  79964. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  79965. }
  79966. lastNode = hemiLight;
  79967. }
  79968. else if (light.type === "directional") {
  79969. var directionalLight = light[light.type];
  79970. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  79971. dirLight.name = node.name || "";
  79972. if (directionalLight.color) {
  79973. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  79974. }
  79975. lastNode = dirLight;
  79976. }
  79977. else if (light.type === "point") {
  79978. var pointLight = light[light.type];
  79979. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  79980. ptLight.name = node.name || "";
  79981. if (pointLight.color) {
  79982. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  79983. }
  79984. lastNode = ptLight;
  79985. }
  79986. else if (light.type === "spot") {
  79987. var spotLight = light[light.type];
  79988. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  79989. spLight.name = node.name || "";
  79990. if (spotLight.color) {
  79991. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  79992. }
  79993. if (spotLight.fallOfAngle) {
  79994. spLight.angle = spotLight.fallOfAngle;
  79995. }
  79996. if (spotLight.fallOffExponent) {
  79997. spLight.exponent = spotLight.fallOffExponent;
  79998. }
  79999. lastNode = spLight;
  80000. }
  80001. }
  80002. }
  80003. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  80004. var camera = gltfRuntime.cameras[node.camera];
  80005. if (camera) {
  80006. if (camera.type === "orthographic") {
  80007. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  80008. orthoCamera.name = node.name || "";
  80009. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  80010. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  80011. lastNode = orthoCamera;
  80012. }
  80013. else if (camera.type === "perspective") {
  80014. var perspectiveCamera = camera[camera.type];
  80015. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  80016. persCamera.name = node.name || "";
  80017. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  80018. if (!perspectiveCamera.aspectRatio) {
  80019. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  80020. }
  80021. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  80022. persCamera.maxZ = perspectiveCamera.zfar;
  80023. persCamera.minZ = perspectiveCamera.znear;
  80024. }
  80025. lastNode = persCamera;
  80026. }
  80027. }
  80028. }
  80029. // Empty node
  80030. if (!node.jointName) {
  80031. if (node.babylonNode) {
  80032. return node.babylonNode;
  80033. }
  80034. else if (lastNode === null) {
  80035. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  80036. node.babylonNode = dummy;
  80037. lastNode = dummy;
  80038. }
  80039. }
  80040. if (lastNode !== null) {
  80041. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  80042. configureNodeFromMatrix(lastNode, node, parent);
  80043. }
  80044. else {
  80045. var translation = node.translation || [0, 0, 0];
  80046. var rotation = node.rotation || [0, 0, 0, 1];
  80047. var scale = node.scale || [1, 1, 1];
  80048. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  80049. }
  80050. lastNode.updateCache(true);
  80051. node.babylonNode = lastNode;
  80052. }
  80053. return lastNode;
  80054. };
  80055. /**
  80056. * Traverses nodes and creates them
  80057. */
  80058. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  80059. if (meshIncluded === void 0) { meshIncluded = false; }
  80060. var node = gltfRuntime.nodes[id];
  80061. var newNode = null;
  80062. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  80063. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  80064. meshIncluded = true;
  80065. }
  80066. else {
  80067. meshIncluded = false;
  80068. }
  80069. }
  80070. else {
  80071. meshIncluded = true;
  80072. }
  80073. if (!node.jointName && meshIncluded) {
  80074. newNode = importNode(gltfRuntime, node, id, parent);
  80075. if (newNode !== null) {
  80076. newNode.id = id;
  80077. newNode.parent = parent;
  80078. }
  80079. }
  80080. if (node.children) {
  80081. for (var i = 0; i < node.children.length; i++) {
  80082. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  80083. }
  80084. }
  80085. };
  80086. /**
  80087. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  80088. */
  80089. var postLoad = function (gltfRuntime) {
  80090. // Nodes
  80091. var currentScene = gltfRuntime.currentScene;
  80092. if (currentScene) {
  80093. for (var i = 0; i < currentScene.nodes.length; i++) {
  80094. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  80095. }
  80096. }
  80097. else {
  80098. for (var thing in gltfRuntime.scenes) {
  80099. currentScene = gltfRuntime.scenes[thing];
  80100. for (var i = 0; i < currentScene.nodes.length; i++) {
  80101. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  80102. }
  80103. }
  80104. }
  80105. // Set animations
  80106. loadAnimations(gltfRuntime);
  80107. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  80108. var skeleton = gltfRuntime.scene.skeletons[i];
  80109. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  80110. }
  80111. };
  80112. /**
  80113. * onBind shaderrs callback to set uniforms and matrices
  80114. */
  80115. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  80116. var materialValues = material.values || technique.parameters;
  80117. for (var unif in unTreatedUniforms) {
  80118. var uniform = unTreatedUniforms[unif];
  80119. var type = uniform.type;
  80120. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  80121. if (uniform.semantic && !uniform.source && !uniform.node) {
  80122. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  80123. }
  80124. else if (uniform.semantic && (uniform.source || uniform.node)) {
  80125. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  80126. if (source === null) {
  80127. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  80128. }
  80129. if (source === null) {
  80130. continue;
  80131. }
  80132. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  80133. }
  80134. }
  80135. else {
  80136. var value = materialValues[technique.uniforms[unif]];
  80137. if (!value) {
  80138. continue;
  80139. }
  80140. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  80141. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  80142. if (texture === null || texture === undefined) {
  80143. continue;
  80144. }
  80145. shaderMaterial.getEffect().setTexture(unif, texture);
  80146. }
  80147. else {
  80148. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  80149. }
  80150. }
  80151. }
  80152. onSuccess(shaderMaterial);
  80153. };
  80154. /**
  80155. * Prepare uniforms to send the only one time
  80156. * Loads the appropriate textures
  80157. */
  80158. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  80159. var materialValues = material.values || technique.parameters;
  80160. var techniqueUniforms = technique.uniforms;
  80161. /**
  80162. * Prepare values here (not matrices)
  80163. */
  80164. for (var unif in unTreatedUniforms) {
  80165. var uniform = unTreatedUniforms[unif];
  80166. var type = uniform.type;
  80167. var value = materialValues[techniqueUniforms[unif]];
  80168. if (value === undefined) {
  80169. // In case the value is the same for all materials
  80170. value = uniform.value;
  80171. }
  80172. if (!value) {
  80173. continue;
  80174. }
  80175. var onLoadTexture = function (uniformName) {
  80176. return function (texture) {
  80177. if (uniform.value && uniformName) {
  80178. // Static uniform
  80179. shaderMaterial.setTexture(uniformName, texture);
  80180. delete unTreatedUniforms[uniformName];
  80181. }
  80182. };
  80183. };
  80184. // Texture (sampler2D)
  80185. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  80186. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  80187. }
  80188. else {
  80189. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  80190. // Static uniform
  80191. delete unTreatedUniforms[unif];
  80192. }
  80193. }
  80194. }
  80195. };
  80196. /**
  80197. * Shader compilation failed
  80198. */
  80199. var onShaderCompileError = function (program, shaderMaterial, onError) {
  80200. return function (effect, error) {
  80201. shaderMaterial.dispose(true);
  80202. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  80203. };
  80204. };
  80205. /**
  80206. * Shader compilation success
  80207. */
  80208. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  80209. return function (_) {
  80210. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  80211. shaderMaterial.onBind = function (mesh) {
  80212. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  80213. };
  80214. };
  80215. };
  80216. /**
  80217. * Returns the appropriate uniform if already handled by babylon
  80218. */
  80219. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  80220. for (var unif in technique.uniforms) {
  80221. var uniform = technique.uniforms[unif];
  80222. var uniformParameter = technique.parameters[uniform];
  80223. if (tokenizer.currentIdentifier === unif) {
  80224. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  80225. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  80226. if (transformIndex !== -1) {
  80227. delete unTreatedUniforms[unif];
  80228. return babylonTransforms[transformIndex];
  80229. }
  80230. }
  80231. }
  80232. }
  80233. return tokenizer.currentIdentifier;
  80234. };
  80235. /**
  80236. * All shaders loaded. Create materials one by one
  80237. */
  80238. var importMaterials = function (gltfRuntime) {
  80239. // Create materials
  80240. for (var mat in gltfRuntime.materials) {
  80241. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  80242. }
  80243. };
  80244. /**
  80245. * Implementation of the base glTF spec
  80246. */
  80247. var GLTFLoaderBase = /** @class */ (function () {
  80248. function GLTFLoaderBase() {
  80249. }
  80250. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  80251. var gltfRuntime = {
  80252. extensions: {},
  80253. accessors: {},
  80254. buffers: {},
  80255. bufferViews: {},
  80256. meshes: {},
  80257. lights: {},
  80258. cameras: {},
  80259. nodes: {},
  80260. images: {},
  80261. textures: {},
  80262. shaders: {},
  80263. programs: {},
  80264. samplers: {},
  80265. techniques: {},
  80266. materials: {},
  80267. animations: {},
  80268. skins: {},
  80269. extensionsUsed: [],
  80270. scenes: {},
  80271. buffersCount: 0,
  80272. shaderscount: 0,
  80273. scene: scene,
  80274. rootUrl: rootUrl,
  80275. loadedBufferCount: 0,
  80276. loadedBufferViews: {},
  80277. loadedShaderCount: 0,
  80278. importOnlyMeshes: false,
  80279. dummyNodes: []
  80280. };
  80281. // Parse
  80282. if (parsedData.extensions) {
  80283. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  80284. }
  80285. if (parsedData.extensionsUsed) {
  80286. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  80287. }
  80288. if (parsedData.buffers) {
  80289. parseBuffers(parsedData.buffers, gltfRuntime);
  80290. }
  80291. if (parsedData.bufferViews) {
  80292. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  80293. }
  80294. if (parsedData.accessors) {
  80295. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  80296. }
  80297. if (parsedData.meshes) {
  80298. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  80299. }
  80300. if (parsedData.lights) {
  80301. parseObject(parsedData.lights, "lights", gltfRuntime);
  80302. }
  80303. if (parsedData.cameras) {
  80304. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  80305. }
  80306. if (parsedData.nodes) {
  80307. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  80308. }
  80309. if (parsedData.images) {
  80310. parseObject(parsedData.images, "images", gltfRuntime);
  80311. }
  80312. if (parsedData.textures) {
  80313. parseObject(parsedData.textures, "textures", gltfRuntime);
  80314. }
  80315. if (parsedData.shaders) {
  80316. parseShaders(parsedData.shaders, gltfRuntime);
  80317. }
  80318. if (parsedData.programs) {
  80319. parseObject(parsedData.programs, "programs", gltfRuntime);
  80320. }
  80321. if (parsedData.samplers) {
  80322. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  80323. }
  80324. if (parsedData.techniques) {
  80325. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  80326. }
  80327. if (parsedData.materials) {
  80328. parseObject(parsedData.materials, "materials", gltfRuntime);
  80329. }
  80330. if (parsedData.animations) {
  80331. parseObject(parsedData.animations, "animations", gltfRuntime);
  80332. }
  80333. if (parsedData.skins) {
  80334. parseObject(parsedData.skins, "skins", gltfRuntime);
  80335. }
  80336. if (parsedData.scenes) {
  80337. gltfRuntime.scenes = parsedData.scenes;
  80338. }
  80339. if (parsedData.scene && parsedData.scenes) {
  80340. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  80341. }
  80342. return gltfRuntime;
  80343. };
  80344. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  80345. var buffer = gltfRuntime.buffers[id];
  80346. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  80347. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  80348. }
  80349. else {
  80350. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  80351. if (request) {
  80352. onError(request.status + " " + request.statusText);
  80353. }
  80354. });
  80355. }
  80356. };
  80357. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  80358. var texture = gltfRuntime.textures[id];
  80359. if (!texture || !texture.source) {
  80360. onError("");
  80361. return;
  80362. }
  80363. if (texture.babylonTexture) {
  80364. onSuccess(null);
  80365. return;
  80366. }
  80367. var source = gltfRuntime.images[texture.source];
  80368. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  80369. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  80370. }
  80371. else {
  80372. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  80373. if (request) {
  80374. onError(request.status + " " + request.statusText);
  80375. }
  80376. });
  80377. }
  80378. };
  80379. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  80380. var texture = gltfRuntime.textures[id];
  80381. if (texture.babylonTexture) {
  80382. onSuccess(texture.babylonTexture);
  80383. return;
  80384. }
  80385. var sampler = gltfRuntime.samplers[texture.sampler];
  80386. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  80387. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  80388. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  80389. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  80390. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  80391. var blob = new Blob([buffer]);
  80392. var blobURL = URL.createObjectURL(blob);
  80393. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  80394. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  80395. if (sampler.wrapS !== undefined) {
  80396. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  80397. }
  80398. if (sampler.wrapT !== undefined) {
  80399. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  80400. }
  80401. newTexture.name = id;
  80402. texture.babylonTexture = newTexture;
  80403. onSuccess(newTexture);
  80404. };
  80405. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  80406. var shader = gltfRuntime.shaders[id];
  80407. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  80408. var shaderString = atob(shader.uri.split(",")[1]);
  80409. onSuccess(shaderString);
  80410. }
  80411. else {
  80412. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  80413. if (request) {
  80414. onError(request.status + " " + request.statusText);
  80415. }
  80416. });
  80417. }
  80418. };
  80419. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  80420. var material = gltfRuntime.materials[id];
  80421. if (!material.technique) {
  80422. if (onError) {
  80423. onError("No technique found.");
  80424. }
  80425. return;
  80426. }
  80427. var technique = gltfRuntime.techniques[material.technique];
  80428. if (!technique) {
  80429. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  80430. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  80431. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  80432. onSuccess(defaultMaterial);
  80433. return;
  80434. }
  80435. var program = gltfRuntime.programs[technique.program];
  80436. var states = technique.states;
  80437. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  80438. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  80439. var newVertexShader = "";
  80440. var newPixelShader = "";
  80441. var vertexTokenizer = new Tokenizer(vertexShader);
  80442. var pixelTokenizer = new Tokenizer(pixelShader);
  80443. var unTreatedUniforms = {};
  80444. var uniforms = [];
  80445. var attributes = [];
  80446. var samplers = [];
  80447. // Fill uniform, sampler2D and attributes
  80448. for (var unif in technique.uniforms) {
  80449. var uniform = technique.uniforms[unif];
  80450. var uniformParameter = technique.parameters[uniform];
  80451. unTreatedUniforms[unif] = uniformParameter;
  80452. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  80453. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  80454. if (transformIndex !== -1) {
  80455. uniforms.push(babylonTransforms[transformIndex]);
  80456. delete unTreatedUniforms[unif];
  80457. }
  80458. else {
  80459. uniforms.push(unif);
  80460. }
  80461. }
  80462. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  80463. samplers.push(unif);
  80464. }
  80465. else {
  80466. uniforms.push(unif);
  80467. }
  80468. }
  80469. for (var attr in technique.attributes) {
  80470. var attribute = technique.attributes[attr];
  80471. var attributeParameter = technique.parameters[attribute];
  80472. if (attributeParameter.semantic) {
  80473. attributes.push(getAttribute(attributeParameter));
  80474. }
  80475. }
  80476. // Configure vertex shader
  80477. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  80478. var tokenType = vertexTokenizer.currentToken;
  80479. if (tokenType !== ETokenType.IDENTIFIER) {
  80480. newVertexShader += vertexTokenizer.currentString;
  80481. continue;
  80482. }
  80483. var foundAttribute = false;
  80484. for (var attr in technique.attributes) {
  80485. var attribute = technique.attributes[attr];
  80486. var attributeParameter = technique.parameters[attribute];
  80487. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  80488. newVertexShader += getAttribute(attributeParameter);
  80489. foundAttribute = true;
  80490. break;
  80491. }
  80492. }
  80493. if (foundAttribute) {
  80494. continue;
  80495. }
  80496. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  80497. }
  80498. // Configure pixel shader
  80499. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  80500. var tokenType = pixelTokenizer.currentToken;
  80501. if (tokenType !== ETokenType.IDENTIFIER) {
  80502. newPixelShader += pixelTokenizer.currentString;
  80503. continue;
  80504. }
  80505. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  80506. }
  80507. // Create shader material
  80508. var shaderPath = {
  80509. vertex: program.vertexShader + id,
  80510. fragment: program.fragmentShader + id
  80511. };
  80512. var options = {
  80513. attributes: attributes,
  80514. uniforms: uniforms,
  80515. samplers: samplers,
  80516. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  80517. };
  80518. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  80519. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  80520. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  80521. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  80522. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  80523. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  80524. if (states && states.functions) {
  80525. var functions = states.functions;
  80526. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  80527. shaderMaterial.backFaceCulling = false;
  80528. }
  80529. var blendFunc = functions.blendFuncSeparate;
  80530. if (blendFunc) {
  80531. 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) {
  80532. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  80533. }
  80534. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  80535. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  80536. }
  80537. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  80538. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  80539. }
  80540. 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) {
  80541. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  80542. }
  80543. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  80544. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  80545. }
  80546. 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) {
  80547. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  80548. }
  80549. }
  80550. }
  80551. };
  80552. return GLTFLoaderBase;
  80553. }());
  80554. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  80555. /**
  80556. * glTF V1 Loader
  80557. */
  80558. var GLTFLoader = /** @class */ (function () {
  80559. function GLTFLoader() {
  80560. }
  80561. GLTFLoader.RegisterExtension = function (extension) {
  80562. if (GLTFLoader.Extensions[extension.name]) {
  80563. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  80564. return;
  80565. }
  80566. GLTFLoader.Extensions[extension.name] = extension;
  80567. };
  80568. GLTFLoader.prototype.dispose = function () {
  80569. // do nothing
  80570. };
  80571. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  80572. var _this = this;
  80573. scene.useRightHandedSystem = true;
  80574. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  80575. gltfRuntime.importOnlyMeshes = true;
  80576. if (meshesNames === "") {
  80577. gltfRuntime.importMeshesNames = [];
  80578. }
  80579. else if (typeof meshesNames === "string") {
  80580. gltfRuntime.importMeshesNames = [meshesNames];
  80581. }
  80582. else if (meshesNames && !(meshesNames instanceof Array)) {
  80583. gltfRuntime.importMeshesNames = [meshesNames];
  80584. }
  80585. else {
  80586. gltfRuntime.importMeshesNames = [];
  80587. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  80588. }
  80589. // Create nodes
  80590. _this._createNodes(gltfRuntime);
  80591. var meshes = new Array();
  80592. var skeletons = new Array();
  80593. // Fill arrays of meshes and skeletons
  80594. for (var nde in gltfRuntime.nodes) {
  80595. var node = gltfRuntime.nodes[nde];
  80596. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  80597. meshes.push(node.babylonNode);
  80598. }
  80599. }
  80600. for (var skl in gltfRuntime.skins) {
  80601. var skin = gltfRuntime.skins[skl];
  80602. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  80603. skeletons.push(skin.babylonSkeleton);
  80604. }
  80605. }
  80606. // Load buffers, shaders, materials, etc.
  80607. _this._loadBuffersAsync(gltfRuntime, function () {
  80608. _this._loadShadersAsync(gltfRuntime, function () {
  80609. importMaterials(gltfRuntime);
  80610. postLoad(gltfRuntime);
  80611. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  80612. onSuccess(meshes, [], skeletons);
  80613. }
  80614. });
  80615. }, onProgress);
  80616. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  80617. onSuccess(meshes, [], skeletons);
  80618. }
  80619. }, onError);
  80620. return true;
  80621. };
  80622. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  80623. var _this = this;
  80624. scene.useRightHandedSystem = true;
  80625. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  80626. // Load runtime extensios
  80627. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  80628. // Create nodes
  80629. _this._createNodes(gltfRuntime);
  80630. // Load buffers, shaders, materials, etc.
  80631. _this._loadBuffersAsync(gltfRuntime, function () {
  80632. _this._loadShadersAsync(gltfRuntime, function () {
  80633. importMaterials(gltfRuntime);
  80634. postLoad(gltfRuntime);
  80635. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  80636. onSuccess();
  80637. }
  80638. });
  80639. });
  80640. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  80641. onSuccess();
  80642. }
  80643. }, onError);
  80644. }, onError);
  80645. };
  80646. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  80647. var hasShaders = false;
  80648. var processShader = function (sha, shader) {
  80649. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  80650. gltfRuntime.loadedShaderCount++;
  80651. if (shaderString) {
  80652. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  80653. }
  80654. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  80655. onload();
  80656. }
  80657. }, function () {
  80658. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  80659. });
  80660. };
  80661. for (var sha in gltfRuntime.shaders) {
  80662. hasShaders = true;
  80663. var shader = gltfRuntime.shaders[sha];
  80664. if (shader) {
  80665. processShader.bind(this, sha, shader)();
  80666. }
  80667. else {
  80668. BABYLON.Tools.Error("No shader named: " + sha);
  80669. }
  80670. }
  80671. if (!hasShaders) {
  80672. onload();
  80673. }
  80674. };
  80675. ;
  80676. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  80677. var hasBuffers = false;
  80678. var processBuffer = function (buf, buffer) {
  80679. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  80680. gltfRuntime.loadedBufferCount++;
  80681. if (bufferView) {
  80682. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  80683. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  80684. }
  80685. gltfRuntime.loadedBufferViews[buf] = bufferView;
  80686. }
  80687. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  80688. onLoad();
  80689. }
  80690. }, function () {
  80691. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  80692. });
  80693. };
  80694. for (var buf in gltfRuntime.buffers) {
  80695. hasBuffers = true;
  80696. var buffer = gltfRuntime.buffers[buf];
  80697. if (buffer) {
  80698. processBuffer.bind(this, buf, buffer)();
  80699. }
  80700. else {
  80701. BABYLON.Tools.Error("No buffer named: " + buf);
  80702. }
  80703. }
  80704. if (!hasBuffers) {
  80705. onLoad();
  80706. }
  80707. };
  80708. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  80709. var currentScene = gltfRuntime.currentScene;
  80710. if (currentScene) {
  80711. // Only one scene even if multiple scenes are defined
  80712. for (var i = 0; i < currentScene.nodes.length; i++) {
  80713. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  80714. }
  80715. }
  80716. else {
  80717. // Load all scenes
  80718. for (var thing in gltfRuntime.scenes) {
  80719. currentScene = gltfRuntime.scenes[thing];
  80720. for (var i = 0; i < currentScene.nodes.length; i++) {
  80721. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  80722. }
  80723. }
  80724. }
  80725. };
  80726. GLTFLoader.Extensions = {};
  80727. return GLTFLoader;
  80728. }());
  80729. GLTF1.GLTFLoader = GLTFLoader;
  80730. ;
  80731. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  80732. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  80733. })(BABYLON || (BABYLON = {}));
  80734. //# sourceMappingURL=babylon.glTFLoader.js.map
  80735. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  80736. var BABYLON;
  80737. (function (BABYLON) {
  80738. var GLTF1;
  80739. (function (GLTF1) {
  80740. /**
  80741. * Utils functions for GLTF
  80742. */
  80743. var GLTFUtils = /** @class */ (function () {
  80744. function GLTFUtils() {
  80745. }
  80746. /**
  80747. * Sets the given "parameter" matrix
  80748. * @param scene: the {BABYLON.Scene} object
  80749. * @param source: the source node where to pick the matrix
  80750. * @param parameter: the GLTF technique parameter
  80751. * @param uniformName: the name of the shader's uniform
  80752. * @param shaderMaterial: the shader material
  80753. */
  80754. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  80755. var mat = null;
  80756. if (parameter.semantic === "MODEL") {
  80757. mat = source.getWorldMatrix();
  80758. }
  80759. else if (parameter.semantic === "PROJECTION") {
  80760. mat = scene.getProjectionMatrix();
  80761. }
  80762. else if (parameter.semantic === "VIEW") {
  80763. mat = scene.getViewMatrix();
  80764. }
  80765. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  80766. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  80767. }
  80768. else if (parameter.semantic === "MODELVIEW") {
  80769. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  80770. }
  80771. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  80772. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  80773. }
  80774. else if (parameter.semantic === "MODELINVERSE") {
  80775. mat = source.getWorldMatrix().invert();
  80776. }
  80777. else if (parameter.semantic === "VIEWINVERSE") {
  80778. mat = scene.getViewMatrix().invert();
  80779. }
  80780. else if (parameter.semantic === "PROJECTIONINVERSE") {
  80781. mat = scene.getProjectionMatrix().invert();
  80782. }
  80783. else if (parameter.semantic === "MODELVIEWINVERSE") {
  80784. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  80785. }
  80786. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  80787. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  80788. }
  80789. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  80790. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  80791. }
  80792. else {
  80793. debugger;
  80794. }
  80795. if (mat) {
  80796. switch (parameter.type) {
  80797. case GLTF1.EParameterType.FLOAT_MAT2:
  80798. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  80799. break;
  80800. case GLTF1.EParameterType.FLOAT_MAT3:
  80801. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  80802. break;
  80803. case GLTF1.EParameterType.FLOAT_MAT4:
  80804. shaderMaterial.setMatrix(uniformName, mat);
  80805. break;
  80806. default: break;
  80807. }
  80808. }
  80809. };
  80810. /**
  80811. * Sets the given "parameter" matrix
  80812. * @param shaderMaterial: the shader material
  80813. * @param uniform: the name of the shader's uniform
  80814. * @param value: the value of the uniform
  80815. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  80816. */
  80817. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  80818. switch (type) {
  80819. case GLTF1.EParameterType.FLOAT:
  80820. shaderMaterial.setFloat(uniform, value);
  80821. return true;
  80822. case GLTF1.EParameterType.FLOAT_VEC2:
  80823. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  80824. return true;
  80825. case GLTF1.EParameterType.FLOAT_VEC3:
  80826. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  80827. return true;
  80828. case GLTF1.EParameterType.FLOAT_VEC4:
  80829. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  80830. return true;
  80831. default: return false;
  80832. }
  80833. };
  80834. /**
  80835. * If the uri is a base64 string
  80836. * @param uri: the uri to test
  80837. */
  80838. GLTFUtils.IsBase64 = function (uri) {
  80839. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  80840. };
  80841. /**
  80842. * Decode the base64 uri
  80843. * @param uri: the uri to decode
  80844. */
  80845. GLTFUtils.DecodeBase64 = function (uri) {
  80846. var decodedString = atob(uri.split(",")[1]);
  80847. var bufferLength = decodedString.length;
  80848. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  80849. for (var i = 0; i < bufferLength; i++) {
  80850. bufferView[i] = decodedString.charCodeAt(i);
  80851. }
  80852. return bufferView.buffer;
  80853. };
  80854. /**
  80855. * Returns the wrap mode of the texture
  80856. * @param mode: the mode value
  80857. */
  80858. GLTFUtils.GetWrapMode = function (mode) {
  80859. switch (mode) {
  80860. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  80861. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  80862. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  80863. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  80864. }
  80865. };
  80866. /**
  80867. * Returns the byte stride giving an accessor
  80868. * @param accessor: the GLTF accessor objet
  80869. */
  80870. GLTFUtils.GetByteStrideFromType = function (accessor) {
  80871. // Needs this function since "byteStride" isn't requiered in glTF format
  80872. var type = accessor.type;
  80873. switch (type) {
  80874. case "VEC2": return 2;
  80875. case "VEC3": return 3;
  80876. case "VEC4": return 4;
  80877. case "MAT2": return 4;
  80878. case "MAT3": return 9;
  80879. case "MAT4": return 16;
  80880. default: return 1;
  80881. }
  80882. };
  80883. /**
  80884. * Returns the texture filter mode giving a mode value
  80885. * @param mode: the filter mode value
  80886. */
  80887. GLTFUtils.GetTextureFilterMode = function (mode) {
  80888. switch (mode) {
  80889. case GLTF1.ETextureFilterType.LINEAR:
  80890. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  80891. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  80892. case GLTF1.ETextureFilterType.NEAREST:
  80893. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  80894. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  80895. }
  80896. };
  80897. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  80898. var byteOffset = bufferView.byteOffset + byteOffset;
  80899. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  80900. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  80901. throw new Error("Buffer access is out of range");
  80902. }
  80903. var buffer = loadedBufferView.buffer;
  80904. byteOffset += loadedBufferView.byteOffset;
  80905. switch (componentType) {
  80906. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  80907. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  80908. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  80909. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  80910. default: return new Float32Array(buffer, byteOffset, byteLength);
  80911. }
  80912. };
  80913. /**
  80914. * Returns a buffer from its accessor
  80915. * @param gltfRuntime: the GLTF runtime
  80916. * @param accessor: the GLTF accessor
  80917. */
  80918. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  80919. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  80920. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  80921. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  80922. };
  80923. /**
  80924. * Decodes a buffer view into a string
  80925. * @param view: the buffer view
  80926. */
  80927. GLTFUtils.DecodeBufferToText = function (view) {
  80928. var result = "";
  80929. var length = view.byteLength;
  80930. for (var i = 0; i < length; ++i) {
  80931. result += String.fromCharCode(view[i]);
  80932. }
  80933. return result;
  80934. };
  80935. /**
  80936. * Returns the default material of gltf. Related to
  80937. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  80938. * @param scene: the Babylon.js scene
  80939. */
  80940. GLTFUtils.GetDefaultMaterial = function (scene) {
  80941. if (!GLTFUtils._DefaultMaterial) {
  80942. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  80943. "precision highp float;",
  80944. "",
  80945. "uniform mat4 worldView;",
  80946. "uniform mat4 projection;",
  80947. "",
  80948. "attribute vec3 position;",
  80949. "",
  80950. "void main(void)",
  80951. "{",
  80952. " gl_Position = projection * worldView * vec4(position, 1.0);",
  80953. "}"
  80954. ].join("\n");
  80955. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  80956. "precision highp float;",
  80957. "",
  80958. "uniform vec4 u_emission;",
  80959. "",
  80960. "void main(void)",
  80961. "{",
  80962. " gl_FragColor = u_emission;",
  80963. "}"
  80964. ].join("\n");
  80965. var shaderPath = {
  80966. vertex: "GLTFDefaultMaterial",
  80967. fragment: "GLTFDefaultMaterial"
  80968. };
  80969. var options = {
  80970. attributes: ["position"],
  80971. uniforms: ["worldView", "projection", "u_emission"],
  80972. samplers: new Array(),
  80973. needAlphaBlending: false
  80974. };
  80975. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  80976. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  80977. }
  80978. return GLTFUtils._DefaultMaterial;
  80979. };
  80980. // The GLTF default material
  80981. GLTFUtils._DefaultMaterial = null;
  80982. return GLTFUtils;
  80983. }());
  80984. GLTF1.GLTFUtils = GLTFUtils;
  80985. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  80986. })(BABYLON || (BABYLON = {}));
  80987. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  80988. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  80989. var BABYLON;
  80990. (function (BABYLON) {
  80991. var GLTF1;
  80992. (function (GLTF1) {
  80993. var GLTFLoaderExtension = /** @class */ (function () {
  80994. function GLTFLoaderExtension(name) {
  80995. this._name = name;
  80996. }
  80997. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  80998. get: function () {
  80999. return this._name;
  81000. },
  81001. enumerable: true,
  81002. configurable: true
  81003. });
  81004. /**
  81005. * Defines an override for loading the runtime
  81006. * Return true to stop further extensions from loading the runtime
  81007. */
  81008. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  81009. return false;
  81010. };
  81011. /**
  81012. * Defines an onverride for creating gltf runtime
  81013. * Return true to stop further extensions from creating the runtime
  81014. */
  81015. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  81016. return false;
  81017. };
  81018. /**
  81019. * Defines an override for loading buffers
  81020. * Return true to stop further extensions from loading this buffer
  81021. */
  81022. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  81023. return false;
  81024. };
  81025. /**
  81026. * Defines an override for loading texture buffers
  81027. * Return true to stop further extensions from loading this texture data
  81028. */
  81029. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  81030. return false;
  81031. };
  81032. /**
  81033. * Defines an override for creating textures
  81034. * Return true to stop further extensions from loading this texture
  81035. */
  81036. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  81037. return false;
  81038. };
  81039. /**
  81040. * Defines an override for loading shader strings
  81041. * Return true to stop further extensions from loading this shader data
  81042. */
  81043. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  81044. return false;
  81045. };
  81046. /**
  81047. * Defines an override for loading materials
  81048. * Return true to stop further extensions from loading this material
  81049. */
  81050. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  81051. return false;
  81052. };
  81053. // ---------
  81054. // Utilities
  81055. // ---------
  81056. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  81057. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  81058. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  81059. }, function () {
  81060. setTimeout(function () {
  81061. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  81062. });
  81063. });
  81064. };
  81065. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  81066. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  81067. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  81068. }, function () {
  81069. setTimeout(function () {
  81070. onSuccess();
  81071. });
  81072. });
  81073. };
  81074. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  81075. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  81076. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  81077. }, function () {
  81078. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  81079. });
  81080. };
  81081. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  81082. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  81083. };
  81084. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  81085. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  81086. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  81087. }, function () {
  81088. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  81089. });
  81090. };
  81091. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  81092. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  81093. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  81094. }, function () {
  81095. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  81096. });
  81097. };
  81098. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  81099. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  81100. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  81101. }, function () {
  81102. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  81103. });
  81104. };
  81105. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  81106. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  81107. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  81108. }, function () {
  81109. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  81110. });
  81111. };
  81112. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  81113. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  81114. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  81115. if (func(loaderExtension)) {
  81116. return;
  81117. }
  81118. }
  81119. defaultFunc();
  81120. };
  81121. return GLTFLoaderExtension;
  81122. }());
  81123. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  81124. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  81125. })(BABYLON || (BABYLON = {}));
  81126. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  81127. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  81128. var BABYLON;
  81129. (function (BABYLON) {
  81130. var GLTF1;
  81131. (function (GLTF1) {
  81132. var BinaryExtensionBufferName = "binary_glTF";
  81133. ;
  81134. ;
  81135. var GLTFBinaryExtension = /** @class */ (function (_super) {
  81136. __extends(GLTFBinaryExtension, _super);
  81137. function GLTFBinaryExtension() {
  81138. return _super.call(this, "KHR_binary_glTF") || this;
  81139. }
  81140. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  81141. var extensionsUsed = data.json.extensionsUsed;
  81142. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  81143. return false;
  81144. }
  81145. this._bin = data.bin;
  81146. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  81147. return true;
  81148. };
  81149. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  81150. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  81151. return false;
  81152. }
  81153. if (id !== BinaryExtensionBufferName) {
  81154. return false;
  81155. }
  81156. onSuccess(this._bin);
  81157. return true;
  81158. };
  81159. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  81160. var texture = gltfRuntime.textures[id];
  81161. var source = gltfRuntime.images[texture.source];
  81162. if (!source.extensions || !(this.name in source.extensions)) {
  81163. return false;
  81164. }
  81165. var sourceExt = source.extensions[this.name];
  81166. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  81167. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  81168. onSuccess(buffer);
  81169. return true;
  81170. };
  81171. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  81172. var shader = gltfRuntime.shaders[id];
  81173. if (!shader.extensions || !(this.name in shader.extensions)) {
  81174. return false;
  81175. }
  81176. var binaryExtensionShader = shader.extensions[this.name];
  81177. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  81178. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  81179. setTimeout(function () {
  81180. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  81181. onSuccess(shaderString);
  81182. });
  81183. return true;
  81184. };
  81185. return GLTFBinaryExtension;
  81186. }(GLTF1.GLTFLoaderExtension));
  81187. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  81188. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  81189. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  81190. })(BABYLON || (BABYLON = {}));
  81191. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  81192. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  81193. var BABYLON;
  81194. (function (BABYLON) {
  81195. var GLTF1;
  81196. (function (GLTF1) {
  81197. ;
  81198. ;
  81199. ;
  81200. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  81201. __extends(GLTFMaterialsCommonExtension, _super);
  81202. function GLTFMaterialsCommonExtension() {
  81203. return _super.call(this, "KHR_materials_common") || this;
  81204. }
  81205. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  81206. if (!gltfRuntime.extensions)
  81207. return false;
  81208. var extension = gltfRuntime.extensions[this.name];
  81209. if (!extension)
  81210. return false;
  81211. // Create lights
  81212. var lights = extension.lights;
  81213. if (lights) {
  81214. for (var thing in lights) {
  81215. var light = lights[thing];
  81216. switch (light.type) {
  81217. case "ambient":
  81218. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  81219. var ambient = light.ambient;
  81220. if (ambient) {
  81221. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  81222. }
  81223. break;
  81224. case "point":
  81225. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  81226. var point = light.point;
  81227. if (point) {
  81228. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  81229. }
  81230. break;
  81231. case "directional":
  81232. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  81233. var directional = light.directional;
  81234. if (directional) {
  81235. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  81236. }
  81237. break;
  81238. case "spot":
  81239. var spot = light.spot;
  81240. if (spot) {
  81241. 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);
  81242. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  81243. }
  81244. break;
  81245. default:
  81246. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  81247. break;
  81248. }
  81249. }
  81250. }
  81251. return false;
  81252. };
  81253. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  81254. var material = gltfRuntime.materials[id];
  81255. if (!material || !material.extensions)
  81256. return false;
  81257. var extension = material.extensions[this.name];
  81258. if (!extension)
  81259. return false;
  81260. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  81261. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  81262. if (extension.technique === "CONSTANT") {
  81263. standardMaterial.disableLighting = true;
  81264. }
  81265. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  81266. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  81267. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  81268. // Ambient
  81269. if (typeof extension.values.ambient === "string") {
  81270. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  81271. }
  81272. else {
  81273. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  81274. }
  81275. // Diffuse
  81276. if (typeof extension.values.diffuse === "string") {
  81277. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  81278. }
  81279. else {
  81280. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  81281. }
  81282. // Emission
  81283. if (typeof extension.values.emission === "string") {
  81284. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  81285. }
  81286. else {
  81287. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  81288. }
  81289. // Specular
  81290. if (typeof extension.values.specular === "string") {
  81291. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  81292. }
  81293. else {
  81294. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  81295. }
  81296. return true;
  81297. };
  81298. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  81299. // Create buffer from texture url
  81300. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  81301. // Create texture from buffer
  81302. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  81303. }, onError);
  81304. };
  81305. return GLTFMaterialsCommonExtension;
  81306. }(GLTF1.GLTFLoaderExtension));
  81307. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  81308. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  81309. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  81310. })(BABYLON || (BABYLON = {}));
  81311. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  81312. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  81313. var BABYLON;
  81314. (function (BABYLON) {
  81315. var GLTF2;
  81316. (function (GLTF2) {
  81317. /**
  81318. * Enums
  81319. */
  81320. var EComponentType;
  81321. (function (EComponentType) {
  81322. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  81323. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  81324. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  81325. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  81326. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  81327. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  81328. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  81329. var EMeshPrimitiveMode;
  81330. (function (EMeshPrimitiveMode) {
  81331. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  81332. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  81333. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  81334. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  81335. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  81336. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  81337. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  81338. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  81339. var ETextureMagFilter;
  81340. (function (ETextureMagFilter) {
  81341. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  81342. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  81343. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  81344. var ETextureMinFilter;
  81345. (function (ETextureMinFilter) {
  81346. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  81347. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  81348. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  81349. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  81350. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  81351. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  81352. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  81353. var ETextureWrapMode;
  81354. (function (ETextureWrapMode) {
  81355. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  81356. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  81357. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  81358. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  81359. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  81360. })(BABYLON || (BABYLON = {}));
  81361. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  81362. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  81363. var BABYLON;
  81364. (function (BABYLON) {
  81365. var GLTF2;
  81366. (function (GLTF2) {
  81367. var GLTFLoaderTracker = /** @class */ (function () {
  81368. function GLTFLoaderTracker(onComplete) {
  81369. this._pendingCount = 0;
  81370. this._callback = onComplete;
  81371. }
  81372. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  81373. this._pendingCount++;
  81374. };
  81375. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  81376. if (--this._pendingCount === 0) {
  81377. this._callback();
  81378. }
  81379. };
  81380. return GLTFLoaderTracker;
  81381. }());
  81382. var GLTFLoader = /** @class */ (function () {
  81383. function GLTFLoader(parent) {
  81384. this._disposed = false;
  81385. this._renderReady = false;
  81386. this._requests = new Array();
  81387. this._renderReadyObservable = new BABYLON.Observable();
  81388. // Count of pending work that needs to complete before the asset is rendered.
  81389. this._renderPendingCount = 0;
  81390. // Count of pending work that needs to complete before the loader is disposed.
  81391. this._loaderPendingCount = 0;
  81392. this._loaderTrackers = new Array();
  81393. this._parent = parent;
  81394. if (!GLTFLoader._progressEventFactory) {
  81395. if (typeof window["ProgressEvent"] === "function") {
  81396. GLTFLoader._progressEventFactory = GLTFLoader._createProgressEventByConstructor;
  81397. }
  81398. else {
  81399. GLTFLoader._progressEventFactory = GLTFLoader._createProgressEventByDocument;
  81400. }
  81401. }
  81402. }
  81403. GLTFLoader.RegisterExtension = function (extension) {
  81404. if (GLTFLoader.Extensions[extension.name]) {
  81405. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  81406. return;
  81407. }
  81408. GLTFLoader.Extensions[extension.name] = extension;
  81409. // Keep the order of registration so that extensions registered first are called first.
  81410. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  81411. };
  81412. GLTFLoader._createProgressEventByConstructor = function (name, data) {
  81413. return new ProgressEvent(name, data);
  81414. };
  81415. GLTFLoader._createProgressEventByDocument = function (name, data) {
  81416. var event = document.createEvent("ProgressEvent");
  81417. event.initProgressEvent(name, false, false, data.lengthComputable, data.loaded, data.total);
  81418. return event;
  81419. };
  81420. GLTFLoader.prototype.dispose = function () {
  81421. if (this._disposed) {
  81422. return;
  81423. }
  81424. this._disposed = true;
  81425. // Abort requests that are not complete
  81426. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  81427. var request = _a[_i];
  81428. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  81429. request.abort();
  81430. }
  81431. }
  81432. // Revoke object urls created during load
  81433. if (this._gltf.textures) {
  81434. for (var _b = 0, _c = this._gltf.textures; _b < _c.length; _b++) {
  81435. var texture = _c[_b];
  81436. if (texture.url) {
  81437. URL.revokeObjectURL(texture.url);
  81438. }
  81439. }
  81440. }
  81441. };
  81442. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  81443. var _this = this;
  81444. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  81445. onSuccess(_this._getMeshes(), [], _this._getSkeletons());
  81446. }, onProgress, onError);
  81447. };
  81448. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  81449. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  81450. };
  81451. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  81452. var _this = this;
  81453. this._tryCatchOnError(function () {
  81454. _this._loadData(data);
  81455. _this._babylonScene = scene;
  81456. _this._rootUrl = rootUrl;
  81457. _this._successCallback = onSuccess;
  81458. _this._progressCallback = onProgress;
  81459. _this._errorCallback = onError;
  81460. _this._addPendingData(_this);
  81461. _this._loadDefaultScene(nodeNames);
  81462. _this._loadAnimations();
  81463. _this._removePendingData(_this);
  81464. });
  81465. };
  81466. GLTFLoader.prototype._onProgress = function () {
  81467. if (!this._progressCallback) {
  81468. return;
  81469. }
  81470. var loaded = 0;
  81471. var total = 0;
  81472. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  81473. var request = _a[_i];
  81474. if (!request._loaded || !request._total) {
  81475. return;
  81476. }
  81477. loaded += request._loaded;
  81478. total += request._total;
  81479. }
  81480. this._progressCallback(GLTFLoader._progressEventFactory("GLTFLoaderProgress", {
  81481. lengthComputable: true,
  81482. loaded: loaded,
  81483. total: total
  81484. }));
  81485. };
  81486. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  81487. if (this._renderReady) {
  81488. func();
  81489. }
  81490. else {
  81491. this._renderReadyObservable.add(func);
  81492. }
  81493. };
  81494. GLTFLoader.prototype._onRenderReady = function () {
  81495. this._rootNode.babylonMesh.setEnabled(true);
  81496. this._startAnimations();
  81497. this._successCallback();
  81498. this._renderReadyObservable.notifyObservers(this);
  81499. };
  81500. GLTFLoader.prototype._onComplete = function () {
  81501. if (this._parent.onComplete) {
  81502. this._parent.onComplete();
  81503. }
  81504. this.dispose();
  81505. };
  81506. GLTFLoader.prototype._loadData = function (data) {
  81507. this._gltf = data.json;
  81508. // Assign the index of each object for convinience.
  81509. GLTFLoader._AssignIndices(this._gltf.accessors);
  81510. GLTFLoader._AssignIndices(this._gltf.animations);
  81511. GLTFLoader._AssignIndices(this._gltf.buffers);
  81512. GLTFLoader._AssignIndices(this._gltf.bufferViews);
  81513. GLTFLoader._AssignIndices(this._gltf.images);
  81514. GLTFLoader._AssignIndices(this._gltf.materials);
  81515. GLTFLoader._AssignIndices(this._gltf.meshes);
  81516. GLTFLoader._AssignIndices(this._gltf.nodes);
  81517. GLTFLoader._AssignIndices(this._gltf.scenes);
  81518. GLTFLoader._AssignIndices(this._gltf.skins);
  81519. GLTFLoader._AssignIndices(this._gltf.textures);
  81520. if (data.bin) {
  81521. var buffers = this._gltf.buffers;
  81522. if (buffers && buffers[0] && !buffers[0].uri) {
  81523. var binaryBuffer = buffers[0];
  81524. if (binaryBuffer.byteLength != data.bin.byteLength) {
  81525. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  81526. }
  81527. binaryBuffer.loadedData = data.bin;
  81528. }
  81529. else {
  81530. BABYLON.Tools.Warn("Unexpected BIN chunk");
  81531. }
  81532. }
  81533. };
  81534. GLTFLoader.prototype._getMeshes = function () {
  81535. var meshes = new Array();
  81536. // Root mesh is always first.
  81537. meshes.push(this._rootNode.babylonMesh);
  81538. var nodes = this._gltf.nodes;
  81539. if (nodes) {
  81540. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  81541. var node = nodes_1[_i];
  81542. if (node.babylonMesh) {
  81543. meshes.push(node.babylonMesh);
  81544. }
  81545. }
  81546. }
  81547. return meshes;
  81548. };
  81549. GLTFLoader.prototype._getSkeletons = function () {
  81550. var skeletons = new Array();
  81551. var skins = this._gltf.skins;
  81552. if (skins) {
  81553. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  81554. var skin = skins_1[_i];
  81555. if (skin.babylonSkeleton) {
  81556. skeletons.push(skin.babylonSkeleton);
  81557. }
  81558. }
  81559. }
  81560. return skeletons;
  81561. };
  81562. GLTFLoader.prototype._getAnimationTargets = function () {
  81563. var targets = new Array();
  81564. var animations = this._gltf.animations;
  81565. if (animations) {
  81566. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  81567. var animation = animations_1[_i];
  81568. targets.push.apply(targets, animation.targets);
  81569. }
  81570. }
  81571. return targets;
  81572. };
  81573. GLTFLoader.prototype._startAnimations = function () {
  81574. for (var _i = 0, _a = this._getAnimationTargets(); _i < _a.length; _i++) {
  81575. var target = _a[_i];
  81576. this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true);
  81577. }
  81578. };
  81579. GLTFLoader.prototype._loadDefaultScene = function (nodeNames) {
  81580. var scene = GLTFLoader._GetProperty(this._gltf.scenes, this._gltf.scene || 0);
  81581. if (!scene) {
  81582. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  81583. }
  81584. this._loadScene("#/scenes/" + scene.index, scene, nodeNames);
  81585. };
  81586. GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) {
  81587. this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) };
  81588. switch (this._parent.coordinateSystemMode) {
  81589. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  81590. if (!this._babylonScene.useRightHandedSystem) {
  81591. this._rootNode.rotation = [0, 1, 0, 0];
  81592. this._rootNode.scale = [1, 1, -1];
  81593. this._loadTransform(this._rootNode);
  81594. }
  81595. break;
  81596. }
  81597. case BABYLON.GLTFLoaderCoordinateSystemMode.PASS_THROUGH: {
  81598. // do nothing
  81599. break;
  81600. }
  81601. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  81602. this._babylonScene.useRightHandedSystem = true;
  81603. break;
  81604. }
  81605. default: {
  81606. BABYLON.Tools.Error("Invalid coordinate system mode " + this._parent.coordinateSystemMode);
  81607. return;
  81608. }
  81609. }
  81610. if (this._parent.onMeshLoaded) {
  81611. this._parent.onMeshLoaded(this._rootNode.babylonMesh);
  81612. }
  81613. var nodeIndices = scene.nodes;
  81614. this._traverseNodes(context, nodeIndices, function (node, parentNode) {
  81615. node.parent = parentNode;
  81616. return true;
  81617. }, this._rootNode);
  81618. if (nodeNames) {
  81619. if (!(nodeNames instanceof Array)) {
  81620. nodeNames = [nodeNames];
  81621. }
  81622. var filteredNodeIndices_1 = new Array();
  81623. this._traverseNodes(context, nodeIndices, function (node) {
  81624. if (nodeNames.indexOf(node.name) !== -1) {
  81625. filteredNodeIndices_1.push(node.index);
  81626. return false;
  81627. }
  81628. return true;
  81629. }, this._rootNode);
  81630. nodeIndices = filteredNodeIndices_1;
  81631. }
  81632. for (var _i = 0, nodeIndices_1 = nodeIndices; _i < nodeIndices_1.length; _i++) {
  81633. var index = nodeIndices_1[_i];
  81634. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  81635. if (!node) {
  81636. throw new Error(context + ": Failed to find node " + index);
  81637. }
  81638. this._loadNode("#/nodes/" + index, node);
  81639. }
  81640. // Disable the root mesh until the asset is ready to render.
  81641. this._rootNode.babylonMesh.setEnabled(false);
  81642. };
  81643. GLTFLoader.prototype._loadNode = function (context, node) {
  81644. if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) {
  81645. return;
  81646. }
  81647. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  81648. node.babylonMesh.hasVertexAlpha = true;
  81649. this._loadTransform(node);
  81650. if (node.mesh != null) {
  81651. var mesh = GLTFLoader._GetProperty(this._gltf.meshes, node.mesh);
  81652. if (!mesh) {
  81653. throw new Error(context + ": Failed to find mesh " + node.mesh);
  81654. }
  81655. this._loadMesh("#/meshes/" + node.mesh, node, mesh);
  81656. }
  81657. node.babylonMesh.parent = node.parent.babylonMesh;
  81658. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  81659. node.babylonAnimationTargets.push(node.babylonMesh);
  81660. if (node.skin != null) {
  81661. var skin_1 = GLTFLoader._GetProperty(this._gltf.skins, node.skin);
  81662. if (!skin_1) {
  81663. throw new Error(context + ": Failed to find skin " + node.skin);
  81664. }
  81665. this._loadSkinAsync("#/skins/" + node.skin, skin_1, function () {
  81666. node.babylonMesh.skeleton = skin_1.babylonSkeleton;
  81667. node.babylonMesh._refreshBoundingInfo(true);
  81668. });
  81669. node.babylonMesh.parent = this._rootNode.babylonMesh;
  81670. node.babylonMesh.position = BABYLON.Vector3.Zero();
  81671. node.babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  81672. node.babylonMesh.scaling = BABYLON.Vector3.One();
  81673. }
  81674. if (node.camera != null) {
  81675. // TODO: handle cameras
  81676. }
  81677. if (node.children) {
  81678. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  81679. var index = _a[_i];
  81680. var childNode = GLTFLoader._GetProperty(this._gltf.nodes, index);
  81681. if (!childNode) {
  81682. throw new Error(context + ": Failed to find child node " + index);
  81683. }
  81684. this._loadNode("#/nodes/" + index, childNode);
  81685. }
  81686. }
  81687. if (this._parent.onMeshLoaded) {
  81688. this._parent.onMeshLoaded(node.babylonMesh);
  81689. }
  81690. };
  81691. GLTFLoader.prototype._loadMesh = function (context, node, mesh) {
  81692. var _this = this;
  81693. var primitives = mesh.primitives;
  81694. if (!primitives || primitives.length === 0) {
  81695. throw new Error(context + ": Primitives are missing");
  81696. }
  81697. this._createMorphTargets(context, node, mesh);
  81698. this._loadAllVertexDataAsync(context, mesh, function () {
  81699. _this._loadMorphTargets(context, node, mesh);
  81700. var vertexData = new BABYLON.VertexData();
  81701. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  81702. var primitive = primitives_1[_i];
  81703. vertexData.merge(primitive.vertexData);
  81704. }
  81705. new BABYLON.Geometry(node.babylonMesh.name, _this._babylonScene, vertexData, false, node.babylonMesh);
  81706. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  81707. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  81708. node.babylonMesh.subMeshes = [];
  81709. var verticesStart = 0;
  81710. var indicesStart = 0;
  81711. for (var index = 0; index < primitives.length; index++) {
  81712. var vertexData_1 = primitives[index].vertexData;
  81713. var verticesCount = vertexData_1.positions.length;
  81714. var indicesCount = vertexData_1.indices.length;
  81715. BABYLON.SubMesh.AddToMesh(index, verticesStart, verticesCount, indicesStart, indicesCount, node.babylonMesh);
  81716. verticesStart += verticesCount;
  81717. indicesStart += indicesCount;
  81718. }
  81719. ;
  81720. });
  81721. if (primitives.length === 1) {
  81722. var primitive = primitives[0];
  81723. if (primitive.material == null) {
  81724. node.babylonMesh.material = this._getDefaultMaterial();
  81725. }
  81726. else {
  81727. var material = GLTFLoader._GetProperty(this._gltf.materials, primitive.material);
  81728. if (!material) {
  81729. throw new Error(context + ": Failed to find material " + primitive.material);
  81730. }
  81731. this._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  81732. if (isNew && _this._parent.onMaterialLoaded) {
  81733. _this._parent.onMaterialLoaded(babylonMaterial);
  81734. }
  81735. node.babylonMesh.material = babylonMaterial;
  81736. });
  81737. }
  81738. }
  81739. else {
  81740. var multiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  81741. node.babylonMesh.material = multiMaterial;
  81742. var subMaterials_1 = multiMaterial.subMaterials;
  81743. var _loop_1 = function (index) {
  81744. var primitive = primitives[index];
  81745. if (primitive.material == null) {
  81746. subMaterials_1[index] = this_1._getDefaultMaterial();
  81747. }
  81748. else {
  81749. var material = GLTFLoader._GetProperty(this_1._gltf.materials, primitive.material);
  81750. if (!material) {
  81751. throw new Error(context + ": Failed to find material " + primitive.material);
  81752. }
  81753. this_1._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  81754. if (isNew && _this._parent.onMaterialLoaded) {
  81755. _this._parent.onMaterialLoaded(babylonMaterial);
  81756. }
  81757. subMaterials_1[index] = babylonMaterial;
  81758. });
  81759. }
  81760. };
  81761. var this_1 = this;
  81762. for (var index = 0; index < primitives.length; index++) {
  81763. _loop_1(index);
  81764. }
  81765. ;
  81766. }
  81767. };
  81768. GLTFLoader.prototype._loadAllVertexDataAsync = function (context, mesh, onSuccess) {
  81769. var primitives = mesh.primitives;
  81770. var numRemainingPrimitives = primitives.length;
  81771. var _loop_2 = function (index) {
  81772. var primitive = primitives[index];
  81773. this_2._loadVertexDataAsync(context + "/primitive/" + index, mesh, primitive, function (vertexData) {
  81774. primitive.vertexData = vertexData;
  81775. if (--numRemainingPrimitives === 0) {
  81776. onSuccess();
  81777. }
  81778. });
  81779. };
  81780. var this_2 = this;
  81781. for (var index = 0; index < primitives.length; index++) {
  81782. _loop_2(index);
  81783. }
  81784. };
  81785. /**
  81786. * Converts a data bufferview into a Float4 Texture Coordinate Array, based on the accessor component type
  81787. * @param {ArrayBufferView} data
  81788. * @param {IGLTFAccessor} accessor
  81789. */
  81790. GLTFLoader.prototype._convertToFloat4TextureCoordArray = function (context, data, accessor) {
  81791. if (accessor.componentType == GLTF2.EComponentType.FLOAT) {
  81792. return data;
  81793. }
  81794. var buffer = data;
  81795. var factor = 1;
  81796. switch (accessor.componentType) {
  81797. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  81798. factor = 1 / 255;
  81799. break;
  81800. }
  81801. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  81802. factor = 1 / 65535;
  81803. break;
  81804. }
  81805. default: {
  81806. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  81807. }
  81808. }
  81809. var result = new Float32Array(accessor.count * 2);
  81810. for (var i = 0; i < result.length; ++i) {
  81811. result[i] = buffer[i] * factor;
  81812. }
  81813. return result;
  81814. };
  81815. /**
  81816. * Converts a data bufferview into a Float4 Color Array, based on the accessor component type
  81817. * @param {ArrayBufferView} data
  81818. * @param {IGLTFAccessor} accessor
  81819. */
  81820. GLTFLoader.prototype._convertToFloat4ColorArray = function (context, data, accessor) {
  81821. var colorComponentCount = GLTFLoader._GetNumComponents(accessor.type);
  81822. if (colorComponentCount === 4 && accessor.componentType === GLTF2.EComponentType.FLOAT) {
  81823. return data;
  81824. }
  81825. var buffer = data;
  81826. var factor = 1;
  81827. switch (accessor.componentType) {
  81828. case GLTF2.EComponentType.FLOAT: {
  81829. factor = 1;
  81830. break;
  81831. }
  81832. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  81833. factor = 1 / 255;
  81834. break;
  81835. }
  81836. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  81837. factor = 1 / 65535;
  81838. break;
  81839. }
  81840. default: {
  81841. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  81842. }
  81843. }
  81844. var result = new Float32Array(accessor.count * 4);
  81845. if (colorComponentCount === 4) {
  81846. for (var i = 0; i < result.length; ++i) {
  81847. result[i] = buffer[i] * factor;
  81848. }
  81849. }
  81850. else {
  81851. var offset = 0;
  81852. for (var i = 0; i < result.length; ++i) {
  81853. if ((i + 1) % 4 === 0) {
  81854. result[i] = 1;
  81855. }
  81856. else {
  81857. result[i] = buffer[offset++] * factor;
  81858. }
  81859. }
  81860. }
  81861. return result;
  81862. };
  81863. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  81864. var _this = this;
  81865. var attributes = primitive.attributes;
  81866. if (!attributes) {
  81867. throw new Error(context + ": Attributes are missing");
  81868. }
  81869. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  81870. // TODO: handle other primitive modes
  81871. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  81872. }
  81873. var vertexData = new BABYLON.VertexData();
  81874. var numRemainingAttributes = Object.keys(attributes).length;
  81875. var _loop_3 = function (attribute) {
  81876. var accessor = GLTFLoader._GetProperty(this_3._gltf.accessors, attributes[attribute]);
  81877. if (!accessor) {
  81878. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  81879. }
  81880. this_3._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  81881. switch (attribute) {
  81882. case "POSITION": {
  81883. vertexData.positions = data;
  81884. break;
  81885. }
  81886. case "NORMAL": {
  81887. vertexData.normals = data;
  81888. break;
  81889. }
  81890. case "TANGENT": {
  81891. vertexData.tangents = data;
  81892. break;
  81893. }
  81894. case "TEXCOORD_0": {
  81895. vertexData.uvs = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  81896. break;
  81897. }
  81898. case "TEXCOORD_1": {
  81899. vertexData.uvs2 = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  81900. break;
  81901. }
  81902. case "JOINTS_0": {
  81903. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  81904. break;
  81905. }
  81906. case "WEIGHTS_0": {
  81907. //TODO: need to add support for normalized weights.
  81908. vertexData.matricesWeights = data;
  81909. break;
  81910. }
  81911. case "COLOR_0": {
  81912. vertexData.colors = _this._convertToFloat4ColorArray(context, data, accessor);
  81913. break;
  81914. }
  81915. default: {
  81916. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  81917. break;
  81918. }
  81919. }
  81920. if (--numRemainingAttributes === 0) {
  81921. if (primitive.indices == null) {
  81922. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  81923. for (var i = 0; i < vertexData.indices.length; i++) {
  81924. vertexData.indices[i] = i;
  81925. }
  81926. onSuccess(vertexData);
  81927. }
  81928. else {
  81929. var indicesAccessor = GLTFLoader._GetProperty(_this._gltf.accessors, primitive.indices);
  81930. if (!indicesAccessor) {
  81931. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  81932. }
  81933. _this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, function (data) {
  81934. vertexData.indices = data;
  81935. onSuccess(vertexData);
  81936. });
  81937. }
  81938. }
  81939. });
  81940. };
  81941. var this_3 = this;
  81942. for (var attribute in attributes) {
  81943. _loop_3(attribute);
  81944. }
  81945. };
  81946. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh) {
  81947. var primitives = mesh.primitives;
  81948. var targets = primitives[0].targets;
  81949. if (!targets) {
  81950. return;
  81951. }
  81952. for (var _i = 0, primitives_2 = primitives; _i < primitives_2.length; _i++) {
  81953. var primitive = primitives_2[_i];
  81954. if (!primitive.targets || primitive.targets.length != targets.length) {
  81955. throw new Error(context + ": All primitives are required to list the same number of targets");
  81956. }
  81957. }
  81958. var morphTargetManager = new BABYLON.MorphTargetManager();
  81959. node.babylonMesh.morphTargetManager = morphTargetManager;
  81960. for (var index = 0; index < targets.length; index++) {
  81961. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  81962. morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  81963. }
  81964. };
  81965. GLTFLoader.prototype._loadMorphTargets = function (context, node, mesh) {
  81966. var morphTargetManager = node.babylonMesh.morphTargetManager;
  81967. if (!morphTargetManager) {
  81968. return;
  81969. }
  81970. this._loadAllMorphTargetVertexDataAsync(context, node, mesh, function () {
  81971. var numTargets = morphTargetManager.numTargets;
  81972. for (var index = 0; index < numTargets; index++) {
  81973. var vertexData = new BABYLON.VertexData();
  81974. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  81975. var primitive = _a[_i];
  81976. vertexData.merge(primitive.targetsVertexData[index], { tangentLength: 3 });
  81977. }
  81978. if (!vertexData.positions) {
  81979. throw new Error(context + ": Positions are missing");
  81980. }
  81981. var target = morphTargetManager.getTarget(index);
  81982. target.setPositions(vertexData.positions);
  81983. target.setNormals(vertexData.normals);
  81984. target.setTangents(vertexData.tangents);
  81985. }
  81986. });
  81987. };
  81988. GLTFLoader.prototype._loadAllMorphTargetVertexDataAsync = function (context, node, mesh, onSuccess) {
  81989. var numRemainingTargets = mesh.primitives.length * node.babylonMesh.morphTargetManager.numTargets;
  81990. var _loop_4 = function (primitive) {
  81991. var targets = primitive.targets;
  81992. primitive.targetsVertexData = new Array(targets.length);
  81993. var _loop_5 = function (index) {
  81994. this_4._loadMorphTargetVertexDataAsync(context + "/targets/" + index, primitive.vertexData, targets[index], function (vertexData) {
  81995. primitive.targetsVertexData[index] = vertexData;
  81996. if (--numRemainingTargets === 0) {
  81997. onSuccess();
  81998. }
  81999. });
  82000. };
  82001. for (var index = 0; index < targets.length; index++) {
  82002. _loop_5(index);
  82003. }
  82004. };
  82005. var this_4 = this;
  82006. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  82007. var primitive = _a[_i];
  82008. _loop_4(primitive);
  82009. }
  82010. };
  82011. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, vertexData, attributes, onSuccess) {
  82012. var targetVertexData = new BABYLON.VertexData();
  82013. var numRemainingAttributes = Object.keys(attributes).length;
  82014. var _loop_6 = function (attribute) {
  82015. var accessor = GLTFLoader._GetProperty(this_5._gltf.accessors, attributes[attribute]);
  82016. if (!accessor) {
  82017. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  82018. }
  82019. this_5._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  82020. // glTF stores morph target information as deltas while babylon.js expects the final data.
  82021. // As a result we have to add the original data to the delta to calculate the final data.
  82022. var values = data;
  82023. switch (attribute) {
  82024. case "POSITION": {
  82025. for (var i = 0; i < values.length; i++) {
  82026. values[i] += vertexData.positions[i];
  82027. }
  82028. targetVertexData.positions = values;
  82029. break;
  82030. }
  82031. case "NORMAL": {
  82032. for (var i = 0; i < values.length; i++) {
  82033. values[i] += vertexData.normals[i];
  82034. }
  82035. targetVertexData.normals = values;
  82036. break;
  82037. }
  82038. case "TANGENT": {
  82039. // Tangent data for morph targets is stored as xyz delta.
  82040. // The vertexData.tangent is stored as xyzw.
  82041. // So we need to skip every fourth vertexData.tangent.
  82042. for (var i = 0, j = 0; i < values.length; i++, j++) {
  82043. values[i] += vertexData.tangents[j];
  82044. if ((i + 1) % 3 == 0) {
  82045. j++;
  82046. }
  82047. }
  82048. targetVertexData.tangents = values;
  82049. break;
  82050. }
  82051. default: {
  82052. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  82053. break;
  82054. }
  82055. }
  82056. if (--numRemainingAttributes === 0) {
  82057. onSuccess(targetVertexData);
  82058. }
  82059. });
  82060. };
  82061. var this_5 = this;
  82062. for (var attribute in attributes) {
  82063. _loop_6(attribute);
  82064. }
  82065. };
  82066. GLTFLoader.prototype._loadTransform = function (node) {
  82067. var position = BABYLON.Vector3.Zero();
  82068. var rotation = BABYLON.Quaternion.Identity();
  82069. var scaling = BABYLON.Vector3.One();
  82070. if (node.matrix) {
  82071. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  82072. matrix.decompose(scaling, rotation, position);
  82073. }
  82074. else {
  82075. if (node.translation)
  82076. position = BABYLON.Vector3.FromArray(node.translation);
  82077. if (node.rotation)
  82078. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  82079. if (node.scale)
  82080. scaling = BABYLON.Vector3.FromArray(node.scale);
  82081. }
  82082. node.babylonMesh.position = position;
  82083. node.babylonMesh.rotationQuaternion = rotation;
  82084. node.babylonMesh.scaling = scaling;
  82085. };
  82086. GLTFLoader.prototype._loadSkinAsync = function (context, skin, onSuccess) {
  82087. var _this = this;
  82088. if (skin.babylonSkeleton) {
  82089. onSuccess();
  82090. return;
  82091. }
  82092. var skeletonId = "skeleton" + skin.index;
  82093. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  82094. if (skin.inverseBindMatrices == null) {
  82095. this._loadBones(context, skin, null);
  82096. onSuccess();
  82097. }
  82098. else {
  82099. var accessor = GLTFLoader._GetProperty(this._gltf.accessors, skin.inverseBindMatrices);
  82100. if (!accessor) {
  82101. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  82102. }
  82103. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  82104. _this._loadBones(context, skin, data);
  82105. onSuccess();
  82106. });
  82107. }
  82108. };
  82109. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  82110. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  82111. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  82112. node.babylonAnimationTargets.push(babylonBone);
  82113. return babylonBone;
  82114. };
  82115. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  82116. var babylonBones = {};
  82117. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  82118. var index = _a[_i];
  82119. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  82120. if (!node) {
  82121. throw new Error(context + ": Failed to find joint " + index);
  82122. }
  82123. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  82124. }
  82125. };
  82126. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  82127. var babylonBone = babylonBones[node.index];
  82128. if (babylonBone) {
  82129. return babylonBone;
  82130. }
  82131. var boneIndex = skin.joints.indexOf(node.index);
  82132. var baseMatrix = BABYLON.Matrix.Identity();
  82133. if (inverseBindMatrixData && boneIndex !== -1) {
  82134. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  82135. baseMatrix.invertToRef(baseMatrix);
  82136. }
  82137. var babylonParentBone = null;
  82138. if (node.parent !== this._rootNode) {
  82139. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  82140. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  82141. }
  82142. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  82143. babylonBones[node.index] = babylonBone;
  82144. return babylonBone;
  82145. };
  82146. GLTFLoader.prototype._getNodeMatrix = function (node) {
  82147. return node.matrix ?
  82148. BABYLON.Matrix.FromArray(node.matrix) :
  82149. 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());
  82150. };
  82151. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  82152. for (var _i = 0, indices_1 = indices; _i < indices_1.length; _i++) {
  82153. var index = indices_1[_i];
  82154. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  82155. if (!node) {
  82156. throw new Error(context + ": Failed to find node " + index);
  82157. }
  82158. this._traverseNode(context, node, action, parentNode);
  82159. }
  82160. };
  82161. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  82162. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  82163. return;
  82164. }
  82165. if (!action(node, parentNode)) {
  82166. return;
  82167. }
  82168. if (node.children) {
  82169. this._traverseNodes(context, node.children, action, node);
  82170. }
  82171. };
  82172. GLTFLoader.prototype._loadAnimations = function () {
  82173. var animations = this._gltf.animations;
  82174. if (!animations) {
  82175. return;
  82176. }
  82177. for (var index = 0; index < animations.length; index++) {
  82178. var animation = animations[index];
  82179. this._loadAnimation("#/animations/" + index, animation);
  82180. }
  82181. };
  82182. GLTFLoader.prototype._loadAnimation = function (context, animation) {
  82183. animation.targets = [];
  82184. for (var index = 0; index < animation.channels.length; index++) {
  82185. var channel = GLTFLoader._GetProperty(animation.channels, index);
  82186. if (!channel) {
  82187. throw new Error(context + ": Failed to find channel " + index);
  82188. }
  82189. var sampler = GLTFLoader._GetProperty(animation.samplers, channel.sampler);
  82190. if (!sampler) {
  82191. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  82192. }
  82193. this._loadAnimationChannel(animation, context + "/channels/" + index, channel, context + "/samplers/" + channel.sampler, sampler);
  82194. }
  82195. };
  82196. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  82197. var targetNode = GLTFLoader._GetProperty(this._gltf.nodes, channel.target.node);
  82198. if (!targetNode) {
  82199. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  82200. }
  82201. var targetPath;
  82202. var animationType;
  82203. switch (channel.target.path) {
  82204. case "translation": {
  82205. targetPath = "position";
  82206. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  82207. break;
  82208. }
  82209. case "rotation": {
  82210. targetPath = "rotationQuaternion";
  82211. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  82212. break;
  82213. }
  82214. case "scale": {
  82215. targetPath = "scaling";
  82216. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  82217. break;
  82218. }
  82219. case "weights": {
  82220. targetPath = "influence";
  82221. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  82222. break;
  82223. }
  82224. default: {
  82225. throw new Error(channelContext + ": Invalid target path " + channel.target.path);
  82226. }
  82227. }
  82228. var inputData;
  82229. var outputData;
  82230. var checkSuccess = function () {
  82231. if (!inputData || !outputData) {
  82232. return;
  82233. }
  82234. var outputBufferOffset = 0;
  82235. var getNextOutputValue;
  82236. switch (targetPath) {
  82237. case "position": {
  82238. getNextOutputValue = function () {
  82239. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  82240. outputBufferOffset += 3;
  82241. return value;
  82242. };
  82243. break;
  82244. }
  82245. case "rotationQuaternion": {
  82246. getNextOutputValue = function () {
  82247. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  82248. outputBufferOffset += 4;
  82249. return value;
  82250. };
  82251. break;
  82252. }
  82253. case "scaling": {
  82254. getNextOutputValue = function () {
  82255. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  82256. outputBufferOffset += 3;
  82257. return value;
  82258. };
  82259. break;
  82260. }
  82261. case "influence": {
  82262. getNextOutputValue = function () {
  82263. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  82264. var value = new Array(numTargets);
  82265. for (var i = 0; i < numTargets; i++) {
  82266. value[i] = outputData[outputBufferOffset++];
  82267. }
  82268. return value;
  82269. };
  82270. break;
  82271. }
  82272. }
  82273. var getNextKey;
  82274. switch (sampler.interpolation) {
  82275. case "LINEAR": {
  82276. getNextKey = function (frameIndex) { return ({
  82277. frame: inputData[frameIndex],
  82278. value: getNextOutputValue()
  82279. }); };
  82280. break;
  82281. }
  82282. case "CUBICSPLINE": {
  82283. getNextKey = function (frameIndex) { return ({
  82284. frame: inputData[frameIndex],
  82285. inTangent: getNextOutputValue(),
  82286. value: getNextOutputValue(),
  82287. outTangent: getNextOutputValue()
  82288. }); };
  82289. break;
  82290. }
  82291. default: {
  82292. throw new Error(samplerContext + ": Invalid interpolation " + sampler.interpolation);
  82293. }
  82294. }
  82295. ;
  82296. var keys;
  82297. if (inputData.length === 1) {
  82298. var key = getNextKey(0);
  82299. keys = [
  82300. { frame: key.frame, value: key.value },
  82301. { frame: key.frame + 1, value: key.value }
  82302. ];
  82303. }
  82304. else {
  82305. keys = new Array(inputData.length);
  82306. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  82307. keys[frameIndex] = getNextKey(frameIndex);
  82308. }
  82309. }
  82310. if (targetPath === "influence") {
  82311. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  82312. var _loop_7 = function (targetIndex) {
  82313. var morphTarget = morphTargetManager.getTarget(targetIndex);
  82314. var animationName = (animation.name || "anim" + animation.index) + "_" + targetIndex;
  82315. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  82316. babylonAnimation.setKeys(keys.map(function (key) { return ({
  82317. frame: key.frame,
  82318. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  82319. value: key.value[targetIndex],
  82320. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  82321. }); }));
  82322. morphTarget.animations.push(babylonAnimation);
  82323. animation.targets.push(morphTarget);
  82324. };
  82325. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  82326. _loop_7(targetIndex);
  82327. }
  82328. }
  82329. else {
  82330. var animationName = animation.name || "anim" + animation.index;
  82331. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  82332. babylonAnimation.setKeys(keys);
  82333. if (targetNode.babylonAnimationTargets) {
  82334. for (var _i = 0, _a = targetNode.babylonAnimationTargets; _i < _a.length; _i++) {
  82335. var target = _a[_i];
  82336. target.animations.push(babylonAnimation.clone());
  82337. animation.targets.push(target);
  82338. }
  82339. }
  82340. }
  82341. };
  82342. var inputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.input);
  82343. if (!inputAccessor) {
  82344. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  82345. }
  82346. this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, function (data) {
  82347. inputData = data;
  82348. checkSuccess();
  82349. });
  82350. var outputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.output);
  82351. if (!outputAccessor) {
  82352. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  82353. }
  82354. this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, function (data) {
  82355. outputData = data;
  82356. checkSuccess();
  82357. });
  82358. };
  82359. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  82360. var _this = this;
  82361. this._addPendingData(buffer);
  82362. if (buffer.loadedData) {
  82363. onSuccess(buffer.loadedData);
  82364. this._removePendingData(buffer);
  82365. }
  82366. else if (buffer.loadedObservable) {
  82367. buffer.loadedObservable.add(function (buffer) {
  82368. onSuccess(buffer.loadedData);
  82369. _this._removePendingData(buffer);
  82370. });
  82371. }
  82372. else {
  82373. if (!buffer.uri) {
  82374. throw new Error(context + ": Uri is missing");
  82375. }
  82376. buffer.loadedObservable = new BABYLON.Observable();
  82377. buffer.loadedObservable.add(function (buffer) {
  82378. onSuccess(buffer.loadedData);
  82379. _this._removePendingData(buffer);
  82380. });
  82381. this._loadUriAsync(context, buffer.uri, function (data) {
  82382. buffer.loadedData = data;
  82383. buffer.loadedObservable.notifyObservers(buffer);
  82384. buffer.loadedObservable = undefined;
  82385. });
  82386. }
  82387. };
  82388. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  82389. var buffer = GLTFLoader._GetProperty(this._gltf.buffers, bufferView.buffer);
  82390. if (!buffer) {
  82391. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  82392. }
  82393. this._loadBufferAsync("#/buffers/" + buffer.index, buffer, function (bufferData) {
  82394. var data;
  82395. try {
  82396. data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  82397. }
  82398. catch (e) {
  82399. throw new Error(context + ": " + e.message);
  82400. }
  82401. onSuccess(data);
  82402. });
  82403. };
  82404. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  82405. var _this = this;
  82406. if (accessor.sparse) {
  82407. throw new Error(context + ": Sparse accessors are not currently supported");
  82408. }
  82409. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, accessor.bufferView);
  82410. if (!bufferView) {
  82411. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  82412. }
  82413. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, function (bufferViewData) {
  82414. var numComponents = GLTFLoader._GetNumComponents(accessor.type);
  82415. if (numComponents === 0) {
  82416. throw new Error(context + ": Invalid type " + accessor.type);
  82417. }
  82418. var data;
  82419. var byteOffset = accessor.byteOffset || 0;
  82420. var byteStride = bufferView.byteStride;
  82421. try {
  82422. switch (accessor.componentType) {
  82423. case GLTF2.EComponentType.BYTE: {
  82424. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  82425. break;
  82426. }
  82427. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  82428. data = _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  82429. break;
  82430. }
  82431. case GLTF2.EComponentType.SHORT: {
  82432. data = _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  82433. break;
  82434. }
  82435. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  82436. data = _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  82437. break;
  82438. }
  82439. case GLTF2.EComponentType.UNSIGNED_INT: {
  82440. data = _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  82441. break;
  82442. }
  82443. case GLTF2.EComponentType.FLOAT: {
  82444. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  82445. break;
  82446. }
  82447. default: {
  82448. throw new Error(context + ": Invalid component type " + accessor.componentType);
  82449. }
  82450. }
  82451. }
  82452. catch (e) {
  82453. throw new Error(context + ": " + e);
  82454. }
  82455. onSuccess(data);
  82456. });
  82457. };
  82458. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  82459. byteOffset += data.byteOffset;
  82460. var targetLength = count * numComponents;
  82461. if (byteStride == null || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  82462. return new typedArray(data.buffer, byteOffset, targetLength);
  82463. }
  82464. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  82465. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  82466. var targetBuffer = new typedArray(targetLength);
  82467. var sourceIndex = 0;
  82468. var targetIndex = 0;
  82469. while (targetIndex < targetLength) {
  82470. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  82471. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  82472. targetIndex++;
  82473. }
  82474. sourceIndex += elementStride;
  82475. }
  82476. return targetBuffer;
  82477. };
  82478. GLTFLoader.prototype._addPendingData = function (data) {
  82479. if (!this._renderReady) {
  82480. this._renderPendingCount++;
  82481. }
  82482. this._addLoaderPendingData(data);
  82483. };
  82484. GLTFLoader.prototype._removePendingData = function (data) {
  82485. var _this = this;
  82486. if (!this._renderReady) {
  82487. if (--this._renderPendingCount === 0) {
  82488. this._addLoaderPendingData(this);
  82489. this._compileMaterialsAsync(function () {
  82490. _this._compileShadowGeneratorsAsync(function () {
  82491. _this._removeLoaderPendingData(_this);
  82492. _this._renderReady = true;
  82493. _this._onRenderReady();
  82494. });
  82495. });
  82496. }
  82497. }
  82498. this._removeLoaderPendingData(data);
  82499. };
  82500. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  82501. this._loaderPendingCount++;
  82502. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  82503. var tracker = _a[_i];
  82504. tracker._addPendingData(data);
  82505. }
  82506. };
  82507. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  82508. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  82509. var tracker = _a[_i];
  82510. tracker._removePendingData(data);
  82511. }
  82512. if (--this._loaderPendingCount === 0) {
  82513. this._onComplete();
  82514. }
  82515. };
  82516. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  82517. var _this = this;
  82518. var tracker = new GLTFLoaderTracker(function () {
  82519. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker), 1);
  82520. onComplete();
  82521. });
  82522. this._loaderTrackers.push(tracker);
  82523. this._addLoaderPendingData(tracker);
  82524. action();
  82525. this._removeLoaderPendingData(tracker);
  82526. };
  82527. GLTFLoader.prototype._getDefaultMaterial = function () {
  82528. if (!this._defaultMaterial) {
  82529. var id = "__gltf_default";
  82530. var material = this._babylonScene.getMaterialByName(id);
  82531. if (!material) {
  82532. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  82533. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  82534. material.metallic = 1;
  82535. material.roughness = 1;
  82536. }
  82537. this._defaultMaterial = material;
  82538. }
  82539. return this._defaultMaterial;
  82540. };
  82541. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  82542. var babylonMaterial = material.babylonMaterial;
  82543. // Ensure metallic workflow
  82544. babylonMaterial.metallic = 1;
  82545. babylonMaterial.roughness = 1;
  82546. var properties = material.pbrMetallicRoughness;
  82547. if (!properties) {
  82548. return;
  82549. }
  82550. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  82551. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  82552. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  82553. if (properties.baseColorTexture) {
  82554. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.baseColorTexture.index);
  82555. if (!texture) {
  82556. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  82557. }
  82558. babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord);
  82559. }
  82560. if (properties.metallicRoughnessTexture) {
  82561. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.metallicRoughnessTexture.index);
  82562. if (!texture) {
  82563. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  82564. }
  82565. babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord);
  82566. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  82567. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  82568. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  82569. }
  82570. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  82571. };
  82572. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  82573. if (material.babylonMaterial) {
  82574. assign(material.babylonMaterial, false);
  82575. return;
  82576. }
  82577. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  82578. return;
  82579. }
  82580. this._createPbrMaterial(material);
  82581. this._loadMaterialBaseProperties(context, material);
  82582. this._loadMaterialMetallicRoughnessProperties(context, material);
  82583. assign(material.babylonMaterial, true);
  82584. };
  82585. GLTFLoader.prototype._createPbrMaterial = function (material) {
  82586. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  82587. babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  82588. material.babylonMaterial = babylonMaterial;
  82589. };
  82590. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  82591. var babylonMaterial = material.babylonMaterial;
  82592. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  82593. if (material.doubleSided) {
  82594. babylonMaterial.backFaceCulling = false;
  82595. babylonMaterial.twoSidedLighting = true;
  82596. }
  82597. if (material.normalTexture) {
  82598. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.normalTexture.index);
  82599. if (!texture) {
  82600. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  82601. }
  82602. babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord);
  82603. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  82604. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  82605. if (material.normalTexture.scale != null) {
  82606. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  82607. }
  82608. }
  82609. if (material.occlusionTexture) {
  82610. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.occlusionTexture.index);
  82611. if (!texture) {
  82612. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  82613. }
  82614. babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord);
  82615. babylonMaterial.useAmbientInGrayScale = true;
  82616. if (material.occlusionTexture.strength != null) {
  82617. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  82618. }
  82619. }
  82620. if (material.emissiveTexture) {
  82621. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.emissiveTexture.index);
  82622. if (!texture) {
  82623. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  82624. }
  82625. babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord);
  82626. }
  82627. };
  82628. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  82629. var babylonMaterial = material.babylonMaterial;
  82630. var alphaMode = material.alphaMode || "OPAQUE";
  82631. switch (alphaMode) {
  82632. case "OPAQUE": {
  82633. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  82634. break;
  82635. }
  82636. case "MASK": {
  82637. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  82638. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  82639. if (colorFactor) {
  82640. if (colorFactor[3] == 0) {
  82641. babylonMaterial.alphaCutOff = 1;
  82642. }
  82643. else {
  82644. babylonMaterial.alphaCutOff /= colorFactor[3];
  82645. }
  82646. }
  82647. if (babylonMaterial.albedoTexture) {
  82648. babylonMaterial.albedoTexture.hasAlpha = true;
  82649. }
  82650. break;
  82651. }
  82652. case "BLEND": {
  82653. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  82654. if (colorFactor) {
  82655. babylonMaterial.alpha = colorFactor[3];
  82656. }
  82657. if (babylonMaterial.albedoTexture) {
  82658. babylonMaterial.albedoTexture.hasAlpha = true;
  82659. babylonMaterial.useAlphaFromAlbedoTexture = true;
  82660. }
  82661. break;
  82662. }
  82663. default: {
  82664. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  82665. }
  82666. }
  82667. };
  82668. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  82669. var _this = this;
  82670. var sampler = (texture.sampler == null ? {} : GLTFLoader._GetProperty(this._gltf.samplers, texture.sampler));
  82671. if (!sampler) {
  82672. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  82673. }
  82674. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  82675. var samplingMode = GLTFLoader._GetTextureSamplingMode(sampler.magFilter, sampler.minFilter);
  82676. this._addPendingData(texture);
  82677. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, noMipMaps, false, samplingMode, function () {
  82678. _this._tryCatchOnError(function () {
  82679. _this._removePendingData(texture);
  82680. });
  82681. }, function (message) {
  82682. _this._tryCatchOnError(function () {
  82683. throw new Error(context + ": " + message);
  82684. });
  82685. });
  82686. if (texture.url) {
  82687. babylonTexture.updateURL(texture.url);
  82688. }
  82689. else if (texture.dataReadyObservable) {
  82690. texture.dataReadyObservable.add(function (texture) {
  82691. babylonTexture.updateURL(texture.url);
  82692. });
  82693. }
  82694. else {
  82695. texture.dataReadyObservable = new BABYLON.Observable();
  82696. texture.dataReadyObservable.add(function (texture) {
  82697. babylonTexture.updateURL(texture.url);
  82698. });
  82699. var image_1 = GLTFLoader._GetProperty(this._gltf.images, texture.source);
  82700. if (!image_1) {
  82701. throw new Error(context + ": Failed to find source " + texture.source);
  82702. }
  82703. this._loadImageAsync("#/images/" + image_1.index, image_1, function (data) {
  82704. texture.url = URL.createObjectURL(new Blob([data], { type: image_1.mimeType }));
  82705. texture.dataReadyObservable.notifyObservers(texture);
  82706. texture.dataReadyObservable = undefined;
  82707. });
  82708. }
  82709. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  82710. babylonTexture.wrapU = GLTFLoader._GetTextureWrapMode(sampler.wrapS);
  82711. babylonTexture.wrapV = GLTFLoader._GetTextureWrapMode(sampler.wrapT);
  82712. babylonTexture.name = texture.name || "texture" + texture.index;
  82713. if (this._parent.onTextureLoaded) {
  82714. this._parent.onTextureLoaded(babylonTexture);
  82715. }
  82716. return babylonTexture;
  82717. };
  82718. GLTFLoader.prototype._loadImageAsync = function (context, image, onSuccess) {
  82719. if (image.uri) {
  82720. this._loadUriAsync(context, image.uri, onSuccess);
  82721. }
  82722. else {
  82723. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, image.bufferView);
  82724. if (!bufferView) {
  82725. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  82726. }
  82727. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess);
  82728. }
  82729. };
  82730. GLTFLoader.prototype._loadUriAsync = function (context, uri, onSuccess) {
  82731. var _this = this;
  82732. if (GLTF2.GLTFUtils.IsBase64(uri)) {
  82733. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(uri)));
  82734. return;
  82735. }
  82736. if (!GLTF2.GLTFUtils.ValidateUri(uri)) {
  82737. throw new Error(context + ": Uri '" + uri + "' is invalid");
  82738. }
  82739. var request = BABYLON.Tools.LoadFile(this._rootUrl + uri, function (data) {
  82740. _this._tryCatchOnError(function () {
  82741. onSuccess(new Uint8Array(data));
  82742. });
  82743. }, function (event) {
  82744. _this._tryCatchOnError(function () {
  82745. if (request && !_this._renderReady) {
  82746. request._loaded = event.loaded;
  82747. request._total = event.total;
  82748. _this._onProgress();
  82749. }
  82750. });
  82751. }, this._babylonScene.database, true, function (request) {
  82752. _this._tryCatchOnError(function () {
  82753. throw new Error(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""));
  82754. });
  82755. });
  82756. if (request) {
  82757. request._loaded = null;
  82758. request._total = null;
  82759. this._requests.push(request);
  82760. }
  82761. };
  82762. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  82763. if (this._disposed) {
  82764. return;
  82765. }
  82766. try {
  82767. handler();
  82768. }
  82769. catch (e) {
  82770. BABYLON.Tools.Error("glTF Loader: " + e.message);
  82771. if (this._errorCallback) {
  82772. this._errorCallback(e.message);
  82773. }
  82774. this.dispose();
  82775. }
  82776. };
  82777. GLTFLoader._AssignIndices = function (array) {
  82778. if (array) {
  82779. for (var index = 0; index < array.length; index++) {
  82780. array[index].index = index;
  82781. }
  82782. }
  82783. };
  82784. GLTFLoader._GetProperty = function (array, index) {
  82785. if (!array || index == undefined || !array[index]) {
  82786. return null;
  82787. }
  82788. return array[index];
  82789. };
  82790. GLTFLoader._GetTextureWrapMode = function (mode) {
  82791. // Set defaults if undefined
  82792. mode = mode == undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  82793. switch (mode) {
  82794. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  82795. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  82796. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  82797. default:
  82798. BABYLON.Tools.Warn("Invalid texture wrap mode (" + mode + ")");
  82799. return BABYLON.Texture.WRAP_ADDRESSMODE;
  82800. }
  82801. };
  82802. GLTFLoader._GetTextureSamplingMode = function (magFilter, minFilter) {
  82803. // Set defaults if undefined
  82804. magFilter = magFilter == undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  82805. minFilter = minFilter == undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  82806. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  82807. switch (minFilter) {
  82808. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  82809. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  82810. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  82811. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  82812. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  82813. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  82814. default:
  82815. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  82816. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  82817. }
  82818. }
  82819. else {
  82820. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  82821. BABYLON.Tools.Warn("Invalid texture magnification filter (" + magFilter + ")");
  82822. }
  82823. switch (minFilter) {
  82824. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  82825. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  82826. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  82827. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  82828. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  82829. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  82830. default:
  82831. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  82832. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  82833. }
  82834. }
  82835. };
  82836. GLTFLoader._GetNumComponents = function (type) {
  82837. switch (type) {
  82838. case "SCALAR": return 1;
  82839. case "VEC2": return 2;
  82840. case "VEC3": return 3;
  82841. case "VEC4": return 4;
  82842. case "MAT2": return 4;
  82843. case "MAT3": return 9;
  82844. case "MAT4": return 16;
  82845. }
  82846. return 0;
  82847. };
  82848. GLTFLoader.prototype._compileMaterialAsync = function (babylonMaterial, babylonMesh, onSuccess) {
  82849. var _this = this;
  82850. if (!this._parent.compileMaterials) {
  82851. onSuccess();
  82852. return;
  82853. }
  82854. if (this._parent.useClipPlane) {
  82855. babylonMaterial.forceCompilation(babylonMesh, function () {
  82856. babylonMaterial.forceCompilation(babylonMesh, function () {
  82857. _this._tryCatchOnError(onSuccess);
  82858. }, { clipPlane: true });
  82859. });
  82860. }
  82861. else {
  82862. babylonMaterial.forceCompilation(babylonMesh, function () {
  82863. _this._tryCatchOnError(onSuccess);
  82864. });
  82865. }
  82866. };
  82867. GLTFLoader.prototype._compileMaterialsAsync = function (onSuccess) {
  82868. if (!this._parent.compileMaterials || !this._gltf.materials) {
  82869. onSuccess();
  82870. return;
  82871. }
  82872. var meshes = this._getMeshes();
  82873. var remaining = 0;
  82874. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  82875. var mesh = meshes_1[_i];
  82876. if (mesh.material instanceof BABYLON.MultiMaterial) {
  82877. for (var _a = 0, _b = mesh.material.subMaterials; _a < _b.length; _a++) {
  82878. var subMaterial = _b[_a];
  82879. if (subMaterial) {
  82880. remaining++;
  82881. }
  82882. }
  82883. }
  82884. else {
  82885. remaining++;
  82886. }
  82887. }
  82888. if (remaining === 0) {
  82889. onSuccess();
  82890. return;
  82891. }
  82892. for (var _c = 0, meshes_2 = meshes; _c < meshes_2.length; _c++) {
  82893. var mesh = meshes_2[_c];
  82894. if (mesh.material instanceof BABYLON.MultiMaterial) {
  82895. for (var _d = 0, _e = mesh.material.subMaterials; _d < _e.length; _d++) {
  82896. var subMaterial = _e[_d];
  82897. if (subMaterial) {
  82898. this._compileMaterialAsync(subMaterial, mesh, function () {
  82899. if (--remaining === 0) {
  82900. onSuccess();
  82901. }
  82902. });
  82903. }
  82904. }
  82905. }
  82906. else if (mesh.material !== null) {
  82907. this._compileMaterialAsync(mesh.material, mesh, function () {
  82908. if (--remaining === 0) {
  82909. onSuccess();
  82910. }
  82911. });
  82912. }
  82913. }
  82914. };
  82915. GLTFLoader.prototype._compileShadowGeneratorsAsync = function (onSuccess) {
  82916. var _this = this;
  82917. if (!this._parent.compileShadowGenerators) {
  82918. onSuccess();
  82919. return;
  82920. }
  82921. var lights = this._babylonScene.lights;
  82922. var remaining = 0;
  82923. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  82924. var light = lights_1[_i];
  82925. var generator = light.getShadowGenerator();
  82926. if (generator) {
  82927. remaining++;
  82928. }
  82929. }
  82930. if (remaining === 0) {
  82931. onSuccess();
  82932. return;
  82933. }
  82934. for (var _a = 0, lights_2 = lights; _a < lights_2.length; _a++) {
  82935. var light = lights_2[_a];
  82936. var generator = light.getShadowGenerator();
  82937. if (generator) {
  82938. generator.forceCompilation(function () {
  82939. if (--remaining === 0) {
  82940. _this._tryCatchOnError(onSuccess);
  82941. }
  82942. });
  82943. }
  82944. }
  82945. };
  82946. GLTFLoader.Extensions = {};
  82947. return GLTFLoader;
  82948. }());
  82949. GLTF2.GLTFLoader = GLTFLoader;
  82950. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  82951. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  82952. })(BABYLON || (BABYLON = {}));
  82953. //# sourceMappingURL=babylon.glTFLoader.js.map
  82954. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  82955. var BABYLON;
  82956. (function (BABYLON) {
  82957. var GLTF2;
  82958. (function (GLTF2) {
  82959. /**
  82960. * Utils functions for GLTF
  82961. */
  82962. var GLTFUtils = /** @class */ (function () {
  82963. function GLTFUtils() {
  82964. }
  82965. /**
  82966. * If the uri is a base64 string
  82967. * @param uri: the uri to test
  82968. */
  82969. GLTFUtils.IsBase64 = function (uri) {
  82970. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  82971. };
  82972. /**
  82973. * Decode the base64 uri
  82974. * @param uri: the uri to decode
  82975. */
  82976. GLTFUtils.DecodeBase64 = function (uri) {
  82977. var decodedString = atob(uri.split(",")[1]);
  82978. var bufferLength = decodedString.length;
  82979. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  82980. for (var i = 0; i < bufferLength; i++) {
  82981. bufferView[i] = decodedString.charCodeAt(i);
  82982. }
  82983. return bufferView.buffer;
  82984. };
  82985. GLTFUtils.ValidateUri = function (uri) {
  82986. return (uri.indexOf("..") === -1);
  82987. };
  82988. return GLTFUtils;
  82989. }());
  82990. GLTF2.GLTFUtils = GLTFUtils;
  82991. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  82992. })(BABYLON || (BABYLON = {}));
  82993. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  82994. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  82995. var BABYLON;
  82996. (function (BABYLON) {
  82997. var GLTF2;
  82998. (function (GLTF2) {
  82999. var GLTFLoaderExtension = /** @class */ (function () {
  83000. function GLTFLoaderExtension() {
  83001. this.enabled = true;
  83002. }
  83003. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  83004. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  83005. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  83006. GLTFLoaderExtension.prototype._loadExtension = function (context, property, action) {
  83007. var _this = this;
  83008. if (!property.extensions) {
  83009. return false;
  83010. }
  83011. var extension = property.extensions[this.name];
  83012. if (!extension) {
  83013. return false;
  83014. }
  83015. // Clear out the extension before executing the action to avoid recursing into the same property.
  83016. property.extensions[this.name] = undefined;
  83017. action(context + "extensions/" + this.name, extension, function () {
  83018. // Restore the extension after completing the action.
  83019. property.extensions[_this.name] = extension;
  83020. });
  83021. return true;
  83022. };
  83023. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  83024. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  83025. };
  83026. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  83027. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  83028. };
  83029. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  83030. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  83031. };
  83032. GLTFLoaderExtension._ApplyExtensions = function (action) {
  83033. var extensions = GLTFLoaderExtension._Extensions;
  83034. if (!extensions) {
  83035. return false;
  83036. }
  83037. for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
  83038. var extension = extensions_1[_i];
  83039. if (extension.enabled && action(extension)) {
  83040. return true;
  83041. }
  83042. }
  83043. return false;
  83044. };
  83045. //
  83046. // Utilities
  83047. //
  83048. GLTFLoaderExtension._Extensions = [];
  83049. return GLTFLoaderExtension;
  83050. }());
  83051. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  83052. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  83053. })(BABYLON || (BABYLON = {}));
  83054. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  83055. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  83056. var BABYLON;
  83057. (function (BABYLON) {
  83058. var GLTF2;
  83059. (function (GLTF2) {
  83060. var Extensions;
  83061. (function (Extensions) {
  83062. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  83063. var MSFTLOD = /** @class */ (function (_super) {
  83064. __extends(MSFTLOD, _super);
  83065. function MSFTLOD() {
  83066. var _this = _super !== null && _super.apply(this, arguments) || this;
  83067. /**
  83068. * Specify the minimal delay between LODs in ms (default = 250)
  83069. */
  83070. _this.Delay = 250;
  83071. return _this;
  83072. }
  83073. Object.defineProperty(MSFTLOD.prototype, "name", {
  83074. get: function () {
  83075. return "MSFT_lod";
  83076. },
  83077. enumerable: true,
  83078. configurable: true
  83079. });
  83080. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  83081. return this._loadExtension(context, node, function (context, extension, onComplete) {
  83082. for (var i = extension.ids.length - 1; i >= 0; i--) {
  83083. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, extension.ids[i]);
  83084. if (!lodNode) {
  83085. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  83086. }
  83087. loader._traverseNode(context, lodNode, action, parentNode);
  83088. }
  83089. loader._traverseNode(context, node, action, parentNode);
  83090. onComplete();
  83091. });
  83092. };
  83093. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  83094. var _this = this;
  83095. return this._loadExtension(context, node, function (context, extension, onComplete) {
  83096. var nodes = [node];
  83097. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  83098. var index = _a[_i];
  83099. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, index);
  83100. if (!lodNode) {
  83101. throw new Error(context + ": Failed to find node " + index);
  83102. }
  83103. nodes.push(lodNode);
  83104. }
  83105. loader._addLoaderPendingData(node);
  83106. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  83107. loader._removeLoaderPendingData(node);
  83108. onComplete();
  83109. });
  83110. });
  83111. };
  83112. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  83113. var _this = this;
  83114. loader._whenAction(function () {
  83115. loader._loadNode(context, nodes[index]);
  83116. }, function () {
  83117. if (index !== nodes.length - 1) {
  83118. var previousNode = nodes[index + 1];
  83119. previousNode.babylonMesh.setEnabled(false);
  83120. }
  83121. if (index === 0) {
  83122. onComplete();
  83123. return;
  83124. }
  83125. setTimeout(function () {
  83126. loader._tryCatchOnError(function () {
  83127. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  83128. });
  83129. }, _this.Delay);
  83130. });
  83131. };
  83132. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  83133. var _this = this;
  83134. return this._loadExtension(context, material, function (context, extension, onComplete) {
  83135. var materials = [material];
  83136. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  83137. var index = _a[_i];
  83138. var lodMaterial = GLTF2.GLTFLoader._GetProperty(loader._gltf.materials, index);
  83139. if (!lodMaterial) {
  83140. throw new Error(context + ": Failed to find material " + index);
  83141. }
  83142. materials.push(lodMaterial);
  83143. }
  83144. loader._addLoaderPendingData(material);
  83145. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  83146. loader._removeLoaderPendingData(material);
  83147. onComplete();
  83148. });
  83149. });
  83150. };
  83151. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  83152. var _this = this;
  83153. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  83154. if (index === materials.length - 1) {
  83155. assign(babylonMaterial, isNew);
  83156. // Load the next LOD when the loader is ready to render.
  83157. loader._executeWhenRenderReady(function () {
  83158. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  83159. });
  83160. }
  83161. else {
  83162. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  83163. assign(babylonMaterial, isNew);
  83164. if (index === 0) {
  83165. onComplete();
  83166. }
  83167. else {
  83168. setTimeout(function () {
  83169. loader._tryCatchOnError(function () {
  83170. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  83171. });
  83172. }, _this.Delay);
  83173. }
  83174. });
  83175. }
  83176. });
  83177. };
  83178. return MSFTLOD;
  83179. }(GLTF2.GLTFLoaderExtension));
  83180. Extensions.MSFTLOD = MSFTLOD;
  83181. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  83182. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  83183. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  83184. })(BABYLON || (BABYLON = {}));
  83185. //# sourceMappingURL=MSFT_lod.js.map
  83186. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  83187. var BABYLON;
  83188. (function (BABYLON) {
  83189. var GLTF2;
  83190. (function (GLTF2) {
  83191. var Extensions;
  83192. (function (Extensions) {
  83193. var KHRMaterialsPbrSpecularGlossiness = /** @class */ (function (_super) {
  83194. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  83195. function KHRMaterialsPbrSpecularGlossiness() {
  83196. return _super !== null && _super.apply(this, arguments) || this;
  83197. }
  83198. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  83199. get: function () {
  83200. return "KHR_materials_pbrSpecularGlossiness";
  83201. },
  83202. enumerable: true,
  83203. configurable: true
  83204. });
  83205. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  83206. var _this = this;
  83207. return this._loadExtension(context, material, function (context, extension, onComplete) {
  83208. loader._createPbrMaterial(material);
  83209. loader._loadMaterialBaseProperties(context, material);
  83210. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  83211. assign(material.babylonMaterial, true);
  83212. onComplete();
  83213. });
  83214. };
  83215. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  83216. var babylonMaterial = material.babylonMaterial;
  83217. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  83218. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  83219. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  83220. if (properties.diffuseTexture) {
  83221. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.diffuseTexture.index);
  83222. if (!texture) {
  83223. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  83224. }
  83225. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  83226. }
  83227. if (properties.specularGlossinessTexture) {
  83228. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.specularGlossinessTexture.index);
  83229. if (!texture) {
  83230. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  83231. }
  83232. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  83233. babylonMaterial.reflectivityTexture.hasAlpha = true;
  83234. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  83235. }
  83236. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  83237. };
  83238. return KHRMaterialsPbrSpecularGlossiness;
  83239. }(GLTF2.GLTFLoaderExtension));
  83240. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  83241. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  83242. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  83243. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  83244. })(BABYLON || (BABYLON = {}));
  83245. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  83246. (function universalModuleDefinition(root, factory) {
  83247. var f = factory();
  83248. if (root && root["BABYLON"]) {
  83249. return;
  83250. }
  83251. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  83252. globalObject["BABYLON"] = f;
  83253. if(typeof exports === 'object' && typeof module === 'object')
  83254. module.exports = f;
  83255. else if(typeof define === 'function' && define.amd)
  83256. define(["BABYLON"], factory);
  83257. else if(typeof exports === 'object')
  83258. exports["BABYLON"] = f;
  83259. else {
  83260. root["BABYLON"] = f;
  83261. }
  83262. })(this, function() {
  83263. return BABYLON;
  83264. });